{"id":18593105,"url":"https://github.com/embraser01/typoas","last_synced_at":"2025-04-06T16:11:38.838Z","repository":{"id":38890683,"uuid":"350501832","full_name":"Embraser01/typoas","owner":"Embraser01","description":"Open API (OAS 3.0) Typescript generator","archived":false,"fork":false,"pushed_at":"2025-02-12T09:48:38.000Z","size":315433,"stargazers_count":41,"open_issues_count":5,"forks_count":5,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-30T11:11:12.926Z","etag":null,"topics":["generator","nodejs","openapi","openapi-generator","openapi3","openapi31","react-query","swagger","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Embraser01.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-22T22:01:11.000Z","updated_at":"2025-02-12T09:43:48.000Z","dependencies_parsed_at":"2022-08-09T06:31:19.680Z","dependency_job_id":"cf5f2ed4-da1a-49c0-a5d8-b5a0e60ed599","html_url":"https://github.com/Embraser01/typoas","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Embraser01%2Ftypoas","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Embraser01%2Ftypoas/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Embraser01%2Ftypoas/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Embraser01%2Ftypoas/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Embraser01","download_url":"https://codeload.github.com/Embraser01/typoas/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247509222,"owners_count":20950232,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["generator","nodejs","openapi","openapi-generator","openapi3","openapi31","react-query","swagger","typescript"],"created_at":"2024-11-07T01:11:24.019Z","updated_at":"2025-04-06T16:11:38.815Z","avatar_url":"https://github.com/Embraser01.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Typoas\n\n![npm](https://img.shields.io/npm/v/@typoas/cli?label=cli%40npm)  \n![npm](https://img.shields.io/npm/v/@typoas/generator?label=generator%40npm)  \n![npm](https://img.shields.io/npm/v/@typoas/runtime?label=runtime%40npm)  \n![GitHub](https://img.shields.io/github/license/embraser01/typoas)  \n![npm bundle size](https://img.shields.io/bundlephobia/minzip/@typoas/runtime)\n\nTypoas is an OpenAPI 3.X generator for Typescript. It's inspired by [openapi-generator](https://openapi-generator.tech/)  \nbut is written in Typescript for Typescript. The generator uses the Typescript AST to generate code instead on relaying  \non templates which allows better schemas definitions and other cool stuff.\n\nMain features are:\n\n- Fully typed and fully customizable\n- References `$ref` handling (including cyclic refs)\n- **Tree Shaking** out of the box\n- **React Query** integration\n- Support for `allOf`, `oneOf` and `anyOf` schemas.\n- Automatically convert `format: 'date-time'` to JS `Date`\n- Handle **API Key**, **HTTP Config**, **OAuth2**\u003csup\u003e1\u003c/sup\u003e and **OIDC**\u003csup\u003e1\u003c/sup\u003e auth security schemes\n- JSDoc for schemas and operations\n- Override system for generated types\n- Uses `fetch` api (can be customized)\n- Non JSON content type support\n- Small bundle size\n- And more...\n\n\u003e \u003csup\u003e1\u003c/sup\u003e: OAuth2 and OpenIDConnect scheme do not handle flows to retrieve an `accessToken`.  \n\u003e You need to provide your own `accessToken` through the `provider.getConfig()` function.\n\nThe project is split into 4 packages:\n\n- [`@typoas/generator`](./packages/typoas-generator) is used to generate the API specific code.\n- [`@typoas/cli`](./packages/typoas-cli) is a CLI entry point built on top of `@typoas/generator`.\n- [`@typoas/runtime`](./packages/typoas-runtime) is the package that will be used by the generated code.\n- [`@typoas/react-query`](./packages/typoas-react-query) integrates _Typoas_ with [React Query](https://tanstack.com/query/latest).\n\n---\n\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Use the generator from the CLI](#use-the-generator-from-the-cli)\n  - [Use the generator from the API](#use-the-generator-from-the-api)\n  - [Use the generated code](#use-the-generated-code)\n    - [Customize server configuration](#customize-server-configuration)\n    - [Customize fetch implementation](#customize-fetch-implementation)\n    - [Handling authentification](#handling-authentification)\n    - [Customizing the serialization](#customizing-the-serialization)\n  - [Using with React Query](#using-with-react-query)\n- [Examples](#examples)\n- [Notes](#notes)\n  - [Overrides](#overrides)\n  - [External references](#external-references)\n  - [Parameters serialization](#parameters-serialization)\n  - [Migrating from v1 to v2](#migrating-from-v1-to-v2)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Installation\n\nIt will generate a single TS file containing all the code specific to the underlying API.  \nThis file only has a single dependency on `@typoas/runtime`.  \n**You need to manually** add `@typoas/runtime` to your `dependencies`.  \nIt handles common things like serialization/authentification\n\n## Usage\n\n### Use the generator from the CLI\n\nYou can generate the TS client from the spec from the command line:\n\n```bash\nyarn dlx @typoas/cli generate -i my-spec.json -o src/client.ts\nnpx @typoas/cli generate -i my-spec.json -o src/client.ts\n```\n\nHere is a short list of supported command line options:\n\n```\n    -i, --input [path/url]         Path or URL to the OpenAPI JSON specification (yaml/json format)\n    -o, --output [path]            Path where to write the generated TS file\n    -e,--generate-enums            Generate enums instead of literal string types where possible\n    -p,--prettier                  If set, the generated file will be formatted with Prettier\n    -r,--full-response-mode        Enabled by default, generate functions that only throws on network errors, can be disabled using --no-full-response-mode\n    --js-doc, --no-js-doc          Whether to add JS Doc to the generated code (default: true)\n    --wrap-lines-at                Define a maximum width for JS Doc comments, 0 to disable (default: 120)\n    --only-types                   Use it to only generate types in #components/schemas/\n    --no-fetcher-options           Use it to disable the additional param added to every operations\n    --override                     You can define a list of types that will be imported from a custom file instead of being generated. Must be used with --override-import\n    --override-import              Path to the file that will be imported to resolve overrides\n    --version                      Output the version number\n    -h, --help                     Display help for command\n```\n\nor you can use it in code:\n\n```ts\nimport cli from '@typoas/cli';\n\nawait cli.run(\n  [\n    'generate',\n    '-i',\n    'https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.yaml',\n    '-o',\n    `./src/github.ts`,\n  ],\n  {\n    stdin: process.stdin,\n    stdout: process.stdout,\n    stderr: process.stderr,\n  },\n);\n```\n\n### Use the generator from the API\n\n\u003e The API is still at an **alpha** stage, so it may break between minors.\n\nIt uses `typescript` API to generate usable code:\n\n```typescript\nimport { readFileSync, writeFileSync } from 'fs';\nimport { createPrinter, NewLineKind, SourceFile } from 'typescript';\nimport { generateClient, getStringFromSourceFile } from '@typoas/generator';\n\nconst specs = JSON.parse(readFileSync('path/to/github-openapi.json', 'utf8'));\nconst src = generateClient(specs, {\n  /* options */\n});\nconst data = getStringFromSourceFile(src);\n\nwriteFileSync('./src/client.ts', data, 'utf8');\n```\n\n### Use the generated code\n\nOnce the file is generated you'll be able to use it like this:\n\n```typescript\nimport { ServerConfiguration, ok } from '@typoas/runtime';\n// Client generated from:\n// yarn dlx @typoas/cli generate -i https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.yaml -o client.ts\nimport { createContext, pullsList } from './client';\n\nconst ctx = createContext();\n\n// By default, returns a StatusResponse that contains statusCode, data and headers.\nconst res = await pullsList(ctx, { repo: 'typoas', owner: 'embraser01' });\nif (res.ok) {\n  res.data.forEach((pr) =\u003e console.log(pr.title));\n}\n\n// An helper `ok` function can help throw on non 2xx status code and return the data\n// The second argument is an optional expected status code (useful when multiple success status code are possible)\nconst prs = await ok(\n  pullsList(ctx, { repo: 'typoas', owner: 'embraser01' }),\n  200,\n);\n```\n\n\u003e You can directly generate functions that throw on non 2xx status code by using the `--no-full-response-mode` option.\n\u003e This feature may be removed in the future and isn't the recommended way.\n\nYou can customize multiple things in the `createContext` function.\n\n#### Customize server configuration\n\nBy default, the `createContext` function will use the first `servers` entry in the spec.\nYou can override the server configuration by passing a `ServerConfiguration` object:\n\n```typescript\nimport { ServerConfiguration } from '@typoas/runtime';\nimport { createContext } from './client';\n\nconst ctx = createContext({\n  serverConfiguration: new ServerConfiguration(\n    'https://{env}.api.example.com',\n    {\n      env: 'staging',\n    },\n  ),\n});\n```\n\n\u003e The way it's done currently is not the best. It will be improved in the future.\n\n#### Customize fetch implementation\n\nThe default fetcher implementation [uses](./packages/typoas-runtime/src/fetcher/index.ts) the `fetch` API.\nYou can override the fetcher implementation if you want to customize things (like adding a retry policy, headers, etc.).\n\nFor example, you can use `axios` instead of the `fetch` API:\n\n```typescript\nimport axios, { AxiosError, AxiosResponse, Method } from 'axios';\nimport {\n  Fetcher,\n  RequestContext,\n  ResponseContext,\n  BaseFetcherData,\n} from '@typoas/runtime';\nimport { createContext } from './client';\n\nclass AxiosHttpLibrary implements Fetcher\u003cBaseFetcherData\u003e {\n  async send(request: RequestContext): Promise\u003cResponseContext\u003e {\n    let resp: AxiosResponse;\n    try {\n      resp = await axios.request({\n        url: request.getUrl(),\n        method: request.getHttpMethod() as Method,\n        headers: request.getHeaders(),\n        data: request.getBody(),\n      });\n    } catch (e) {\n      const err = e as AxiosError;\n      if (!err.response) {\n        throw e;\n      }\n      // Typoas handles errors itself\n      resp = err.response;\n    }\n\n    return new ResponseContext(resp.status, resp.headers, {\n      text: async () =\u003e resp.data as string,\n      binary: async () =\u003e resp.data as Blob,\n      json: async () =\u003e resp.data,\n    });\n  }\n}\n\nconst ctx = createContext({ fetcher: new AxiosHttpLibrary() });\n```\n\n\u003e Node.js \u003e= 18.0.0 includes the `fetch` implementation, so Typoas should work out of the box.\n\n#### Handling authentification\n\nThe `createContext` function can take an `authProviders` object to handle authentification.\n\nFor example, for the petstore sample:\n\n```typescript\nimport { createContext } from './petstore';\n\nconst ctx = createContext({\n  authProviders: {\n    api_key: {\n      async getConfig() {\n        return 'MyAPIKey';\n      },\n    },\n    petstore_auth: {\n      getConfig() {\n        const accessToken = globalStore.getAccessToken();\n\n        if (accessToken) {\n          return null;\n        }\n        return { accessToken };\n      },\n    },\n  },\n});\n```\n\nIt supports 5 types of security schemes:\n\n- `apiKey` mode\n- `http` bearer and basic mode\n- `oauth2` mode\n- `openIdConnect` mode\n\nThe `getConfig` function should return the configuration needed to authenticate the request. Returning `null` will skip the authentification.\n\n#### Customizing the serialization\n\nYou can switch some serialization options by passing a `serializerOptions` object to the `createContext` function.\n\n\u003e Not every serialization option is supported. See [#11](https://github.com/Embraser01/typoas/issues/11) for more information.\n\n### Using with React Query\n\nDocumentation is available in the [`@typoas/react-query`](./packages/typoas-react-query) package.\n\n## Examples\n\nYou can find examples in the [`examples`](./examples) folder.\n\n## Notes\n\nHere is some notes on some known issues.\n\n### Overrides\n\nSometimes you may want to override some of the generated types.\nFor example, Typoas will not generate Template Literal Types or Generics as it's hard to be defined in an OpenAPI spec.\n\nThis works by listing the types you want to override and giving the import path you want to use.\n\nFor example, if you want to override the PetStore `Category` type of your spec:\n\n```typescript\n// my-overrides.ts\nexport type Category = {\n  id?: number;\n  name?: string;\n  description?: string;\n};\n```\n\nWhen you generate the client, you can pass the `--overrides` option:\n\n```bash\nyarn dlx @typoas/cli generate -i my-spec.json -o src/client.ts --override-import my-overrides.ts --override Category\n```\n\nThis will not generate the `Category` type but import it from the `my-overrides.ts` file. This allows easy customization of generated types.\n\nThere are a couple of things to note:\n\n- The override name is the **sanitized** name of the type. You can first generate the client and see the generated types to know the name.\n- _Typoas_ will not check the override file. If the file isn't there or the type isn't exported, it will throw a TypeScript error.\n- You will have to export the type yourself, _Typoas_ will not do it for you (contrary to the generated types).\n\n### External references\n\nExternal references are not supported. Every `$ref` must be in the spec.  \nAn issue is open [here](https://github.com/Embraser01/typoas/issues/37).\n\n### Parameters serialization\n\n_Typoas_ has partial support for serialization specified here: https://swagger.io/docs/specification/serialization/\n\n- It **does** support array serialization for **query**.\n- It **does NOT** support serialization for **path** parameters with `style` `label` or `matrix`.\n- It **does NOT** support serialization for **query** parameters with nested objects. It will be JSON.stringify\n- It **does NOT** support serialization for **headers** or **cookie** parameters.\n\nOn query serialization, there can only be one style for a full operation. The first query param will set the style for  \nthe whole operation.\n\n### Migrating from v1 to v2\n\nIn v1, the whole API was generated in a single class. In V2 this was replaced by individual function  \nwhich allow [Tree Shaking](https://webpack.js.org/guides/tree-shaking/). To get a similar result,  \nyou can use `wrapApi` helper:\n\n```typescript\nimport { ServerConfiguration, wrapApi } from '@typoas/runtime';\nimport { createContext, pullsList, issuesList } from './client';\n\nconst ctx = createContext();\nconst ghClient = wrapApi(ctx, {\n  pullsList,\n  issuesList,\n  // ...\n});\n\nghClient\n  .pullsList(ctx, {\n    repo: 'typoas',\n    owner: 'embraser01',\n  })\n  .then((list) =\u003e console.log('List of PRs', list))\n  .catch((err) =\u003e console.error('Error while getting PRs', err));\n```\n\n## Contributing\n\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\n## License\n\n[MIT](https://choosealicense.com/licenses/mit/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fembraser01%2Ftypoas","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fembraser01%2Ftypoas","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fembraser01%2Ftypoas/lists"}