@cerios/openapi-to-zod 1.4.0 → 1.5.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.
@@ -1,470 +0,0 @@
1
- import { E as ExecutionMode, e as OpenAPISchema, f as OpenAPISpec, g as OperationFilters, b as OpenAPIParameter, c as OpenAPIRequestBody, d as OpenAPIResponse } from './types-DZ4Bw-D5.js';
2
- import { z } from 'zod';
3
- import { Loader } from 'cosmiconfig';
4
-
5
- /**
6
- * @shared Generator interface for batch execution
7
- * @since 1.0.0
8
- * Interface that both OpenApiGenerator and OpenApiPlaywrightGenerator must implement
9
- */
10
- interface Generator {
11
- generate(): void;
12
- }
13
- /**
14
- * Result of processing a single spec
15
- */
16
- interface SpecResult<T> {
17
- spec: T;
18
- success: boolean;
19
- error?: string;
20
- }
21
- /**
22
- * Summary of batch execution results
23
- */
24
- interface BatchExecutionSummary<T> {
25
- total: number;
26
- successful: number;
27
- failed: number;
28
- results: SpecResult<T>[];
29
- }
30
- /**
31
- * @shared Execute batch processing of multiple specs with custom generator
32
- * @since 1.0.0
33
- * Utility used by core and playwright packages
34
- *
35
- * @param specs - Array of spec configurations to process
36
- * @param executionMode - Execution mode: "parallel" (default) or "sequential"
37
- * @param createGenerator - Factory function to create generator from spec
38
- * @param batchSize - Number of specifications to process concurrently in parallel mode
39
- * @returns BatchExecutionSummary with results
40
- * @throws Never throws - collects all errors and reports them
41
- */
42
- declare function executeBatch<T>(specs: T[], executionMode: ExecutionMode | undefined, createGenerator: (spec: T) => Generator, batchSize: number): Promise<BatchExecutionSummary<T>>;
43
- /**
44
- * Determine exit code based on batch execution results
45
- * Returns 1 if any spec failed, 0 if all succeeded
46
- */
47
- declare function getBatchExitCode<T>(summary: BatchExecutionSummary<T>): number;
48
-
49
- /**
50
- * @shared Simple LRU Cache implementation for performance optimization
51
- * @since 1.0.0
52
- * Utility used by core and playwright packages
53
- * Prevents memory leaks from unbounded cache growth
54
- */
55
- declare class LRUCache<K, V> {
56
- private cache;
57
- private maxSize;
58
- constructor(maxSize: number);
59
- get capacity(): number;
60
- get(key: K): V | undefined;
61
- set(key: K, value: V): void;
62
- has(key: K): boolean;
63
- clear(): void;
64
- size(): number;
65
- }
66
-
67
- /**
68
- * Name conversion utilities
69
- */
70
- interface NamingOptions {
71
- prefix?: string;
72
- suffix?: string;
73
- }
74
- /**
75
- * Convert schema name to camelCase with optional prefix/suffix
76
- * Handles dotted names like "Company.Models.User" -> "companyModelsUser"
77
- */
78
- declare function toCamelCase(str: string, options?: NamingOptions): string;
79
- /**
80
- * @shared Convert enum value to PascalCase and sanitize for TypeScript enum keys
81
- * @since 1.0.0
82
- * Utility used by core and playwright packages
83
- * Handles dotted names like "Company.Models.User" -> "CompanyModelsUser"
84
- */
85
- declare function toPascalCase(str: string | number): string;
86
-
87
- type ObjectMode = "strict" | "normal" | "loose";
88
-
89
- interface PropertyGeneratorContext {
90
- spec: OpenAPISpec;
91
- schemaDependencies: Map<string, Set<string>>;
92
- schemaType: "all" | "request" | "response";
93
- mode: ObjectMode;
94
- includeDescriptions: boolean;
95
- useDescribe: boolean;
96
- namingOptions: NamingOptions;
97
- stripSchemaPrefix?: string;
98
- /**
99
- * Default nullable behavior when not explicitly specified
100
- * @default false
101
- */
102
- defaultNullable: boolean;
103
- /**
104
- * Behavior for empty object schemas (objects with no properties defined)
105
- * @default 'loose'
106
- */
107
- emptyObjectBehavior: "strict" | "loose" | "record";
108
- /**
109
- * Zod validation string for date-time format fields
110
- * @default "z.iso.datetime()"
111
- */
112
- dateTimeValidation: string;
113
- /**
114
- * Instance-level cache for escaped regex patterns (parallel-safe)
115
- */
116
- patternCache: LRUCache<string, string>;
117
- }
118
- /**
119
- * Property schema generator with memoization for performance
120
- */
121
- declare class PropertyGenerator {
122
- private context;
123
- private filteredPropsCache;
124
- private schemaCache;
125
- static readonly INCLUSION_RULES: {
126
- readonly request: (schema: OpenAPISchema) => boolean;
127
- readonly response: (schema: OpenAPISchema) => boolean;
128
- readonly all: () => boolean;
129
- };
130
- constructor(context: PropertyGeneratorContext);
131
- /**
132
- * Check if a property should be included based on schemaType and readOnly/writeOnly flags
133
- */
134
- shouldIncludeProperty(schema: OpenAPISchema): boolean;
135
- /**
136
- * Recursively filter any schema type (helper for composition schemas)
137
- */
138
- private filterSchemaRecursive;
139
- /**
140
- * Recursively filter properties in nested objects based on readOnly/writeOnly
141
- * Performance optimized with memoization
142
- */
143
- private filterNestedProperties;
144
- /**
145
- * Resolve discriminator mapping to actual schema references
146
- */
147
- private resolveDiscriminatorMapping;
148
- /**
149
- * Resolve a $ref string to the actual schema
150
- */
151
- private resolveSchemaRef;
152
- /**
153
- * Resolve a schema name through any aliases to get the actual schema name
154
- * If the schema is an alias (allOf with single $ref), return the target name
155
- */
156
- private resolveSchemaAlias;
157
- /**
158
- * Check if this is a circular dependency through aliases
159
- */
160
- private isCircularThroughAlias;
161
- /**
162
- * Generate union for multiple types (OpenAPI 3.1)
163
- */
164
- private generateMultiTypeUnion;
165
- /**
166
- * Apply unevaluatedProperties validation to a schema
167
- */
168
- private applyUnevaluatedProperties;
169
- /**
170
- * Generate Zod schema for a property
171
- * @param schema - The OpenAPI schema to generate
172
- * @param currentSchema - The name of the current schema being processed (for circular ref detection)
173
- * @param isTopLevel - Whether this is a top-level schema definition
174
- * @param suppressDefaultNullable - When true, don't apply defaultNullable (used when outer schema has explicit nullable: false)
175
- */
176
- generatePropertySchema(schema: OpenAPISchema, currentSchema?: string, isTopLevel?: boolean, suppressDefaultNullable?: boolean): string;
177
- /**
178
- * Generate inline object shape for use with .extend()
179
- * Returns just the shape object literal: { prop1: z.string(), prop2: z.number() }
180
- *
181
- * This method is specifically for allOf compositions where we need to pass
182
- * the shape directly to .extend() instead of using z.object({...}).shape.
183
- * This avoids the .nullable().shape bug when inline objects have nullable: true.
184
- *
185
- * According to Zod docs (https://zod.dev/api?id=extend):
186
- * - .extend() accepts an object of shape definitions
187
- * - e.g., baseSchema.extend({ prop: z.string() })
188
- */
189
- generateInlineObjectShape(schema: OpenAPISchema, currentSchema?: string): string;
190
- }
191
-
192
- /**
193
- * @shared Zod schema for request/response options validation
194
- * @since 1.0.0
195
- * Utility used by core and playwright packages
196
- */
197
- declare const RequestResponseOptionsSchema: z.ZodObject<{
198
- mode: z.ZodOptional<z.ZodEnum<{
199
- strict: "strict";
200
- normal: "normal";
201
- loose: "loose";
202
- }>>;
203
- useDescribe: z.ZodOptional<z.ZodBoolean>;
204
- includeDescriptions: z.ZodOptional<z.ZodBoolean>;
205
- defaultNullable: z.ZodOptional<z.ZodBoolean>;
206
- emptyObjectBehavior: z.ZodOptional<z.ZodEnum<{
207
- strict: "strict";
208
- loose: "loose";
209
- record: "record";
210
- }>>;
211
- }, z.core.$strict>;
212
- /**
213
- * @shared Base Zod schema for operation filters (without status codes)
214
- * @since 1.0.0
215
- * Utility used by core and playwright packages
216
- */
217
- declare const OperationFiltersSchema: z.ZodObject<{
218
- includeTags: z.ZodOptional<z.ZodArray<z.ZodString>>;
219
- excludeTags: z.ZodOptional<z.ZodArray<z.ZodString>>;
220
- includePaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
221
- excludePaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
222
- includeMethods: z.ZodOptional<z.ZodArray<z.ZodString>>;
223
- excludeMethods: z.ZodOptional<z.ZodArray<z.ZodString>>;
224
- includeOperationIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
225
- excludeOperationIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
226
- excludeDeprecated: z.ZodOptional<z.ZodBoolean>;
227
- }, z.core.$strict>;
228
- /**
229
- * Inferred TypeScript type for request/response options
230
- */
231
- type RequestResponseOptions = z.infer<typeof RequestResponseOptionsSchema>;
232
- /**
233
- * Inferred TypeScript type for base operation filters
234
- */
235
- type BaseOperationFilters = z.infer<typeof OperationFiltersSchema>;
236
-
237
- /**
238
- * @shared Format Zod validation errors into user-friendly error messages
239
- * @since 1.0.0
240
- * Utility used by core and playwright packages
241
- *
242
- * @param error - The Zod validation error
243
- * @param filepath - Path to the config file that was being validated
244
- * @param configPath - Optional explicit config path provided by user
245
- * @param additionalNotes - Optional array of additional notes to append to the error message
246
- * @returns Formatted error message string
247
- */
248
- declare function formatConfigValidationError(error: z.ZodError, filepath: string | undefined, configPath: string | undefined, additionalNotes?: string[]): string;
249
-
250
- /**
251
- * Content type utilities for determining response parsing methods
252
- */
253
- /**
254
- * Result of content type analysis
255
- */
256
- interface ContentTypeParseResult {
257
- /**
258
- * The recommended parsing method
259
- * - "json": Use response.json() for JSON content types
260
- * - "text": Use response.text() for text-based content types
261
- * - "body": Use response.body() for binary content types
262
- */
263
- method: "json" | "text" | "body";
264
- /**
265
- * Whether the content type was unknown and fallback was used
266
- */
267
- isUnknown: boolean;
268
- }
269
- /**
270
- * Fallback parsing method for unknown content types
271
- */
272
- type FallbackContentTypeParsing = "json" | "text" | "body";
273
- /**
274
- * Determines the appropriate response parsing method based on content type
275
- *
276
- * Categories:
277
- * - JSON: application/json, text/json, *+json suffix
278
- * - Text: text/* (except text/json), application/xml, *+xml suffix, application/javascript
279
- * - Binary: image/*, audio/*, video/*, font/*, application/octet-stream, application/pdf, etc.
280
- *
281
- * @param contentType - The content type to analyze (e.g., "application/json; charset=utf-8")
282
- * @param fallback - The method to use for unknown content types (default: "text" for safety)
283
- * @returns The recommended parsing method and whether the content type was unknown
284
- */
285
- declare function getResponseParseMethod(contentType: string | undefined, fallback?: FallbackContentTypeParsing): ContentTypeParseResult;
286
-
287
- /**
288
- * Filter statistics to track which operations were included/excluded
289
- */
290
- interface FilterStatistics {
291
- totalOperations: number;
292
- includedOperations: number;
293
- filteredByTags: number;
294
- filteredByPaths: number;
295
- filteredByMethods: number;
296
- filteredByOperationIds: number;
297
- filteredByDeprecated: number;
298
- }
299
- /**
300
- * Create a new filter statistics object with all counters initialized to zero
301
- */
302
- declare function createFilterStatistics(): FilterStatistics;
303
- /**
304
- * Determine if an operation should be included based on filter criteria
305
- *
306
- * Filter logic:
307
- * 1. If no filters specified, include all operations
308
- * 2. Empty arrays are treated as "no constraint" (not as "exclude all")
309
- * 3. Include filters are applied first (allowlist)
310
- * 4. Exclude filters are applied second (blocklist)
311
- * 5. Exclude rules always win over include rules
312
- *
313
- * @param operation - The OpenAPI operation object
314
- * @param path - The operation path (e.g., "/users/{id}")
315
- * @param method - The HTTP method (e.g., "get", "post")
316
- * @param filters - Optional filter configuration
317
- * @param stats - Optional statistics object to track filtering reasons
318
- * @returns true if the operation should be included, false otherwise
319
- */
320
- declare function shouldIncludeOperation(operation: any, path: string, method: string, filters?: OperationFilters, stats?: FilterStatistics): boolean;
321
- /**
322
- * Validate filter statistics and emit warnings for filters that matched nothing
323
- * Helps users debug filter configurations that might be too restrictive or contain typos
324
- *
325
- * @param stats - Filter statistics object
326
- * @param filters - The filter configuration to validate
327
- */
328
- declare function validateFilters(stats: FilterStatistics, filters?: OperationFilters): void;
329
- /**
330
- * Format filter statistics for display in generated output
331
- * Returns a formatted string suitable for inclusion in comments
332
- *
333
- * @param stats - Filter statistics object
334
- * @returns Formatted statistics string
335
- */
336
- declare function formatFilterStatistics(stats: FilterStatistics): string;
337
-
338
- /**
339
- * @shared Strips a prefix from a string using either literal string matching or glob patterns
340
- * @since 1.1.0
341
- * Shared utility used by core and playwright packages
342
- *
343
- * @param input - The full string to strip from
344
- * @param pattern - The glob pattern to strip
345
- * @param ensureLeadingChar - Optional character to ensure at start (e.g., "/" for paths)
346
- * @returns The string with prefix removed, or original string if no match
347
- *
348
- * @example
349
- * // Literal string matching
350
- * stripPrefix("/api/v1/users", "/api/v1") // => "/users"
351
- * stripPrefix("Company.Models.User", "Company.Models.") // => "User"
352
- *
353
- * @example
354
- * // Glob pattern matching
355
- * stripPrefix("/api/v1.0/users", "/api/v*") // => matches and strips
356
- * stripPrefix("Company.Models.User", "*.Models.") // => "User"
357
- * stripPrefix("api_v2_UserSchema", "api_v[0-9]_") // => "UserSchema"
358
- */
359
- declare function stripPrefix(input: string, pattern: string | undefined, ensureLeadingChar?: string): string;
360
- /**
361
- * @shared Strips a prefix from a path (ensures leading slash)
362
- * @since 1.1.0
363
- * Shared utility used by playwright package for path manipulation
364
- *
365
- * @param path - The full path to strip from
366
- * @param pattern - The glob pattern to strip
367
- * @returns The path with prefix removed, or original path if no match
368
- *
369
- * @example
370
- * stripPathPrefix("/api/v1/users", "/api/v1") // => "/users"
371
- * stripPathPrefix("/api/v2/posts", "/api/v*") // => "/posts"
372
- * stripPathPrefix("/api/v1.0/items", "/api/v[0-9].*") // => "/items"
373
- */
374
- declare function stripPathPrefix(path: string, pattern: string | undefined): string;
375
-
376
- /**
377
- * OpenAPI $ref resolution utilities
378
- *
379
- * Provides functions to resolve $ref references to component definitions
380
- * Supports: parameters, requestBodies, responses, schemas
381
- *
382
- * @internal Used by core and playwright packages
383
- */
384
-
385
- /**
386
- * Type for any resolvable component
387
- */
388
- type ResolvableComponent = OpenAPIParameter | OpenAPIRequestBody | OpenAPIResponse | OpenAPISchema | any;
389
- /**
390
- * Resolve a $ref to a component definition
391
- * Handles nested $refs by recursively resolving until no more refs found
392
- *
393
- * @param obj - Object that may contain a $ref
394
- * @param spec - The OpenAPI specification
395
- * @param maxDepth - Maximum recursion depth to prevent infinite loops (default: 10)
396
- * @returns The resolved component, or the original object if not a reference
397
- */
398
- declare function resolveRef<T extends ResolvableComponent>(obj: T | any, spec: OpenAPISpec, maxDepth?: number): T;
399
- /**
400
- * Resolve a parameter reference
401
- * Convenience wrapper for resolveRef with parameter type
402
- */
403
- declare function resolveParameterRef(param: any, spec: OpenAPISpec): OpenAPIParameter | any;
404
- /**
405
- * Resolve a request body reference
406
- * Convenience wrapper for resolveRef with request body type
407
- */
408
- declare function resolveRequestBodyRef(requestBody: any, spec: OpenAPISpec): OpenAPIRequestBody | any;
409
- /**
410
- * Resolve a response reference
411
- * Convenience wrapper for resolveRef with response type
412
- */
413
- declare function resolveResponseRef(response: any, spec: OpenAPISpec): OpenAPIResponse | any;
414
- /**
415
- * Merge path-level parameters with operation-level parameters
416
- * Operation parameters override path-level parameters with the same name and location
417
- *
418
- * @param pathParams - Parameters defined at the path level
419
- * @param operationParams - Parameters defined at the operation level
420
- * @param spec - The OpenAPI specification for resolving $refs
421
- * @returns Merged array of resolved parameters
422
- */
423
- declare function mergeParameters(pathParams: any[] | undefined, operationParams: any[] | undefined, spec: OpenAPISpec): any[];
424
-
425
- /**
426
- * String utility functions for escaping and formatting
427
- */
428
-
429
- /**
430
- * @shared Escape JSDoc comment content to prevent injection
431
- * @since 1.0.0
432
- * Utility used by core and playwright packages
433
- */
434
- declare function escapeJSDoc(str: string): string;
435
-
436
- /**
437
- * @shared Create a TypeScript loader for cosmiconfig using esbuild
438
- * @since 1.0.0
439
- * Utility used by core and playwright packages
440
- *
441
- * Creates a loader that transpiles TypeScript config files to JavaScript
442
- * using esbuild, then executes them to load the configuration.
443
- *
444
- * @returns A cosmiconfig Loader function
445
- */
446
- declare function createTypeScriptLoader(): Loader;
447
-
448
- /**
449
- * Build the Zod validation string for date-time format
450
- * Pure function that returns the validation string without side effects
451
- *
452
- * @param pattern - Optional regex pattern (string or RegExp) for date-time validation
453
- * @returns Zod validation string (either "z.iso.datetime()" or custom regex)
454
- * @throws {Error} If the provided pattern is not a valid regular expression
455
- *
456
- * @example
457
- * // Default (no pattern)
458
- * buildDateTimeValidation() // Returns "z.iso.datetime()"
459
- *
460
- * @example
461
- * // String pattern (for JSON/YAML configs)
462
- * buildDateTimeValidation('^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$')
463
- *
464
- * @example
465
- * // RegExp literal (TypeScript configs)
466
- * buildDateTimeValidation(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/)
467
- */
468
- declare function buildDateTimeValidation(pattern?: string | RegExp): string;
469
-
470
- export { type BaseOperationFilters, type ContentTypeParseResult, type FallbackContentTypeParsing, type FilterStatistics, type Generator, LRUCache, OperationFiltersSchema, PropertyGenerator, type PropertyGeneratorContext, type RequestResponseOptions, RequestResponseOptionsSchema, buildDateTimeValidation, createFilterStatistics, createTypeScriptLoader, escapeJSDoc, executeBatch, formatConfigValidationError, formatFilterStatistics, getBatchExitCode, getResponseParseMethod, mergeParameters, resolveParameterRef, resolveRef, resolveRequestBodyRef, resolveResponseRef, shouldIncludeOperation, stripPathPrefix, stripPrefix, toCamelCase, toPascalCase, validateFilters };