openapi-sync 4.0.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,19 +4,31 @@
4
4
 
5
5
  # OpenAPI Sync
6
6
 
7
- **OpenAPI Sync** is a powerful developer tool that automates the synchronization of your API documentation with your codebase using OpenAPI (formerly Swagger) specifications. It generates TypeScript types, endpoint definitions, runtime validation schemas (Zod, Yup, Joi), and comprehensive documentation from your OpenAPI schema—ensuring type safety from API specification to runtime validation.
7
+ **OpenAPI Sync** is a powerful developer tool that automates the synchronization of your API documentation with your codebase using OpenAPI (formerly Swagger) specifications. It generates TypeScript types, fully-typed API clients (Fetch, Axios, React Query, SWR, RTK Query), endpoint definitions, runtime validation schemas (Zod, Yup, Joi), and comprehensive documentation from your OpenAPI schema—ensuring type safety from API specification through client implementation to runtime validation.
8
8
 
9
9
  > 📘 **[Full documentation available at openapi-sync.com](https://openapi-sync.com)**
10
10
 
11
11
  ## Features
12
12
 
13
- - 🔄 **Real-time API Synchronization** - Automatically syncs OpenAPI specs from remote URLs
14
- - 📝 **Automatic Type Generation** - Generates TypeScript interfaces for all endpoints
15
- - 🔧 **Highly Configurable** - Customizable naming, filtering, and folder organization
16
- - 🛡️ **Enterprise Ready** - Error handling, validation, and state persistence
17
- - 🔐 **Runtime Validation** - Generate Zod, Yup, or Joi schemas from OpenAPI specs
18
- - 📚 **Rich Documentation** - JSDoc comments with cURL examples
19
- - 🔄 **Custom Code Injection** - Preserve your custom code between regenerations
13
+ ### 🎉 v5.0.0 - Enhanced Client Generation & Developer Experience
14
+
15
+ - 🚀 **Fully-Typed API Client Generation** - Generate type-safe clients for Fetch, Axios, React Query, SWR, and RTK Query with comprehensive inline documentation
16
+ - **RTK Query Simplified Setup** - New `setupApiStore` helper reduces Redux configuration from ~15 lines to ~5 lines
17
+ - **Perfect TypeScript Support** - Fixed SWR mutation types, ESLint-compliant Fetch clients, and unique RTK Query reducer paths
18
+ - 🎨 **Better File Organization** - Streamlined non-folder-split mode with `clients.ts` and `hooks.ts` directly at root
19
+ - 🔧 **CLI Improvements** - Arguments now correctly override config file settings as expected
20
+ - 📚 **230+ Lines of SWR Documentation** - Every generated hooks file includes comprehensive usage examples
21
+
22
+ ### Core Features
23
+
24
+ - 🔄 **Real-time API Synchronization** - Automatically syncs OpenAPI specs from remote URLs with configurable intervals
25
+ - 📝 **Automatic Type Generation** - Generates TypeScript interfaces for all endpoints with full nested support
26
+ - 🔐 **Runtime Validation** - Generate Zod, Yup, or Joi schemas from OpenAPI specs with all constraints preserved
27
+ - 🎯 **Interactive Setup Wizard** - Streamlined configuration with auto-enabled tag-based folder splitting
28
+ - 🛡️ **Enterprise Ready** - Error handling, validation, state persistence, and custom code preservation
29
+ - 📦 **Folder Splitting** - Organize code by tags or custom logic with aggregator files for easy imports
30
+ - 📚 **Rich Documentation** - JSDoc comments with cURL examples and inline usage guides
31
+ - 🔄 **Custom Code Injection** - Preserve your custom code between regenerations with protected sections
20
32
 
21
33
  [View all features →](https://openapi-sync.com/docs#features)
22
34
 
@@ -32,6 +44,28 @@ npx openapi-sync
32
44
 
33
45
  ## Quick Start
34
46
 
47
+ ### Option 1: Interactive Setup (Recommended) 🎯
48
+
49
+ The easiest way to get started is with the interactive setup wizard:
50
+
51
+ ```bash
52
+ npx openapi-sync init
53
+ ```
54
+
55
+ The wizard will guide you through:
56
+
57
+ - 📝 Configuration file format selection (TypeScript, JSON, or JavaScript)
58
+ - 🌐 API specification source (URL or local file)
59
+ - 📁 Folder organization options (split by tags or custom logic)
60
+ - 🚀 Client generation options (React Query, SWR, Fetch, Axios, RTK Query)
61
+ - ✅ Validation library setup (Zod, Yup, Joi)
62
+ - 🔧 Custom code preservation settings
63
+ - 🏷️ Type naming preferences (operationId usage, prefix)
64
+ - 🚫 Endpoint filtering (exclude by tags)
65
+ - 📚 Documentation options (cURL examples)
66
+
67
+ ### Option 2: Manual Setup
68
+
35
69
  **1. Create `openapi.sync.json` in your project root:**
36
70
 
37
71
  ```json
@@ -61,6 +95,139 @@ const petUrl = getPetById("123"); // Returns: "/pet/123"
61
95
 
62
96
  [View detailed quick start guide →](https://openapi-sync.com/docs#quick-start)
63
97
 
98
+ ## API Client Generation
99
+
100
+ Generate fully-typed API clients with hooks for popular libraries:
101
+
102
+ ### Generate Fetch Client
103
+
104
+ ```bash
105
+ npx openapi-sync generate-client --type fetch
106
+ ```
107
+
108
+ ### Generate Axios Client
109
+
110
+ ```bash
111
+ npx openapi-sync generate-client --type axios
112
+ ```
113
+
114
+ ### Generate React Query Hooks
115
+
116
+ ```bash
117
+ npx openapi-sync generate-client --type react-query --api petstore
118
+ ```
119
+
120
+ ### Generate SWR Hooks
121
+
122
+ ```bash
123
+ npx openapi-sync generate-client --type swr
124
+ ```
125
+
126
+ ### Generate RTK Query API
127
+
128
+ ```bash
129
+ npx openapi-sync generate-client --type rtk-query
130
+ ```
131
+
132
+ ### Filter by Tags or Endpoints
133
+
134
+ ```bash
135
+ # Filter by tags
136
+ npx openapi-sync generate-client --type fetch --tags pets,users
137
+
138
+ # Filter by specific endpoints
139
+ npx openapi-sync generate-client --type axios --endpoints getPetById,createPet
140
+ ```
141
+
142
+ ### Usage Example (React Query)
143
+
144
+ **1. Generate the client:**
145
+
146
+ ```bash
147
+ npx openapi-sync generate-client --type react-query
148
+ ```
149
+
150
+ **2. Use in your React components:**
151
+
152
+ ```typescript
153
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
154
+ import { useGetPetById, useCreatePet } from "./api/petstore/client/hooks";
155
+ import apiClient from "./api/petstore/client/client";
156
+
157
+ // Configure API client
158
+ apiClient.updateConfig({
159
+ baseURL: "https://api.example.com",
160
+ });
161
+ apiClient.setAuthToken("your-auth-token");
162
+
163
+ function PetDetails({ petId }: { petId: string }) {
164
+ // Query hook for GET requests with structured params
165
+ const { data, isLoading, error } = useGetPetById({
166
+ url: { petId }, // Path parameters
167
+ query: { includeOwner: true }, // Query parameters (if any)
168
+ });
169
+
170
+ // Mutation hook for POST/PUT/PATCH/DELETE requests
171
+ const createPet = useCreatePet({
172
+ onSuccess: () => {
173
+ console.log("Pet created!");
174
+ },
175
+ });
176
+
177
+ const handleCreate = () => {
178
+ createPet.mutate({
179
+ data: {
180
+ // Request body
181
+ name: "Fluffy",
182
+ species: "cat",
183
+ },
184
+ });
185
+ };
186
+
187
+ if (isLoading) return <div>Loading...</div>;
188
+ if (error) return <div>Error: {error.message}</div>;
189
+
190
+ return (
191
+ <div>
192
+ <h1>{data?.name}</h1>
193
+ <button onClick={handleCreate}>Create New Pet</button>
194
+ </div>
195
+ );
196
+ }
197
+ ```
198
+
199
+ ### Client Generation Options
200
+
201
+ | Option | Description | Example |
202
+ | ----------------- | ------------------------ | --------------------------------------------------- |
203
+ | `--type, -t` | Client type to generate | `fetch`, `axios`, `react-query`, `swr`, `rtk-query` |
204
+ | `--api, -a` | Specific API from config | `--api petstore` |
205
+ | `--tags` | Filter by endpoint tags | `--tags pets,users` |
206
+ | `--endpoints, -e` | Filter by endpoint names | `--endpoints getPetById,createPet` |
207
+ | `--output, -o` | Output directory | `--output ./src/clients` |
208
+ | `--base-url, -b` | Base URL for requests | `--base-url https://api.example.com` |
209
+
210
+ ### Custom Code Preservation
211
+
212
+ Generated clients support custom code sections that are preserved during regeneration:
213
+
214
+ ```typescript
215
+ // client.ts (Generated)
216
+
217
+ // ============================================================
218
+ // 🔒 CUSTOM CODE START
219
+ // Add your custom code below this line
220
+ // This section will be preserved during regeneration
221
+ // ============================================================
222
+
223
+ // Your custom helper functions, middleware, etc.
224
+
225
+ // 🔒 CUSTOM CODE END
226
+ // ============================================================
227
+ ```
228
+
229
+ [View complete client generation guide →](https://openapi-sync.com/docs#client-generation)
230
+
64
231
  ## Configuration
65
232
 
66
233
  Supports multiple configuration formats: `openapi.sync.json`, `openapi.sync.ts`, or `openapi.sync.js`
@@ -102,6 +269,56 @@ export default config;
102
269
 
103
270
  [View full configuration options →](https://openapi-sync.com/docs#configuration)
104
271
 
272
+ ## CLI Commands
273
+
274
+ ### Interactive Setup
275
+
276
+ ```bash
277
+ npx openapi-sync init
278
+ ```
279
+
280
+ Launch an interactive wizard that guides you through creating your configuration file. Perfect for first-time setup or exploring available options.
281
+
282
+ ### Sync API Types
283
+
284
+ ```bash
285
+ # Sync with default config
286
+ npx openapi-sync
287
+
288
+ # Sync with custom refetch interval
289
+ npx openapi-sync --refreshinterval 10000
290
+ ```
291
+
292
+ Synchronize your OpenAPI specifications and generate TypeScript types, endpoints, and validation schemas.
293
+
294
+ ### Generate API Client
295
+
296
+ ```bash
297
+ # Generate React Query hooks
298
+ npx openapi-sync generate-client --type react-query
299
+
300
+ # Generate for specific API
301
+ npx openapi-sync generate-client --type axios --api petstore
302
+
303
+ # Generate with filters
304
+ npx openapi-sync generate-client --type fetch --tags pets,users
305
+
306
+ # Generate for specific endpoints
307
+ npx openapi-sync generate-client --type swr --endpoints getPetById,createPet
308
+ ```
309
+
310
+ Generate fully-typed API clients for various frameworks and libraries.
311
+
312
+ ### Available Options
313
+
314
+ | Command | Description |
315
+ | ----------------- | ------------------------------------- |
316
+ | `init` | Interactive setup wizard |
317
+ | `sync` (default) | Sync OpenAPI specs and generate types |
318
+ | `generate-client` | Generate API client code |
319
+ | `--help, -h` | Show help information |
320
+ | `--version, -v` | Show version number |
321
+
105
322
  ## Documentation
106
323
 
107
324
  For complete documentation including:
package/bin/cli.js CHANGED
@@ -5,17 +5,110 @@ const OpenApisync = require("../dist/index");
5
5
  const yargs = require("yargs/yargs");
6
6
  const { hideBin } = require("yargs/helpers");
7
7
 
8
- // Setup yargs
8
+ // Setup yargs with commands
9
9
  const argv = yargs(hideBin(process.argv))
10
- .usage("Usage: $0 [options]")
11
- .option("refreshinterval", {
12
- alias: "ri",
13
- type: "number",
14
- description: "Interval at which to refetch specifiations",
15
- })
16
- .help().argv;
10
+ .command(
11
+ "init",
12
+ "Interactive setup wizard to create configuration",
13
+ () => {},
14
+ async () => {
15
+ await OpenApisync.InteractiveInit();
16
+ }
17
+ )
18
+ .command(
19
+ ["$0", "sync"],
20
+ "Sync OpenAPI specifications and generate types",
21
+ (yargs) => {
22
+ return yargs.option("refreshinterval", {
23
+ alias: "ri",
24
+ type: "number",
25
+ description: "Interval at which to refetch specifications",
26
+ });
27
+ },
28
+ (argv) => {
29
+ OpenApisync.Init({
30
+ refetchInterval: argv.refreshinterval,
31
+ });
32
+ }
33
+ )
34
+ .command(
35
+ "generate-client",
36
+ "Generate API client from OpenAPI specification",
37
+ (yargs) => {
38
+ return yargs
39
+ .option("type", {
40
+ alias: "t",
41
+ type: "string",
42
+ description: "Client type to generate",
43
+ choices: ["fetch", "axios", "react-query", "swr", "rtk-query"],
44
+ demandOption: true,
45
+ })
46
+ .option("api", {
47
+ alias: "a",
48
+ type: "string",
49
+ description:
50
+ "API name from config (generates for all APIs if not specified)",
51
+ })
52
+ .option("tags", {
53
+ type: "array",
54
+ description: "Filter endpoints by tags",
55
+ })
56
+ .option("endpoints", {
57
+ alias: "e",
58
+ type: "array",
59
+ description: "Filter by specific endpoint names",
60
+ })
61
+ .option("output", {
62
+ alias: "o",
63
+ type: "string",
64
+ description: "Output directory for generated client",
65
+ })
66
+ .option("base-url", {
67
+ alias: "b",
68
+ type: "string",
69
+ description: "Base URL for API requests",
70
+ })
71
+ .example(
72
+ "$0 generate-client --type fetch",
73
+ "Generate fetch client for all APIs"
74
+ )
75
+ .example(
76
+ "$0 generate-client --type react-query --api petstore",
77
+ "Generate React Query hooks for petstore API"
78
+ )
79
+ .example(
80
+ "$0 generate-client --type axios --tags pets,users",
81
+ "Generate axios client for endpoints with pets or users tags"
82
+ )
83
+ .example(
84
+ "$0 generate-client --type swr --endpoints getPetById,createPet",
85
+ "Generate SWR hooks for specific endpoints"
86
+ );
87
+ },
88
+ async (argv) => {
89
+ // First, sync API specs and generate types/endpoints
90
+ console.log("🔄 Syncing API specifications first...\n");
91
+ await OpenApisync.Init();
17
92
 
18
- // Use the flags
19
- OpenApisync.Init({
20
- refetchInterval: argv.refreshinterval,
21
- });
93
+ console.log("\n🚀 Now generating client...\n");
94
+
95
+ // Then generate the client
96
+ await OpenApisync.GenerateClient({
97
+ type: argv.type,
98
+ apiName: argv.api,
99
+ tags: argv.tags,
100
+ endpoints: argv.endpoints,
101
+ outputDir: argv.output,
102
+ baseURL: argv["base-url"],
103
+ });
104
+ }
105
+ )
106
+ .example("$0 init", "Start interactive setup wizard")
107
+ .example("$0", "Sync API types and endpoints")
108
+ .example("$0 --refreshinterval 10000", "Sync with 10s refresh interval")
109
+ .help()
110
+ .alias("help", "h")
111
+ .version()
112
+ .alias("version", "v")
113
+ .demandCommand(1, "You need to specify a command")
114
+ .strict().argv;
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty,n=Object.defineProperties;var o=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var p=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var i=(b,c,a)=>c in b?m(b,c,{enumerable:true,configurable:true,writable:true,value:a}):b[c]=a,r=(b,c)=>{for(var a in c||(c={}))p.call(c,a)&&i(b,a,c[a]);if(h)for(var a of h(c))q.call(c,a)&&i(b,a,c[a]);return b},s=(b,c)=>n(b,o(c));var t=(b=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(b,{get:(c,a)=>(typeof require!="undefined"?require:c)[a]}):b)(function(b){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+b+'" is not supported')});var u=(b,c,a)=>new Promise((j,g)=>{var k=d=>{try{e(a.next(d));}catch(f){g(f);}},l=d=>{try{e(a.throw(d));}catch(f){g(f);}},e=d=>d.done?j(d.value):Promise.resolve(d.value).then(k,l);e((a=a.apply(b,c)).next());});export{r as a,s as b,t as c,u as d};