openapi-sync 4.0.2 → 5.0.1

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.mts 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,105 @@ 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?: {
284
+ disable?: boolean;
285
+ /** Include/exclude advanced filters for client generation */
286
+ include?: IConfigInclude;
287
+ exclude?: IConfigExclude;
288
+ };
289
+ };
290
+ /** Configuration for SWR hooks */
291
+ swr?: {
292
+ /** Enable SWR mutation hooks (default: true) */
293
+ mutations?: boolean;
294
+ infiniteQueries?: {
295
+ disable?: boolean;
296
+ /** Include/exclude advanced filters for client generation */
297
+ include?: IConfigInclude;
298
+ exclude?: IConfigExclude;
299
+ };
300
+ };
301
+ /** Configuration for RTK Query */
302
+ rtkQuery?: {
303
+ /** API slice name */
304
+ apiName?: string;
305
+ /** Base query type */
306
+ baseQuery?: "fetchBaseQuery" | "axiosBaseQuery";
307
+ infiniteQueries?: {
308
+ disable?: boolean;
309
+ /** Include/exclude advanced filters for client generation */
310
+ include?: IConfigInclude;
311
+ exclude?: IConfigExclude;
312
+ };
313
+ };
314
+ /** Include authentication/authorization setup */
315
+ auth?: {
316
+ /** Auth type */
317
+ type?: "bearer" | "apiKey" | "basic" | "oauth2";
318
+ /** Where to include auth token */
319
+ in?: "header" | "query" | "cookie";
320
+ /** Header/query param name for auth */
321
+ name?: string;
322
+ };
323
+ /** Error handling configuration */
324
+ errorHandling?: {
325
+ /** Generate typed error classes */
326
+ generateErrorClasses?: boolean;
327
+ /** Custom error handler function name */
328
+ customHandler?: string;
329
+ };
330
+ };
331
+ /**
332
+ * Main OpenAPI Sync configuration
333
+ *
334
+ * The root configuration object for openapi-sync. Defines API sources,
335
+ * output settings, code generation options, and all feature configurations.
336
+ * Used in openapi.sync.ts, openapi.sync.js, or openapi.sync.json files.
337
+ *
338
+ * @public
339
+ */
137
340
  type IConfig = {
138
341
  refetchInterval?: number;
139
342
  folder?: string;
@@ -145,6 +348,8 @@ type IConfig = {
145
348
  customCode?: IConfigCustomCode;
146
349
  /** Configuration for validation schema generation */
147
350
  validations?: IConfigValidations;
351
+ /** Configuration for API client generation */
352
+ clientGeneration?: IConfigClientGeneration;
148
353
  /** Configuration for excluding endpoints from code generation */
149
354
  types?: {
150
355
  name?: {
@@ -183,6 +388,15 @@ type IConfig = {
183
388
  include?: IConfigInclude;
184
389
  };
185
390
  };
391
+ /**
392
+ * OpenAPI Security Schemes
393
+ *
394
+ * Defines security schemes available in an OpenAPI specification.
395
+ * Supports various authentication methods including HTTP, API keys,
396
+ * OAuth2, OpenID Connect, and mutual TLS.
397
+ *
398
+ * @public
399
+ */
186
400
  type IOpenApiSecuritySchemes = {
187
401
  [key: string]: {
188
402
  type: "http" | "apiKey" | "oauth2" | "openIdConnect" | "mutualTLS";
@@ -203,17 +417,110 @@ type IOpenApiSecuritySchemes = {
203
417
  };
204
418
  };
205
419
 
420
+ /**
421
+ * Check if a value is a JSON object
422
+ *
423
+ * @param {any} value - Value to check
424
+ * @returns {boolean} True if the value is an object and not a Blob
425
+ *
426
+ * @public
427
+ */
206
428
  declare const isJson: (value: any) => boolean;
429
+ /**
430
+ * Check if a string is valid YAML
431
+ *
432
+ * Attempts to parse the string as YAML and returns true if successful.
433
+ *
434
+ * @param {string} fileContent - String content to check
435
+ * @returns {boolean} True if the string can be parsed as YAML
436
+ *
437
+ * @public
438
+ */
207
439
  declare const isYamlString: (fileContent: string) => boolean;
440
+ /**
441
+ * Convert YAML string to JSON object
442
+ *
443
+ * Parses a YAML string and returns a JSON object representation.
444
+ * Returns undefined if the string is not valid YAML.
445
+ *
446
+ * @param {string} fileContent - YAML string content
447
+ * @returns {any | undefined} Parsed JSON object, or undefined if invalid YAML
448
+ *
449
+ * @public
450
+ */
208
451
  declare const yamlStringToJson: (fileContent: string) => any;
452
+ /**
453
+ * Capitalize the first letter of a string
454
+ *
455
+ * @param {string} text - Text to capitalize
456
+ * @returns {string} Text with first letter capitalized
457
+ *
458
+ * @public
459
+ */
209
460
  declare const capitalize: (text: string) => string;
461
+ /**
462
+ * Extract endpoint details from path and method
463
+ *
464
+ * Parses an API path to generate a function name and extract path variables.
465
+ * Handles multiple path variable formats: {id}, <id>, and :id.
466
+ *
467
+ * @param {string} path - API endpoint path (e.g., "/users/{userId}/posts")
468
+ * @param {string} method - HTTP method (GET, POST, etc.)
469
+ * @returns {{ name: string; variables: string[]; pathParts: string[] }} Object containing generated name, path variables, and path parts
470
+ *
471
+ * @example
472
+ * getEndpointDetails("/users/{userId}", "GET")
473
+ * // Returns: { name: "GetUsers$userId", variables: ["userId"], pathParts: [...] }
474
+ *
475
+ * @public
476
+ */
210
477
  declare const getEndpointDetails: (path: string, method: string) => {
211
478
  name: string;
212
479
  variables: string[];
213
480
  pathParts: string[];
214
481
  };
482
+ /**
483
+ * Convert object to formatted TypeScript string
484
+ *
485
+ * Creates a human-readable TypeScript object representation with proper indentation.
486
+ * Used for generating type definitions in generated code.
487
+ *
488
+ * @param {Record<string, any>} obj - Object to stringify
489
+ * @param {number} [indent=1] - Current indentation level
490
+ * @returns {string} Formatted TypeScript object string
491
+ *
492
+ * @public
493
+ */
215
494
  declare const JSONStringify: (obj: Record<string, any>, indent?: number) => string;
495
+ /**
496
+ * Render TypeScript type reference as markdown code block
497
+ *
498
+ * Formats a TypeScript type definition for inclusion in markdown documentation.
499
+ *
500
+ * @param {string} typeRef - TypeScript type definition
501
+ * @param {number} [indent=1] - Indentation level
502
+ * @returns {string} Markdown formatted code block
503
+ *
504
+ * @public
505
+ */
216
506
  declare const renderTypeRefMD: (typeRef: string, indent?: number) => string;
507
+ /**
508
+ * Get nested value from object using dot notation path
509
+ *
510
+ * Safely retrieves a deeply nested value from an object using a string path.
511
+ * Returns undefined if the path doesn't exist.
512
+ *
513
+ * @template T - Type of the expected return value
514
+ * @param {object} obj - Object to navigate
515
+ * @param {string} path - Dot-notation path (e.g., "user.address.city")
516
+ * @returns {T | undefined} The value at the path, or undefined if not found
517
+ *
518
+ * @example
519
+ * getNestedValue<string>({ user: { name: "John" } }, "user.name")
520
+ * // Returns: "John"
521
+ *
522
+ * @public
523
+ */
217
524
  declare function getNestedValue<T>(obj: object, path: string): T | undefined;
218
525
  interface ExtractedCustomCode {
219
526
  beforeGenerated: string;
@@ -221,25 +528,48 @@ interface ExtractedCustomCode {
221
528
  }
222
529
  /**
223
530
  * 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
531
+ *
532
+ * Scans an existing file for custom code blocks marked with special comments
533
+ * and extracts them for preservation during regeneration.
534
+ *
535
+ * @param {string} fileContent - The content of the existing file
536
+ * @param {string} [markerText="CUSTOM CODE"] - The marker text to look for
537
+ * @returns {ExtractedCustomCode} Object containing custom code sections before and after generated code
538
+ *
539
+ * @public
227
540
  */
228
541
  declare const extractCustomCode: (fileContent: string, markerText?: string) => ExtractedCustomCode;
229
542
  /**
230
543
  * 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
544
+ *
545
+ * Generates the comment markers that delineate custom code sections in
546
+ * generated files. These markers tell the regeneration process where
547
+ * user-added code should be preserved.
548
+ *
549
+ * @param {"top" | "bottom"} position - Position of the marker in the file
550
+ * @param {string} [markerText="CUSTOM CODE"] - The marker text to use
551
+ * @param {boolean} [includeInstructions=true] - Whether to include helpful instructions
552
+ * @returns {string} The marker section as a string
553
+ *
554
+ * @public
235
555
  */
236
556
  declare const createCustomCodeMarker: (position: "top" | "bottom", markerText?: string, includeInstructions?: boolean) => string;
237
557
  /**
238
558
  * 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
559
+ *
560
+ * The core function for custom code preservation. Extracts custom code from
561
+ * existing files and merges it with newly generated content, ensuring user
562
+ * modifications survive regeneration.
563
+ *
564
+ * @param {string} generatedContent - The newly generated content
565
+ * @param {string | null} existingFileContent - The existing file content (null if file doesn't exist)
566
+ * @param {Object} [config] - Configuration options
567
+ * @param {"top" | "bottom" | "both"} [config.position="bottom"] - Where to place custom code markers
568
+ * @param {string} [config.markerText="CUSTOM CODE"] - Custom marker text
569
+ * @param {boolean} [config.includeInstructions=true] - Whether to include helpful instructions
570
+ * @returns {string} The merged content with custom code preserved
571
+ *
572
+ * @public
243
573
  */
244
574
  declare const mergeCustomCode: (generatedContent: string, existingFileContent: string | null, config?: {
245
575
  position?: "top" | "bottom" | "both";
@@ -250,8 +580,92 @@ declare const mergeCustomCode: (generatedContent: string, existingFileContent: s
250
580
  declare const variableName: RegExp;
251
581
  declare const variableNameChar: RegExp;
252
582
 
583
+ /**
584
+ * Initialize and sync all OpenAPI specifications
585
+ *
586
+ * This is the main entry point for the OpenAPI sync process. It loads the configuration,
587
+ * resets the state, and syncs all configured APIs to generate types, endpoints, and validations.
588
+ *
589
+ * @param {Object} [options] - Optional configuration
590
+ * @param {number} [options.refetchInterval] - Interval in milliseconds to automatically refetch specifications
591
+ * @returns {Promise<void>}
592
+ * @throws {Error} When configuration is not found or sync fails
593
+ *
594
+ * @example
595
+ * // Sync once
596
+ * await Init();
597
+ *
598
+ * @example
599
+ * // Sync with auto-refresh every 10 seconds
600
+ * await Init({ refetchInterval: 10000 });
601
+ *
602
+ * @public
603
+ */
253
604
  declare const Init: (options?: {
254
605
  refetchInterval?: number;
255
606
  }) => Promise<void>;
607
+ /**
608
+ * Generate API client from OpenAPI specification
609
+ *
610
+ * Generates type-safe API clients based on OpenAPI specifications. Supports multiple
611
+ * client types including Fetch, Axios, React Query, SWR, and RTK Query. Can filter
612
+ * endpoints by tags or specific endpoint names.
613
+ *
614
+ * @param {Object} options - Client generation options
615
+ * @param {"fetch" | "axios" | "react-query" | "swr" | "rtk-query"} options.type - Type of client to generate
616
+ * @param {string} [options.apiName] - Specific API name to generate client for (generates for all if not specified)
617
+ * @param {string[]} [options.tags] - Filter endpoints by OpenAPI tags
618
+ * @param {string[]} [options.endpoints] - Filter by specific endpoint operation IDs
619
+ * @param {string} [options.outputDir] - Custom output directory for generated client
620
+ * @param {string} [options.baseURL] - Base URL for API requests
621
+ * @returns {Promise<void>}
622
+ * @throws {Error} When API name is not found in configuration or sync fails
623
+ *
624
+ * @example
625
+ * // Generate Axios client for all APIs
626
+ * await GenerateClient({ type: "axios" });
627
+ *
628
+ * @example
629
+ * // Generate React Query hooks for a specific API
630
+ * await GenerateClient({
631
+ * type: "react-query",
632
+ * apiName: "petstore",
633
+ * baseURL: "https://api.example.com"
634
+ * });
635
+ *
636
+ * @example
637
+ * // Generate SWR hooks for specific endpoints
638
+ * await GenerateClient({
639
+ * type: "swr",
640
+ * endpoints: ["getPetById", "createPet"]
641
+ * });
642
+ *
643
+ * @public
644
+ */
645
+ declare const GenerateClient: (options: {
646
+ type: "fetch" | "axios" | "react-query" | "swr" | "rtk-query";
647
+ apiName?: string;
648
+ tags?: string[];
649
+ endpoints?: string[];
650
+ outputDir?: string;
651
+ baseURL?: string;
652
+ }) => Promise<void>;
653
+ /**
654
+ * Interactive CLI wizard to create configuration
655
+ *
656
+ * Launches an interactive command-line wizard that guides users through
657
+ * creating an openapi.sync configuration file. Prompts for API URLs,
658
+ * output directories, client generation preferences, and more.
659
+ *
660
+ * @returns {Promise<void>}
661
+ * @throws {Error} When wizard is cancelled or configuration creation fails
662
+ *
663
+ * @example
664
+ * // Run the interactive setup wizard
665
+ * await InteractiveInit();
666
+ *
667
+ * @public
668
+ */
669
+ declare const InteractiveInit: () => Promise<void>;
256
670
 
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 };
671
+ 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 };