zod-codegen 1.0.3 → 1.1.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,30 +1,100 @@
1
- import { beforeEach, describe, expect, it, vi } from 'vitest';
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
2
  import { Generator } from '../../src/generator.js';
3
3
  import { Reporter } from '../../src/utils/reporter.js';
4
+ import { readFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { dirname } from 'node:path';
8
+ const __dirname = dirname(fileURLToPath(import.meta.url));
9
+ const testOutputDir = join(__dirname, '../../test-output');
4
10
  describe('Generator', () => {
5
11
  let generator;
6
12
  let mockReporter;
7
13
  beforeEach(() => {
14
+ // Clean up test output directory
15
+ if (existsSync(testOutputDir)) {
16
+ rmSync(testOutputDir, { recursive: true, force: true });
17
+ }
18
+ mkdirSync(testOutputDir, { recursive: true });
8
19
  // Create a mock reporter
9
20
  mockReporter = {
10
- info: vi.fn(),
21
+ log: vi.fn(),
11
22
  error: vi.fn(),
12
- warn: vi.fn(),
13
- success: vi.fn(),
14
23
  };
15
- generator = new Generator('test-app', '1.0.0', mockReporter, './test-input.json', './test-output');
24
+ });
25
+ afterEach(() => {
26
+ // Clean up test output directory
27
+ if (existsSync(testOutputDir)) {
28
+ rmSync(testOutputDir, { recursive: true, force: true });
29
+ }
16
30
  });
17
31
  describe('constructor', () => {
18
32
  it('should create a new Generator instance', () => {
33
+ generator = new Generator('test-app', '1.0.0', mockReporter, './samples/swagger-petstore.yaml', testOutputDir);
19
34
  expect(generator).toBeInstanceOf(Generator);
20
35
  });
36
+ it('should initialize with correct parameters', () => {
37
+ generator = new Generator('test-app', '1.0.0', mockReporter, './samples/swagger-petstore.yaml', testOutputDir);
38
+ expect(generator).toBeDefined();
39
+ });
21
40
  });
22
41
  describe('run', () => {
23
42
  it('should be a function', () => {
43
+ generator = new Generator('test-app', '1.0.0', mockReporter, './samples/swagger-petstore.yaml', testOutputDir);
24
44
  expect(typeof generator.run).toBe('function');
25
45
  });
26
- it('should have the run method defined', () => {
27
- expect(generator).toHaveProperty('run');
46
+ it('should generate code from a valid OpenAPI file', async () => {
47
+ generator = new Generator('test-app', '1.0.0', mockReporter, './samples/swagger-petstore.yaml', testOutputDir);
48
+ const exitCode = await generator.run();
49
+ expect(exitCode).toBe(0);
50
+ expect(mockReporter.log).toHaveBeenCalled();
51
+ expect(mockReporter.error).not.toHaveBeenCalled();
52
+ // Verify output file was created
53
+ const outputFile = join(testOutputDir, 'type.ts');
54
+ expect(existsSync(outputFile)).toBe(true);
55
+ // Verify file contains expected content
56
+ const content = readFileSync(outputFile, 'utf-8');
57
+ expect(content).toMatch(/import\s*{\s*z\s*}\s*from\s*['"]zod['"]/);
58
+ expect(content).toContain('export class');
59
+ expect(content).toContain('getBaseRequestOptions');
60
+ });
61
+ it('should handle invalid file paths gracefully', async () => {
62
+ generator = new Generator('test-app', '1.0.0', mockReporter, './non-existent-file.yaml', testOutputDir);
63
+ const exitCode = await generator.run();
64
+ expect(exitCode).toBe(1);
65
+ expect(mockReporter.error).toHaveBeenCalled();
66
+ });
67
+ it('should handle invalid OpenAPI specifications', async () => {
68
+ // Create a temporary invalid OpenAPI file
69
+ const invalidFile = join(testOutputDir, 'invalid.yaml');
70
+ mkdirSync(testOutputDir, { recursive: true });
71
+ readFileSync; // Ensure we can write
72
+ const { writeFileSync } = await import('node:fs');
73
+ writeFileSync(invalidFile, 'invalid: yaml: content: [unclosed');
74
+ generator = new Generator('test-app', '1.0.0', mockReporter, invalidFile, testOutputDir);
75
+ const exitCode = await generator.run();
76
+ expect(exitCode).toBe(1);
77
+ expect(mockReporter.error).toHaveBeenCalled();
78
+ });
79
+ it('should generate code with correct structure', async () => {
80
+ generator = new Generator('test-app', '1.0.0', mockReporter, './samples/swagger-petstore.yaml', testOutputDir);
81
+ await generator.run();
82
+ const outputFile = join(testOutputDir, 'type.ts');
83
+ const content = readFileSync(outputFile, 'utf-8');
84
+ // Check for key components
85
+ expect(content).toMatch(/import\s*{\s*z\s*}\s*from\s*['"]zod['"]/);
86
+ expect(content).toContain('export const');
87
+ expect(content).toContain('protected getBaseRequestOptions');
88
+ expect(content).toContain('async #makeRequest');
89
+ });
90
+ it('should include header comments in generated file', async () => {
91
+ generator = new Generator('test-app', '1.0.0', mockReporter, './samples/swagger-petstore.yaml', testOutputDir);
92
+ await generator.run();
93
+ const outputFile = join(testOutputDir, 'type.ts');
94
+ const content = readFileSync(outputFile, 'utf-8');
95
+ expect(content).toContain('AUTOGENERATED');
96
+ expect(content).toContain('test-app@1.0.0');
97
+ expect(content).toContain('eslint-disable');
28
98
  });
29
99
  });
30
100
  });
package/eslint.config.mjs CHANGED
@@ -10,6 +10,7 @@ export default defineConfig([
10
10
  'node_modules/**/*',
11
11
  '**/*.test*.ts',
12
12
  '**/coverage/*',
13
+ 'examples/**/*.ts',
13
14
  ],
14
15
  },
15
16
  eslint.configs.recommended,
@@ -0,0 +1,3 @@
1
+ # This file ensures the examples directory is tracked by git
2
+ # Generated type.ts files are ignored via .gitignore
3
+
@@ -0,0 +1,74 @@
1
+ # Examples
2
+
3
+ This directory contains example implementations demonstrating how to use `zod-codegen` with real-world OpenAPI specifications.
4
+
5
+ ## Available Examples
6
+
7
+ ### 🐾 [Petstore API](./petstore/)
8
+
9
+ The Swagger Petstore API is a well-known example API that demonstrates various OpenAPI features. This example shows:
10
+
11
+ - Basic client usage
12
+ - Authentication with API keys
13
+ - Extending the client for custom headers
14
+ - Working with pets, orders, and users
15
+
16
+ **Generate the client:**
17
+
18
+ ```bash
19
+ zod-codegen --input ./samples/swagger-petstore.yaml --output ./examples/petstore
20
+ ```
21
+
22
+ **Run examples:**
23
+
24
+ ```bash
25
+ npx ts-node examples/petstore/basic-usage.ts
26
+ npx ts-node examples/petstore/authenticated-usage.ts
27
+ ```
28
+
29
+ ### ⚔ [PokéAPI](./pokeapi/)
30
+
31
+ PokƩAPI is a public RESTful API that provides data about PokƩmon. This example demonstrates:
32
+
33
+ - Working with a real-world public API
34
+ - Fetching PokƩmon data
35
+ - Custom client configuration
36
+
37
+ **Generate the client:**
38
+
39
+ ```bash
40
+ zod-codegen --input https://pokeapi.co/api/v2/openapi.json --output ./examples/pokeapi
41
+ ```
42
+
43
+ ## Structure
44
+
45
+ Each example directory contains:
46
+
47
+ - `type.ts` - Generated client and schemas (created by zod-codegen)
48
+ - `README.md` - Example-specific documentation
49
+ - `basic-usage.ts` - Basic usage examples
50
+ - `authenticated-usage.ts` - Authentication examples (if applicable)
51
+
52
+ ## Getting Started
53
+
54
+ 1. **Choose an example** that matches your use case
55
+ 2. **Generate the client** using the command shown in the example's README
56
+ 3. **Review the generated code** in `type.ts`
57
+ 4. **Run the example scripts** to see it in action
58
+ 5. **Extend the client** using patterns from [EXAMPLES.md](../EXAMPLES.md)
59
+
60
+ ## Learning Path
61
+
62
+ 1. Start with **Petstore** to understand basic concepts
63
+ 2. Try **PokƩAPI** to see a real-world public API
64
+ 3. Read [EXAMPLES.md](../EXAMPLES.md) for advanced patterns
65
+ 4. Create your own example with your API!
66
+
67
+ ## Contributing Examples
68
+
69
+ If you'd like to add an example:
70
+
71
+ 1. Create a new directory under `examples/`
72
+ 2. Add a `README.md` explaining the example
73
+ 3. Include example TypeScript files
74
+ 4. Update this README to list your example
@@ -0,0 +1,121 @@
1
+ # Petstore API Example
2
+
3
+ This example demonstrates how to use `zod-codegen` with the Swagger Petstore OpenAPI specification.
4
+
5
+ ## Generated Files
6
+
7
+ After running `zod-codegen`, you'll get:
8
+
9
+ - `type.ts` - Contains all Zod schemas and the generated API client
10
+
11
+ ## Basic Usage
12
+
13
+ ```typescript
14
+ import {SwaggerPetstoreOpenAPI30} from './type.js';
15
+
16
+ // Create a client instance using default server from OpenAPI spec
17
+ const client = new SwaggerPetstoreOpenAPI30({});
18
+
19
+ // Use the generated methods
20
+ const pets = await client.findPetsByStatus('available');
21
+ console.log('Available pets:', pets);
22
+ ```
23
+
24
+ ### Server Configuration Options
25
+
26
+ The generated client supports flexible server configuration:
27
+
28
+ ```typescript
29
+ import {SwaggerPetstoreOpenAPI30, ClientOptions} from './type.js';
30
+
31
+ // Option 1: Use default server (first server from OpenAPI spec)
32
+ const defaultClient = new SwaggerPetstoreOpenAPI30({});
33
+
34
+ // Option 2: Override with custom base URL
35
+ const customClient = new SwaggerPetstoreOpenAPI30({
36
+ baseUrl: 'https://custom-api.example.com/v3',
37
+ });
38
+
39
+ // Option 3: Select server by index (if multiple servers exist)
40
+ const indexedClient = new SwaggerPetstoreOpenAPI30({
41
+ serverIndex: 0,
42
+ });
43
+
44
+ // Option 4: Use server variables (if your OpenAPI spec has templated URLs)
45
+ // Example spec: https://{environment}.example.com:{port}/v{version}
46
+ const variableClient = new SwaggerPetstoreOpenAPI30({
47
+ serverIndex: 0,
48
+ serverVariables: {
49
+ environment: 'api.staging',
50
+ port: '8443',
51
+ version: '2',
52
+ },
53
+ });
54
+ ```
55
+
56
+ ## Example: Finding Pets
57
+
58
+ ```typescript
59
+ import {SwaggerPetstoreOpenAPI30, defaultBaseUrl} from './type.js';
60
+
61
+ async function findAvailablePets() {
62
+ const client = new SwaggerPetstoreOpenAPI30(defaultBaseUrl);
63
+
64
+ try {
65
+ // Find pets by status
66
+ const availablePets = await client.findPetsByStatus('available');
67
+ console.log(`Found ${availablePets.length} available pets`);
68
+
69
+ // Find pets by tags
70
+ const taggedPets = await client.findPetsByTags(['friendly', 'cute']);
71
+ console.log(`Found ${taggedPets.length} tagged pets`);
72
+
73
+ // Get a specific pet by ID
74
+ const pet = await client.getPetById(1);
75
+ console.log('Pet details:', pet);
76
+ } catch (error) {
77
+ console.error('Error fetching pets:', error);
78
+ }
79
+ }
80
+
81
+ findAvailablePets();
82
+ ```
83
+
84
+ ## Example: Adding a Pet
85
+
86
+ ```typescript
87
+ import {SwaggerPetstoreOpenAPI30, Pet, PetStatus, defaultBaseUrl} from './type.js';
88
+ import {z} from 'zod';
89
+
90
+ async function addNewPet() {
91
+ const client = new SwaggerPetstoreOpenAPI30(defaultBaseUrl);
92
+
93
+ const newPet: z.infer<typeof Pet> = {
94
+ id: 12345,
95
+ name: 'Fluffy',
96
+ status: PetStatus.enum.available,
97
+ category: {
98
+ id: 1,
99
+ name: 'Dogs',
100
+ },
101
+ photoUrls: ['https://example.com/fluffy.jpg'],
102
+ tags: [
103
+ {id: 1, name: 'friendly'},
104
+ {id: 2, name: 'cute'},
105
+ ],
106
+ };
107
+
108
+ try {
109
+ const addedPet = await client.addPet(newPet);
110
+ console.log('Pet added:', addedPet);
111
+ } catch (error) {
112
+ console.error('Error adding pet:', error);
113
+ }
114
+ }
115
+
116
+ addNewPet();
117
+ ```
118
+
119
+ ## Example: Extending the Client
120
+
121
+ See the main [EXAMPLES.md](../../EXAMPLES.md) for comprehensive examples on extending the client for authentication, CORS, and custom headers.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Example showing how to extend the generated client for authentication
3
+ *
4
+ * Run with: npx ts-node examples/petstore/authenticated-usage.ts
5
+ */
6
+
7
+ import {SwaggerPetstoreOpenAPI30, ClientOptions} from './type.js';
8
+
9
+ class AuthenticatedPetstoreAPI extends SwaggerPetstoreOpenAPI30 {
10
+ private apiKey: string | null = null;
11
+
12
+ constructor(options: ClientOptions = {}) {
13
+ super(options);
14
+ }
15
+
16
+ protected getBaseRequestOptions(): Partial<Omit<RequestInit, 'method' | 'body'>> {
17
+ const options = super.getBaseRequestOptions();
18
+ return {
19
+ ...options,
20
+ headers: {
21
+ ...((options.headers as Record<string, string>) || {}),
22
+ ...(this.apiKey ? {api_key: this.apiKey} : {}),
23
+ 'User-Agent': 'PetstoreClient/1.0.0',
24
+ },
25
+ };
26
+ }
27
+
28
+ setApiKey(key: string): void {
29
+ this.apiKey = key;
30
+ }
31
+
32
+ clearApiKey(): void {
33
+ this.apiKey = null;
34
+ }
35
+ }
36
+
37
+ async function main() {
38
+ const client = new AuthenticatedPetstoreAPI({});
39
+
40
+ // Set API key for authenticated requests
41
+ client.setApiKey('your-api-key-here');
42
+
43
+ try {
44
+ console.log('šŸ” Making authenticated request...\n');
45
+
46
+ // This endpoint typically requires authentication
47
+ const inventory = await client.getInventory();
48
+ console.log('āœ… Inventory retrieved:');
49
+ console.log(JSON.stringify(inventory, null, 2));
50
+ } catch (error) {
51
+ if (error instanceof Error) {
52
+ console.error('āŒ Error:', error.message);
53
+ } else {
54
+ console.error('āŒ Unknown error:', error);
55
+ }
56
+ process.exit(1);
57
+ }
58
+ }
59
+
60
+ void main();
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Basic usage example for the generated Petstore API client
3
+ *
4
+ * Run with: npx ts-node examples/petstore/basic-usage.ts
5
+ */
6
+
7
+ import {SwaggerPetstoreOpenAPI30} from './type.js';
8
+
9
+ async function main() {
10
+ // Use default server (first server from OpenAPI spec)
11
+ const client = new SwaggerPetstoreOpenAPI30({});
12
+
13
+ try {
14
+ console.log('šŸ” Finding available pets...\n');
15
+
16
+ // Find pets by status
17
+ const availablePets = await client.findPetsByStatus('available');
18
+ console.log(`āœ… Found ${availablePets.length} available pets`);
19
+
20
+ if (availablePets.length > 0) {
21
+ console.log('\nšŸ“‹ First pet details:');
22
+ console.log(JSON.stringify(availablePets[0], null, 2));
23
+ }
24
+
25
+ // Find pets by tags (if available)
26
+ try {
27
+ const taggedPets = await client.findPetsByTags(['friendly']);
28
+ console.log(`\nšŸ·ļø Found ${taggedPets.length} pets with tags`);
29
+ } catch (error) {
30
+ console.log('\nāš ļø Tags endpoint may not be available');
31
+ }
32
+
33
+ // Get store inventory
34
+ try {
35
+ const inventory = await client.getInventory();
36
+ console.log('\nšŸ“¦ Store inventory:');
37
+ console.log(JSON.stringify(inventory, null, 2));
38
+ } catch (error) {
39
+ console.log('\nāš ļø Inventory endpoint may require authentication');
40
+ }
41
+ } catch (error) {
42
+ if (error instanceof Error) {
43
+ console.error('āŒ Error:', error.message);
44
+ } else {
45
+ console.error('āŒ Unknown error:', error);
46
+ }
47
+ process.exit(1);
48
+ }
49
+ }
50
+
51
+ void main();
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Example showing how to use server variables for different environments
3
+ *
4
+ * Run with: npx ts-node examples/petstore/server-variables-usage.ts
5
+ *
6
+ * Note: This example uses a hypothetical API with server variables.
7
+ * For a real example, generate a client from an OpenAPI spec with server variables.
8
+ */
9
+
10
+ import {SwaggerPetstoreOpenAPI30, ClientOptions} from './type.js';
11
+
12
+ async function main() {
13
+ // Example 1: Use default server (first server from OpenAPI spec)
14
+ console.log('šŸ“” Example 1: Using default server\n');
15
+ const defaultClient = new SwaggerPetstoreOpenAPI30({});
16
+ console.log('Default client created');
17
+
18
+ // Example 2: Override with custom baseUrl
19
+ console.log('\nšŸ“” Example 2: Overriding with custom baseUrl\n');
20
+ const customClient = new SwaggerPetstoreOpenAPI30({
21
+ baseUrl: 'https://custom-api.example.com/v3',
22
+ });
23
+ console.log('Custom client created');
24
+
25
+ // Example 3: Select different server by index (if multiple servers exist)
26
+ console.log('\nšŸ“” Example 3: Selecting server by index\n');
27
+ const indexedClient = new SwaggerPetstoreOpenAPI30({
28
+ serverIndex: 0, // Use first server
29
+ });
30
+ console.log('Indexed client created');
31
+
32
+ // Example 4: Using server variables (if your OpenAPI spec has templated URLs)
33
+ // For example: https://{environment}.example.com:{port}/v{version}
34
+ console.log('\nšŸ“” Example 4: Using server variables\n');
35
+ const variableClient = new SwaggerPetstoreOpenAPI30({
36
+ serverIndex: 0,
37
+ serverVariables: {
38
+ // environment: 'api.staging', // Uncomment if your spec has these variables
39
+ // port: '8443',
40
+ // version: '2',
41
+ },
42
+ });
43
+ console.log('Variable client created');
44
+
45
+ // Example 5: Combining server selection with custom baseUrl override
46
+ console.log('\nšŸ“” Example 5: Combining options\n');
47
+ const combinedClient = new SwaggerPetstoreOpenAPI30({
48
+ serverIndex: 0,
49
+ serverVariables: {
50
+ // Add variables here if your spec supports them
51
+ },
52
+ // baseUrl takes precedence if provided
53
+ // baseUrl: 'https://override.example.com',
54
+ });
55
+ console.log('Combined client created');
56
+
57
+ console.log('\nāœ… All examples completed!');
58
+ console.log("\nšŸ’” Tip: Check your OpenAPI spec's servers array to see available options.");
59
+ console.log(' Server variables allow you to switch between environments (dev, staging, prod)');
60
+ console.log(' without changing code!');
61
+ }
62
+
63
+ void main();