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/dist/index.d.ts CHANGED
@@ -1,6 +1,24 @@
1
1
  import { Method } from 'axios';
2
2
 
3
+ /**
4
+ * OpenAPI Specification document type
5
+ *
6
+ * Represents a complete OpenAPI specification object with the required
7
+ * "openapi" version field and any additional specification properties.
8
+ *
9
+ * @public
10
+ */
3
11
  type IOpenApiSpec = Record<"openapi", string> & Record<string, any>;
12
+ /**
13
+ * OpenAPI Schema Specification
14
+ *
15
+ * Represents a schema object as defined in the OpenAPI Specification.
16
+ * Includes all standard JSON Schema properties plus OpenAPI extensions.
17
+ * Supports validation constraints, composition keywords (anyOf, oneOf, allOf),
18
+ * and references.
19
+ *
20
+ * @public
21
+ */
4
22
  type IOpenApSchemaSpec = {
5
23
  nullable?: boolean;
6
24
  type: "string" | "integer" | "number" | "array" | "object" | "boolean" | "null" | any[];
@@ -30,6 +48,14 @@ type IOpenApSchemaSpec = {
30
48
  minProperties?: number;
31
49
  maxProperties?: number;
32
50
  };
51
+ /**
52
+ * OpenAPI Parameter Specification
53
+ *
54
+ * Represents a parameter object in an OpenAPI operation. Can describe
55
+ * path, query, header, or cookie parameters with validation and examples.
56
+ *
57
+ * @public
58
+ */
33
59
  type IOpenApiParameterSpec = {
34
60
  $ref?: string;
35
61
  name: string;
@@ -46,27 +72,73 @@ type IOpenApiParameterSpec = {
46
72
  example?: any;
47
73
  examples?: any[];
48
74
  };
75
+ /**
76
+ * OpenAPI Media Type Specification
77
+ *
78
+ * Represents a media type object for request/response bodies.
79
+ * Includes schema definitions and examples for specific content types.
80
+ *
81
+ * @public
82
+ */
49
83
  type IOpenApiMediaTypeSpec = {
50
84
  schema?: IOpenApSchemaSpec;
51
85
  example?: any;
52
86
  examples?: any[];
53
87
  encoding?: any;
54
88
  };
89
+ /**
90
+ * OpenAPI Request Body Specification
91
+ *
92
+ * Represents a request body object with content types and schemas.
93
+ * Maps content types (e.g., "application/json") to their specifications.
94
+ *
95
+ * @public
96
+ */
55
97
  type IOpenApiRequestBodySpec = {
56
98
  description?: string;
57
99
  required?: boolean;
58
100
  content: Record<string, IOpenApiMediaTypeSpec>;
59
101
  };
102
+ /**
103
+ * OpenAPI Response Specification
104
+ *
105
+ * Maps HTTP status codes to their response specifications.
106
+ *
107
+ * @public
108
+ */
60
109
  type IOpenApiResponseSpec = Record<string, IOpenApiRequestBodySpec>;
110
+ /**
111
+ * Configuration for word/pattern replacement in generated names
112
+ *
113
+ * Allows find-and-replace operations on generated type names and endpoint names.
114
+ * Supports regular expressions for pattern matching.
115
+ *
116
+ * @public
117
+ */
61
118
  type IConfigReplaceWord = {
62
119
  /** string and regular expression as a string*/
63
120
  replace: string;
64
121
  with: string;
65
122
  };
123
+ /**
124
+ * Configuration for documentation generation
125
+ *
126
+ * Controls whether documentation is generated and what features are included.
127
+ *
128
+ * @public
129
+ */
66
130
  type IConfigDoc = {
67
131
  disable?: boolean;
68
132
  showCurl?: boolean;
69
133
  };
134
+ /**
135
+ * Configuration for excluding endpoints from generation
136
+ *
137
+ * Allows filtering out specific endpoints by tags or path/method combinations.
138
+ * Supports regex patterns for flexible matching.
139
+ *
140
+ * @public
141
+ */
70
142
  type IConfigExclude = {
71
143
  /** Exclude/Include endpoints by tags */
72
144
  tags?: string[];
@@ -80,8 +152,24 @@ type IConfigExclude = {
80
152
  method?: Method;
81
153
  }>;
82
154
  };
155
+ /**
156
+ * Configuration for including endpoints in generation
157
+ *
158
+ * Mirror of IConfigExclude but used for explicit inclusion filtering.
159
+ * When specified, only matching endpoints will be generated.
160
+ *
161
+ * @public
162
+ */
83
163
  interface IConfigInclude extends IConfigExclude {
84
164
  }
165
+ /**
166
+ * Configuration for folder splitting
167
+ *
168
+ * Controls how generated files are organized into folders.
169
+ * Can split by OpenAPI tags or use custom logic.
170
+ *
171
+ * @public
172
+ */
85
173
  type IConfigFolderSplit = {
86
174
  /** Split folders by tags - creates folders named after each tag */
87
175
  byTags?: boolean;
@@ -97,6 +185,14 @@ type IConfigFolderSplit = {
97
185
  responses?: IOpenApiResponseSpec;
98
186
  }) => string | null;
99
187
  };
188
+ /**
189
+ * Configuration for custom code preservation
190
+ *
191
+ * Controls how custom code sections are handled during regeneration.
192
+ * Allows users to add code that won't be overwritten when files are regenerated.
193
+ *
194
+ * @public
195
+ */
100
196
  type IConfigCustomCode = {
101
197
  /** Enable custom code preservation (default: true) */
102
198
  enabled?: boolean;
@@ -107,6 +203,14 @@ type IConfigCustomCode = {
107
203
  /** Add helpful instructions in markers (default: true) */
108
204
  includeInstructions?: boolean;
109
205
  };
206
+ /**
207
+ * Configuration for validation schema generation
208
+ *
209
+ * Controls generation of runtime validation schemas using Zod, Yup, or Joi.
210
+ * Allows selective generation for query parameters and request bodies.
211
+ *
212
+ * @public
213
+ */
110
214
  type IConfigValidations = {
111
215
  /** Disable validation schema generation (default: false) */
112
216
  disable?: boolean;
@@ -134,6 +238,88 @@ type IConfigValidations = {
134
238
  }, defaultName: string) => string | null | undefined;
135
239
  };
136
240
  };
241
+ /**
242
+ * Configuration for API client generation
243
+ *
244
+ * Controls generation of type-safe API clients including Fetch, Axios,
245
+ * React Query hooks, SWR hooks, and RTK Query slices. Supports filtering,
246
+ * custom naming, and framework-specific options.
247
+ *
248
+ * @public
249
+ */
250
+ type IConfigClientGeneration = {
251
+ /** Enable client generation (default: false) */
252
+ enabled?: boolean;
253
+ /** Client type to generate */
254
+ type?: "fetch" | "axios" | "react-query" | "swr" | "rtk-query";
255
+ /** Output directory for generated clients */
256
+ outputDir?: string;
257
+ /** Base URL for API requests (can be overridden at runtime) */
258
+ baseURL?: string;
259
+ /** Filter endpoints by tags */
260
+ tags?: string[];
261
+ /** Filter endpoints by endpoint names */
262
+ endpoints?: string[];
263
+ /** Naming configuration for client functions */
264
+ name?: {
265
+ prefix?: string;
266
+ suffix?: string;
267
+ useOperationId?: boolean;
268
+ format?: (data: {
269
+ method: Method;
270
+ path: string;
271
+ summary?: string;
272
+ operationId?: string;
273
+ tags?: string[];
274
+ }, defaultName: string) => string | null | undefined;
275
+ };
276
+ /** Configuration for React Query hooks */
277
+ reactQuery?: {
278
+ /** Version of React Query (default: 5) */
279
+ version?: 4 | 5;
280
+ /** Enable mutation hooks for POST/PUT/PATCH/DELETE (default: true) */
281
+ mutations?: boolean;
282
+ /** Enable infinite query hooks for paginated endpoints (default: false) */
283
+ infiniteQueries?: boolean;
284
+ };
285
+ /** Configuration for SWR hooks */
286
+ swr?: {
287
+ /** Enable SWR mutation hooks (default: true) */
288
+ mutations?: boolean;
289
+ };
290
+ /** Configuration for RTK Query */
291
+ rtkQuery?: {
292
+ /** API slice name */
293
+ apiName?: string;
294
+ /** Base query type */
295
+ baseQuery?: "fetchBaseQuery" | "axiosBaseQuery";
296
+ };
297
+ /** Include authentication/authorization setup */
298
+ auth?: {
299
+ /** Auth type */
300
+ type?: "bearer" | "apiKey" | "basic" | "oauth2";
301
+ /** Where to include auth token */
302
+ in?: "header" | "query" | "cookie";
303
+ /** Header/query param name for auth */
304
+ name?: string;
305
+ };
306
+ /** Error handling configuration */
307
+ errorHandling?: {
308
+ /** Generate typed error classes */
309
+ generateErrorClasses?: boolean;
310
+ /** Custom error handler function name */
311
+ customHandler?: string;
312
+ };
313
+ };
314
+ /**
315
+ * Main OpenAPI Sync configuration
316
+ *
317
+ * The root configuration object for openapi-sync. Defines API sources,
318
+ * output settings, code generation options, and all feature configurations.
319
+ * Used in openapi.sync.ts, openapi.sync.js, or openapi.sync.json files.
320
+ *
321
+ * @public
322
+ */
137
323
  type IConfig = {
138
324
  refetchInterval?: number;
139
325
  folder?: string;
@@ -145,6 +331,8 @@ type IConfig = {
145
331
  customCode?: IConfigCustomCode;
146
332
  /** Configuration for validation schema generation */
147
333
  validations?: IConfigValidations;
334
+ /** Configuration for API client generation */
335
+ clientGeneration?: IConfigClientGeneration;
148
336
  /** Configuration for excluding endpoints from code generation */
149
337
  types?: {
150
338
  name?: {
@@ -183,6 +371,15 @@ type IConfig = {
183
371
  include?: IConfigInclude;
184
372
  };
185
373
  };
374
+ /**
375
+ * OpenAPI Security Schemes
376
+ *
377
+ * Defines security schemes available in an OpenAPI specification.
378
+ * Supports various authentication methods including HTTP, API keys,
379
+ * OAuth2, OpenID Connect, and mutual TLS.
380
+ *
381
+ * @public
382
+ */
186
383
  type IOpenApiSecuritySchemes = {
187
384
  [key: string]: {
188
385
  type: "http" | "apiKey" | "oauth2" | "openIdConnect" | "mutualTLS";
@@ -203,17 +400,110 @@ type IOpenApiSecuritySchemes = {
203
400
  };
204
401
  };
205
402
 
403
+ /**
404
+ * Check if a value is a JSON object
405
+ *
406
+ * @param {any} value - Value to check
407
+ * @returns {boolean} True if the value is an object and not a Blob
408
+ *
409
+ * @public
410
+ */
206
411
  declare const isJson: (value: any) => boolean;
412
+ /**
413
+ * Check if a string is valid YAML
414
+ *
415
+ * Attempts to parse the string as YAML and returns true if successful.
416
+ *
417
+ * @param {string} fileContent - String content to check
418
+ * @returns {boolean} True if the string can be parsed as YAML
419
+ *
420
+ * @public
421
+ */
207
422
  declare const isYamlString: (fileContent: string) => boolean;
423
+ /**
424
+ * Convert YAML string to JSON object
425
+ *
426
+ * Parses a YAML string and returns a JSON object representation.
427
+ * Returns undefined if the string is not valid YAML.
428
+ *
429
+ * @param {string} fileContent - YAML string content
430
+ * @returns {any | undefined} Parsed JSON object, or undefined if invalid YAML
431
+ *
432
+ * @public
433
+ */
208
434
  declare const yamlStringToJson: (fileContent: string) => any;
435
+ /**
436
+ * Capitalize the first letter of a string
437
+ *
438
+ * @param {string} text - Text to capitalize
439
+ * @returns {string} Text with first letter capitalized
440
+ *
441
+ * @public
442
+ */
209
443
  declare const capitalize: (text: string) => string;
444
+ /**
445
+ * Extract endpoint details from path and method
446
+ *
447
+ * Parses an API path to generate a function name and extract path variables.
448
+ * Handles multiple path variable formats: {id}, <id>, and :id.
449
+ *
450
+ * @param {string} path - API endpoint path (e.g., "/users/{userId}/posts")
451
+ * @param {string} method - HTTP method (GET, POST, etc.)
452
+ * @returns {{ name: string; variables: string[]; pathParts: string[] }} Object containing generated name, path variables, and path parts
453
+ *
454
+ * @example
455
+ * getEndpointDetails("/users/{userId}", "GET")
456
+ * // Returns: { name: "GetUsers$userId", variables: ["userId"], pathParts: [...] }
457
+ *
458
+ * @public
459
+ */
210
460
  declare const getEndpointDetails: (path: string, method: string) => {
211
461
  name: string;
212
462
  variables: string[];
213
463
  pathParts: string[];
214
464
  };
465
+ /**
466
+ * Convert object to formatted TypeScript string
467
+ *
468
+ * Creates a human-readable TypeScript object representation with proper indentation.
469
+ * Used for generating type definitions in generated code.
470
+ *
471
+ * @param {Record<string, any>} obj - Object to stringify
472
+ * @param {number} [indent=1] - Current indentation level
473
+ * @returns {string} Formatted TypeScript object string
474
+ *
475
+ * @public
476
+ */
215
477
  declare const JSONStringify: (obj: Record<string, any>, indent?: number) => string;
478
+ /**
479
+ * Render TypeScript type reference as markdown code block
480
+ *
481
+ * Formats a TypeScript type definition for inclusion in markdown documentation.
482
+ *
483
+ * @param {string} typeRef - TypeScript type definition
484
+ * @param {number} [indent=1] - Indentation level
485
+ * @returns {string} Markdown formatted code block
486
+ *
487
+ * @public
488
+ */
216
489
  declare const renderTypeRefMD: (typeRef: string, indent?: number) => string;
490
+ /**
491
+ * Get nested value from object using dot notation path
492
+ *
493
+ * Safely retrieves a deeply nested value from an object using a string path.
494
+ * Returns undefined if the path doesn't exist.
495
+ *
496
+ * @template T - Type of the expected return value
497
+ * @param {object} obj - Object to navigate
498
+ * @param {string} path - Dot-notation path (e.g., "user.address.city")
499
+ * @returns {T | undefined} The value at the path, or undefined if not found
500
+ *
501
+ * @example
502
+ * getNestedValue<string>({ user: { name: "John" } }, "user.name")
503
+ * // Returns: "John"
504
+ *
505
+ * @public
506
+ */
217
507
  declare function getNestedValue<T>(obj: object, path: string): T | undefined;
218
508
  interface ExtractedCustomCode {
219
509
  beforeGenerated: string;
@@ -221,25 +511,48 @@ interface ExtractedCustomCode {
221
511
  }
222
512
  /**
223
513
  * Extract custom code from existing file using comment markers
224
- * @param fileContent - The content of the existing file
225
- * @param markerText - The marker text to look for (default: "CUSTOM CODE")
226
- * @returns Object containing custom code sections before and after generated code
514
+ *
515
+ * Scans an existing file for custom code blocks marked with special comments
516
+ * and extracts them for preservation during regeneration.
517
+ *
518
+ * @param {string} fileContent - The content of the existing file
519
+ * @param {string} [markerText="CUSTOM CODE"] - The marker text to look for
520
+ * @returns {ExtractedCustomCode} Object containing custom code sections before and after generated code
521
+ *
522
+ * @public
227
523
  */
228
524
  declare const extractCustomCode: (fileContent: string, markerText?: string) => ExtractedCustomCode;
229
525
  /**
230
526
  * Create an empty custom code marker section
231
- * @param position - Position of the marker ("top" or "bottom")
232
- * @param markerText - The marker text (default: "CUSTOM CODE")
233
- * @param includeInstructions - Whether to include helpful instructions
234
- * @returns The marker section as a string
527
+ *
528
+ * Generates the comment markers that delineate custom code sections in
529
+ * generated files. These markers tell the regeneration process where
530
+ * user-added code should be preserved.
531
+ *
532
+ * @param {"top" | "bottom"} position - Position of the marker in the file
533
+ * @param {string} [markerText="CUSTOM CODE"] - The marker text to use
534
+ * @param {boolean} [includeInstructions=true] - Whether to include helpful instructions
535
+ * @returns {string} The marker section as a string
536
+ *
537
+ * @public
235
538
  */
236
539
  declare const createCustomCodeMarker: (position: "top" | "bottom", markerText?: string, includeInstructions?: boolean) => string;
237
540
  /**
238
541
  * Merge generated content with preserved custom code
239
- * @param generatedContent - The newly generated content
240
- * @param existingFileContent - The existing file content (null if file doesn't exist)
241
- * @param config - Configuration options
242
- * @returns The merged content with custom code preserved
542
+ *
543
+ * The core function for custom code preservation. Extracts custom code from
544
+ * existing files and merges it with newly generated content, ensuring user
545
+ * modifications survive regeneration.
546
+ *
547
+ * @param {string} generatedContent - The newly generated content
548
+ * @param {string | null} existingFileContent - The existing file content (null if file doesn't exist)
549
+ * @param {Object} [config] - Configuration options
550
+ * @param {"top" | "bottom" | "both"} [config.position="bottom"] - Where to place custom code markers
551
+ * @param {string} [config.markerText="CUSTOM CODE"] - Custom marker text
552
+ * @param {boolean} [config.includeInstructions=true] - Whether to include helpful instructions
553
+ * @returns {string} The merged content with custom code preserved
554
+ *
555
+ * @public
243
556
  */
244
557
  declare const mergeCustomCode: (generatedContent: string, existingFileContent: string | null, config?: {
245
558
  position?: "top" | "bottom" | "both";
@@ -250,8 +563,92 @@ declare const mergeCustomCode: (generatedContent: string, existingFileContent: s
250
563
  declare const variableName: RegExp;
251
564
  declare const variableNameChar: RegExp;
252
565
 
566
+ /**
567
+ * Initialize and sync all OpenAPI specifications
568
+ *
569
+ * This is the main entry point for the OpenAPI sync process. It loads the configuration,
570
+ * resets the state, and syncs all configured APIs to generate types, endpoints, and validations.
571
+ *
572
+ * @param {Object} [options] - Optional configuration
573
+ * @param {number} [options.refetchInterval] - Interval in milliseconds to automatically refetch specifications
574
+ * @returns {Promise<void>}
575
+ * @throws {Error} When configuration is not found or sync fails
576
+ *
577
+ * @example
578
+ * // Sync once
579
+ * await Init();
580
+ *
581
+ * @example
582
+ * // Sync with auto-refresh every 10 seconds
583
+ * await Init({ refetchInterval: 10000 });
584
+ *
585
+ * @public
586
+ */
253
587
  declare const Init: (options?: {
254
588
  refetchInterval?: number;
255
589
  }) => Promise<void>;
590
+ /**
591
+ * Generate API client from OpenAPI specification
592
+ *
593
+ * Generates type-safe API clients based on OpenAPI specifications. Supports multiple
594
+ * client types including Fetch, Axios, React Query, SWR, and RTK Query. Can filter
595
+ * endpoints by tags or specific endpoint names.
596
+ *
597
+ * @param {Object} options - Client generation options
598
+ * @param {"fetch" | "axios" | "react-query" | "swr" | "rtk-query"} options.type - Type of client to generate
599
+ * @param {string} [options.apiName] - Specific API name to generate client for (generates for all if not specified)
600
+ * @param {string[]} [options.tags] - Filter endpoints by OpenAPI tags
601
+ * @param {string[]} [options.endpoints] - Filter by specific endpoint operation IDs
602
+ * @param {string} [options.outputDir] - Custom output directory for generated client
603
+ * @param {string} [options.baseURL] - Base URL for API requests
604
+ * @returns {Promise<void>}
605
+ * @throws {Error} When API name is not found in configuration or sync fails
606
+ *
607
+ * @example
608
+ * // Generate Axios client for all APIs
609
+ * await GenerateClient({ type: "axios" });
610
+ *
611
+ * @example
612
+ * // Generate React Query hooks for a specific API
613
+ * await GenerateClient({
614
+ * type: "react-query",
615
+ * apiName: "petstore",
616
+ * baseURL: "https://api.example.com"
617
+ * });
618
+ *
619
+ * @example
620
+ * // Generate SWR hooks for specific endpoints
621
+ * await GenerateClient({
622
+ * type: "swr",
623
+ * endpoints: ["getPetById", "createPet"]
624
+ * });
625
+ *
626
+ * @public
627
+ */
628
+ declare const GenerateClient: (options: {
629
+ type: "fetch" | "axios" | "react-query" | "swr" | "rtk-query";
630
+ apiName?: string;
631
+ tags?: string[];
632
+ endpoints?: string[];
633
+ outputDir?: string;
634
+ baseURL?: string;
635
+ }) => Promise<void>;
636
+ /**
637
+ * Interactive CLI wizard to create configuration
638
+ *
639
+ * Launches an interactive command-line wizard that guides users through
640
+ * creating an openapi.sync configuration file. Prompts for API URLs,
641
+ * output directories, client generation preferences, and more.
642
+ *
643
+ * @returns {Promise<void>}
644
+ * @throws {Error} When wizard is cancelled or configuration creation fails
645
+ *
646
+ * @example
647
+ * // Run the interactive setup wizard
648
+ * await InteractiveInit();
649
+ *
650
+ * @public
651
+ */
652
+ declare const InteractiveInit: () => Promise<void>;
256
653
 
257
- export { type ExtractedCustomCode, type IConfig, type IConfigCustomCode, type IConfigDoc, type IConfigExclude, type IConfigFolderSplit, type IConfigInclude, type IConfigReplaceWord, type IConfigValidations, type IOpenApSchemaSpec, type IOpenApiMediaTypeSpec, type IOpenApiParameterSpec, type IOpenApiRequestBodySpec, type IOpenApiResponseSpec, type IOpenApiSecuritySchemes, type IOpenApiSpec, Init, JSONStringify, capitalize, createCustomCodeMarker, extractCustomCode, getEndpointDetails, getNestedValue, isJson, isYamlString, mergeCustomCode, renderTypeRefMD, variableName, variableNameChar, yamlStringToJson };
654
+ export { type ExtractedCustomCode, GenerateClient, type IConfig, type IConfigClientGeneration, type IConfigCustomCode, type IConfigDoc, type IConfigExclude, type IConfigFolderSplit, type IConfigInclude, type IConfigReplaceWord, type IConfigValidations, type IOpenApSchemaSpec, type IOpenApiMediaTypeSpec, type IOpenApiParameterSpec, type IOpenApiRequestBodySpec, type IOpenApiResponseSpec, type IOpenApiSecuritySchemes, type IOpenApiSpec, Init, InteractiveInit, JSONStringify, capitalize, createCustomCodeMarker, extractCustomCode, getEndpointDetails, getNestedValue, isJson, isYamlString, mergeCustomCode, renderTypeRefMD, variableName, variableNameChar, yamlStringToJson };