@rexeus/typeweaver-clients 0.0.3 โ†’ 0.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.
package/README.md CHANGED
@@ -1,411 +1,136 @@
1
- # @rexeus/typeweaver-clients
1
+ # ๐Ÿงตโœจ @rexeus/typeweaver-clients
2
2
 
3
- HTTP client generators for TypeWeaver API specifications.
3
+ [![npm version](https://img.shields.io/npm/v/@rexeus/typeweaver-clients.svg)](https://www.npmjs.com/package/@rexeus/typeweaver-clients)
4
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
4
6
 
5
- ## Overview
7
+ Typeweaver is a type-safe HTTP API framework built for API-first development with a focus on
8
+ developer experience. Use typeweaver to specify your HTTP APIs in TypeScript and Zod, and generate
9
+ clients, validators, routers, and more โœจ
6
10
 
7
- This plugin generates type-safe HTTP API clients from your TypeWeaver API definitions, providing
8
- end-to-end type safety from API definition to client usage.
11
+ ## ๐Ÿ“ Clients Plugin
9
12
 
10
- ## Installation
13
+ This plugin generates type-safe HTTP clients from your typeweaver API definitions, providing
14
+ end-to-end type safety. The generated clients use the Command Pattern, where each API request is
15
+ encapsulated as a typed command object that contains all request data and handles response
16
+ processing.
11
17
 
12
- ```bash
13
- npm install @rexeus/typeweaver-clients
14
- ```
15
-
16
- **Peer Dependencies:**
18
+ ## ๐Ÿ“ฅ Installation
17
19
 
18
20
  ```bash
19
- npm install @rexeus/typeweaver-core @rexeus/typeweaver-gen
20
- ```
21
+ # Install the CLI and the plugin as a dev dependency
22
+ npm install -D @rexeus/typeweaver @rexeus/typeweaver-clients
21
23
 
22
- ## Usage
24
+ # Install the runtime as a dependency
25
+ npm install @rexeus/typeweaver-core
26
+ ```
23
27
 
24
- ### CLI
28
+ ## ๐Ÿ’ก How to use
25
29
 
26
30
  ```bash
27
31
  npx typeweaver generate --input ./api/definitions --output ./api/generated --plugins clients
28
32
  ```
29
33
 
30
- ### Configuration File
34
+ More on the CLI in [@rexeus/typeweaver](https://github.com/rexeus/typeweaver/tree/main/packages/cli/README.md#๏ธ-cli).
31
35
 
32
- ```javascript
33
- // typeweaver.config.js
34
- export default {
35
- input: "./api/definitions",
36
- output: "./api/generated",
37
- plugins: ["clients"],
38
- };
39
- ```
40
-
41
- ## Generated Output
36
+ ## ๐Ÿ“‚ Generated Output
42
37
 
43
- This plugin generates HTTP API clients for each entity in your API definitions.
38
+ For each resource (e.g., `Todo`), the plugin generates a HTTP client. This client can execute
39
+ request commands for all operations of this resource. This plugin generates the following files:
44
40
 
45
- ### Example Generated Client
41
+ - `<ResourceName>Client.ts` - e.g. `TodoClient.ts`
42
+ - `<OperationId>RequestCommand.ts` - e.g. `CreateTodoRequestCommand.ts`
46
43
 
47
- For an API definition with a `users` entity, the plugin generates:
44
+ ### ๐Ÿ“ก Clients
48
45
 
49
- ```typescript
50
- // UsersClient.ts
51
- import { ApiClient } from "@rexeus/typeweaver-core";
52
- import { GetUserRequestCommand } from "./GetUserRequest";
53
- import { GetUserResponseValidator } from "./GetUserResponseValidator";
54
- // ... other imports
46
+ Resource-specific HTTP clients are generated as `<ResourceName>Client.ts` files, e.g.
47
+ `TodoClient.ts`. Each client extends the `ApiClient` base class and provides:
55
48
 
56
- export class UsersClient extends ApiClient {
57
- public send(command: GetUserRequestCommand): Promise<GetUserResponse>;
58
- public send(command: CreateUserRequestCommand): Promise<CreateUserResponse>;
59
- // ... other overloads
49
+ - **Type-safe HTTP methods** - Method overloads for each operation ensuring compile-time type
50
+ checking
51
+ - **axios based** - Supports all axios features and interceptors by using custom axios instances
52
+ - **Response type mapping** - Each response is automatically mapped to the associated response class
53
+ and an instance of the class is returned. This ensures that all responses are in the defined
54
+ format and it is type-safe.
55
+ - **Unknown response handling**
56
+ - Unknown properties are automatically removed from the response. If a response exceeds the
57
+ definition, it is not rejected directly.
58
+ - If a response does not match any known format, it will be rejected by default as an
59
+ `UnknownResponse` instance.
60
+ - This unknown response handling can be configured. It is also possible for an `UnknownResponse`
61
+ instance to be created without being thrown.
60
62
 
61
- public async send(command: unknown): Promise<unknown> {
62
- if (command instanceof GetUserRequestCommand) {
63
- return this.handleGetUser(command);
64
- }
65
- if (command instanceof CreateUserRequestCommand) {
66
- return this.handleCreateUser(command);
67
- }
68
- // ... other handlers
69
-
70
- throw new Error(`Unknown command type`);
71
- }
72
-
73
- private async handleGetUser(command: GetUserRequestCommand): Promise<GetUserResponse> {
74
- const response = await this.makeRequest(command);
75
- const validator = new GetUserResponseValidator();
76
- return validator.validate(response);
77
- }
78
-
79
- // ... other private handlers
80
- }
81
- ```
82
-
83
- ## Usage Examples
84
-
85
- ### Basic Usage
63
+ **Using generated clients**
86
64
 
87
65
  ```typescript
88
- import { UsersClient } from "./api/generated/users/UsersClient";
89
- import { GetUserRequestCommand } from "./api/generated/users/GetUserRequest";
90
-
91
- const client = new UsersClient({
92
- baseURL: "https://api.example.com",
93
- });
66
+ import { TodoClient } from "path/to/generated/output";
94
67
 
95
- // Type-safe request
96
- const command = new GetUserRequestCommand({
97
- param: { userId: "123" },
98
- header: { Authorization: "Bearer token" },
68
+ const client = new TodoClient({
69
+ axiosInstance: customAxios, // Custom axios instance
70
+ baseUrl: "https://api.example.com", // Base URL for all requests
71
+ unknownResponseHandling: "throw", // "throw" | "passthrough" for unknown responses
72
+ // -> In "passthrough" mode, the received status code determines if the response is thrown
73
+ isSuccessStatusCode: code => code < 400, // Custom success status code predicate, determines whether the response is successful or should be thrown
99
74
  });
100
-
101
- try {
102
- // Fully typed response
103
- const result = await client.send(command);
104
- console.log(result.body.name); // Type-safe access
105
- } catch (error) {
106
- // Typed error handling
107
- if (error instanceof UserNotFoundErrorResponse) {
108
- console.error("User not found:", error.body.message);
109
- }
110
- }
111
75
  ```
112
76
 
113
- ### Advanced Configuration
77
+ ### โœ‰๏ธ Request Commands
114
78
 
115
- ```typescript
116
- import { UsersClient } from "./api/generated/users/UsersClient";
79
+ Request commands are generated as `<OperationId>RequestCommand.ts` files, e.g.
80
+ `CreateTodoRequestCommand.ts`. These commands encapsulate all request data and provide:
117
81
 
118
- const client = new UsersClient({
119
- baseURL: "https://api.example.com",
120
- timeout: 5000,
121
- headers: {
122
- "User-Agent": "MyApp/1.0",
123
- },
124
- // Custom axios config
125
- axios: {
126
- validateStatus: status => status < 500,
127
- },
128
- });
129
- ```
82
+ - **Type-safe construction** - Constructor enforces correct request structure
83
+ - **Complete request encapsulation** - Contains method, path, headers, query parameters, and body
84
+ - **Response processing** - Transform raw HTTP responses into typed response objects of the correct
85
+ response class
130
86
 
131
- ### Error Handling
87
+ ### Basic Usage
132
88
 
133
89
  ```typescript
134
90
  import {
135
- UsersClient,
136
- GetUserRequestCommand,
137
- UserNotFoundErrorResponse,
91
+ TodoClient,
92
+ CreateTodoRequestCommand,
93
+ CreateTodoSuccessResponse,
94
+ OtherSuccessResponse,
138
95
  ValidationErrorResponse,
139
- } from "./api/generated";
140
-
141
- const client = new UsersClient({ baseURL: "https://api.example.com" });
96
+ InternalServerErrorResponse,
97
+ } from "path/to/generated/output";
142
98
 
143
- try {
144
- const result = await client.send(
145
- new GetUserRequestCommand({
146
- param: { userId: "invalid-id" },
147
- })
148
- );
149
- } catch (error) {
150
- // Type-safe error handling
151
- if (error instanceof UserNotFoundErrorResponse) {
152
- console.error(`User not found: ${error.body.message}`);
153
- } else if (error instanceof ValidationErrorResponse) {
154
- console.error("Validation failed:", error.body.issues);
155
- } else {
156
- console.error("Unexpected error:", error);
157
- }
158
- }
159
- ```
160
-
161
- ## Client Features
162
-
163
- ### Type Safety
164
-
165
- - **Request Commands** - Fully typed request objects
166
- - **Response Types** - Typed response interfaces
167
- - **Error Types** - Typed error response classes
168
- - **Parameter Validation** - Runtime validation via Zod
169
-
170
- ### Method Overloading
171
-
172
- Each client provides method overloads for perfect type inference:
173
-
174
- ```typescript
175
- // Each command type gets its own overload
176
- client.send(getUserCommand); // Returns GetUserResponse
177
- client.send(createUserCommand); // Returns CreateUserResponse
178
- ```
179
-
180
- ### Automatic Validation
181
-
182
- - **Request validation** - Commands validate input data
183
- - **Response validation** - Responses validated against schemas
184
- - **Error parsing** - HTTP errors mapped to typed error classes
185
-
186
- ### Framework Integration
187
-
188
- Works with any HTTP client framework (uses Axios by default):
189
-
190
- ```typescript
191
- // Custom HTTP adapter
192
- const client = new UsersClient({
193
- baseURL: "https://api.example.com",
194
- httpAdapter: new FetchAdapter(), // Custom adapter
99
+ const client = new TodoClient({
100
+ baseUrl: "https://api.example.com",
195
101
  });
196
- ```
197
-
198
- ## Request Commands
199
-
200
- ### Command Structure
201
102
 
202
- Generated request commands encapsulate all request data:
203
-
204
- ```typescript
205
- import { GetUserRequestCommand } from "./GetUserRequest";
206
-
207
- const command = new GetUserRequestCommand({
208
- param: { userId: "123" }, // Path parameters
209
- query: { include: ["posts"] }, // Query parameters
210
- header: { Authorization: "Bearer token" }, // Headers
211
- body: { name: "John Doe" }, // Request body
103
+ const command = new CreateTodoRequestCommand({
104
+ header: { Authorization: "Bearer token" },
105
+ body: { title: "New Todo", status: "PENDING" },
212
106
  });
213
- ```
214
-
215
- ### Command Validation
216
107
 
217
- Commands validate input data at construction time:
218
-
219
- ```typescript
220
108
  try {
221
- const command = new GetUserRequestCommand({
222
- param: { userId: "invalid-uuid" }, // Will throw validation error
223
- });
224
- } catch (error) {
225
- console.error("Invalid command:", error.issues);
226
- }
227
- ```
228
-
229
- ## Response Handling
109
+ const response = await client.send(command);
230
110
 
231
- ### Success Responses
111
+ // If there is only one success response,
112
+ // you can directly access the response like:
113
+ console.log("Success:", response.body);
232
114
 
233
- ```typescript
234
- const result = await client.send(command);
235
-
236
- // Typed access to response data
237
- console.log(result.statusCode); // HTTP status code
238
- console.log(result.header); // Response headers
239
- console.log(result.body.id); // Response body (fully typed)
240
- ```
241
-
242
- ### Error Responses
243
-
244
- ```typescript
245
- try {
246
- const result = await client.send(command);
247
- } catch (error) {
248
- if (error instanceof UserNotFoundErrorResponse) {
249
- // Specific error type
250
- console.log(error.statusCode); // 404
251
- console.log(error.body.message); // "User not found"
115
+ // If there are multiple success responses, you can check the instance like:
116
+ if (response instanceof CreateTodoSuccessResponse) {
117
+ console.log("Todo created successfully:", response.body);
252
118
  }
253
- }
254
- ```
255
-
256
- ## Plugin Architecture
257
-
258
- This plugin extends the TypeWeaver plugin system:
259
-
260
- ```typescript
261
- import { BasePlugin, type GeneratorContext } from "@rexeus/typeweaver-gen";
262
-
263
- export default class ClientsPlugin extends BasePlugin {
264
- public name = "clients";
265
-
266
- public override generate(context: GeneratorContext): void {
267
- // Generates API clients for each entity
119
+ if (response instanceof OtherSuccessResponse) {
120
+ // ... Handle "OtherSuccessResponse"
268
121
  }
269
- }
270
- ```
271
-
272
- ## Best Practices
273
-
274
- ### Client Configuration
275
-
276
- ```typescript
277
- // Environment-specific configuration
278
- const client = new UsersClient({
279
- baseURL: process.env.API_BASE_URL,
280
- timeout: parseInt(process.env.API_TIMEOUT || "5000"),
281
- headers: {
282
- "User-Agent": `${process.env.APP_NAME}/${process.env.APP_VERSION}`,
283
- },
284
- });
285
- ```
286
-
287
- ### Error Handling Strategy
288
-
289
- ```typescript
290
- // Centralized error handling
291
- async function handleApiCall<T>(operation: () => Promise<T>): Promise<T> {
292
- try {
293
- return await operation();
294
- } catch (error) {
295
- if (error instanceof ValidationErrorResponse) {
296
- // Log validation issues
297
- logger.warn("Validation error:", error.body.issues);
298
- } else if (error instanceof UnauthorizedErrorResponse) {
299
- // Handle auth errors
300
- redirectToLogin();
301
- }
302
- throw error;
122
+ // ...
123
+ } catch (error) {
124
+ if (error instanceof ValidationErrorResponse) {
125
+ // Handle validation errors
303
126
  }
304
- }
305
-
306
- // Usage
307
- const result = await handleApiCall(() =>
308
- client.send(new GetUserRequestCommand({ param: { userId: "123" } }))
309
- );
310
- ```
311
-
312
- ### Testing
313
-
314
- ```typescript
315
- // Mock clients for testing
316
- import { UsersClient } from "./api/generated";
317
-
318
- // Mock the client
319
- jest.mock("./api/generated/users/UsersClient");
320
-
321
- const mockClient = new UsersClient() as jest.Mocked<UsersClient>;
322
- mockClient.send.mockResolvedValue({
323
- statusCode: 200,
324
- body: { id: "123", name: "Test User" },
325
- });
326
- ```
327
-
328
- ## Integration Examples
329
-
330
- ### React Hook
331
-
332
- ```typescript
333
- import { useState, useEffect } from "react";
334
- import { UsersClient, GetUserRequestCommand } from "./api/generated";
335
-
336
- const client = new UsersClient({ baseURL: "https://api.example.com" });
337
-
338
- export function useUser(userId: string) {
339
- const [user, setUser] = useState(null);
340
- const [loading, setLoading] = useState(true);
341
- const [error, setError] = useState(null);
342
-
343
- useEffect(() => {
344
- async function fetchUser() {
345
- try {
346
- setLoading(true);
347
- const result = await client.send(
348
- new GetUserRequestCommand({
349
- param: { userId },
350
- })
351
- );
352
- setUser(result.body);
353
- } catch (err) {
354
- setError(err);
355
- } finally {
356
- setLoading(false);
357
- }
358
- }
359
-
360
- fetchUser();
361
- }, [userId]);
362
-
363
- return { user, loading, error };
364
- }
365
- ```
366
-
367
- ### Node.js Service
368
-
369
- ```typescript
370
- import { UsersClient, CreateUserRequestCommand } from "./api/generated";
371
-
372
- export class UserService {
373
- private client = new UsersClient({
374
- baseURL: process.env.API_BASE_URL,
375
- });
376
-
377
- async createUser(userData: CreateUserRequest["body"]) {
378
- const command = new CreateUserRequestCommand({
379
- body: userData,
380
- header: {
381
- Authorization: `Bearer ${process.env.API_TOKEN}`,
382
- },
383
- });
384
-
385
- return await this.client.send(command);
127
+ if (error instanceof InternalServerErrorResponse) {
128
+ // Handle internal server errors
386
129
  }
130
+ // ... Handle other errors
387
131
  }
388
132
  ```
389
133
 
390
- ## Troubleshooting
391
-
392
- ### Common Issues
393
-
394
- **Import errors**: Ensure all TypeWeaver plugins are installed **Type errors**: Regenerate code
395
- after API definition changes **Runtime errors**: Check that server API matches generated client
396
- expectations
397
-
398
- ### Debug Mode
399
-
400
- Enable verbose logging:
401
-
402
- ```typescript
403
- const client = new UsersClient({
404
- baseURL: "https://api.example.com",
405
- debug: true, // Enable debug logging
406
- });
407
- ```
408
-
409
- ## License
134
+ ## ๐Ÿ“„ License
410
135
 
411
- ISC ยฉ Dennis Wentzien 2025
136
+ Apache 2.0 ยฉ Dennis Wentzien 2025
package/dist/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Dennis Wentzien
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/dist/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Copyright 2025 Dennis Wentzien
2
+
3
+ This project is licensed under the Apache License, Version 2.0
4
+ See LICENSE file for details.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { BasePlugin } from '@rexeus/typeweaver-gen';
2
1
  import path from 'path';
3
- import Case from 'case';
4
2
  import { fileURLToPath } from 'url';
3
+ import { BasePlugin } from '@rexeus/typeweaver-gen';
5
4
  import { TsTypePrinter, TsTypeNode } from '@rexeus/typeweaver-zod-to-ts';
5
+ import Case from 'case';
6
6
 
7
7
  const __dirname$1 = path.dirname(fileURLToPath(import.meta.url));
8
8
  class ClientGenerator {
@@ -13,13 +13,13 @@ class ClientGenerator {
13
13
  "templates",
14
14
  "RequestCommand.ejs"
15
15
  );
16
- for (const [, operationResources] of Object.entries(
16
+ for (const [, entityResource] of Object.entries(
17
17
  context.resources.entityResources
18
18
  )) {
19
- this.writeClient(clientTemplatePath, operationResources, context);
19
+ this.writeClient(clientTemplatePath, entityResource.operations, context);
20
20
  this.writeRequestCommands(
21
21
  commandTemplatePath,
22
- operationResources,
22
+ entityResource.operations,
23
23
  context
24
24
  );
25
25
  }
@@ -80,30 +80,34 @@ class ClientGenerator {
80
80
  const pascalCaseOperationId = Case.pascal(operationId);
81
81
  const allResponses = responses;
82
82
  const ownSuccessResponses = allResponses.filter(
83
- (r) => r.statusCode >= 200 && r.statusCode < 300 && !r.isShared
83
+ (r) => r.statusCode >= 200 && r.statusCode < 300 && !r.isReference
84
84
  );
85
85
  const ownErrorResponses = allResponses.filter(
86
- (r) => (r.statusCode < 200 || r.statusCode >= 300) && !r.isShared
86
+ (r) => (r.statusCode < 200 || r.statusCode >= 300) && !r.isReference
87
87
  );
88
88
  const sharedSuccessResponses = allResponses.filter(
89
- (r) => r.statusCode >= 200 && r.statusCode < 300 && r.isShared
89
+ (r) => r.statusCode >= 200 && r.statusCode < 300 && r.isReference
90
90
  );
91
91
  const sharedErrorResponses = allResponses.filter(
92
- (r) => (r.statusCode < 200 || r.statusCode >= 300) && r.isShared
92
+ (r) => (r.statusCode < 200 || r.statusCode >= 300) && r.isReference
93
93
  );
94
94
  const headerTsType = request.header ? TsTypePrinter.print(TsTypeNode.fromZod(request.header)) : void 0;
95
95
  const paramTsType = request.param ? TsTypePrinter.print(TsTypeNode.fromZod(request.param)) : void 0;
96
96
  const queryTsType = request.query ? TsTypePrinter.print(TsTypeNode.fromZod(request.query)) : void 0;
97
97
  const bodyTsType = request.body ? TsTypePrinter.print(TsTypeNode.fromZod(request.body)) : void 0;
98
98
  const successResponseImportPath = (response) => {
99
- if (response.isShared && response.path) {
99
+ if (response.isReference && response.path) {
100
100
  return response.path;
101
101
  }
102
102
  return `./${path.basename(outputResponseFileName, ".ts")}`;
103
103
  };
104
104
  const requestFile = `./${path.basename(outputRequestFileName, ".ts")}`;
105
105
  const responseValidatorFile = `./${path.basename(outputResponseValidationFileName, ".ts")}`;
106
- const sourcePath = path.join(sourceDir, path.basename(sourceFile, ".ts"));
106
+ const relativeSourceFile = path.relative(sourceDir, sourceFile);
107
+ const sourcePath = path.join(
108
+ sourceDir,
109
+ relativeSourceFile.replace(/\.ts$/, "")
110
+ );
107
111
  const relativeSourcePath = path.relative(outputDir, sourcePath);
108
112
  const content = context.renderTemplate(templateFilePath, {
109
113
  sourcePath: relativeSourcePath,
@@ -1,16 +1,25 @@
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
8
+ import axios, { AxiosError } from "axios";
1
9
  import type {
2
- IHttpQuery,
3
- IHttpParam,
4
10
  IHttpHeader,
11
+ IHttpParam,
12
+ IHttpQuery,
5
13
  IHttpResponse,
6
14
  } from "@rexeus/typeweaver-core";
7
15
  import { RequestCommand } from "./RequestCommand";
8
- import axios, {
9
- AxiosError,
10
- type AxiosInstance,
11
- type AxiosResponse,
12
- } from "axios";
13
- import Case from "case";
16
+ import type { ProcessResponseOptions } from "./RequestCommand";
17
+ import type { AxiosHeaderValue, AxiosInstance, AxiosResponse } from "axios";
18
+
19
+ /**
20
+ * Configuration options for handling unknown responses.
21
+ */
22
+ export type UnknownResponseHandling = "throw" | "passthrough";
14
23
 
15
24
  /**
16
25
  * Configuration options for ApiClient initialization.
@@ -20,6 +29,10 @@ export type ApiClientProps = {
20
29
  axiosInstance?: AxiosInstance;
21
30
  /** Base URL for API requests. If not provided, must be set in axiosInstance */
22
31
  baseUrl?: string;
32
+ /** How to handle unknown responses. Defaults to "throw" */
33
+ unknownResponseHandling?: UnknownResponseHandling;
34
+ /** Predicate to determine if a status code represents success. Defaults to 2xx status codes */
35
+ isSuccessStatusCode?: (statusCode: number) => boolean;
23
36
  };
24
37
 
25
38
  /**
@@ -37,6 +50,10 @@ export abstract class ApiClient {
37
50
  public readonly axiosInstance: AxiosInstance;
38
51
  /** The base URL for all API requests */
39
52
  public readonly baseUrl: string;
53
+ /** How to handle unknown responses */
54
+ public readonly unknownResponseHandling: UnknownResponseHandling;
55
+ /** Predicate to determine if a status code represents success */
56
+ public readonly isSuccessStatusCode: (statusCode: number) => boolean;
40
57
 
41
58
  /**
42
59
  * Creates a new ApiClient instance.
@@ -53,6 +70,24 @@ export abstract class ApiClient {
53
70
  "Base URL must be provided either in axios instance or in constructor"
54
71
  );
55
72
  }
73
+
74
+ this.unknownResponseHandling = props.unknownResponseHandling ?? "throw";
75
+ this.isSuccessStatusCode =
76
+ props.isSuccessStatusCode ??
77
+ ((statusCode: number) => statusCode >= 200 && statusCode < 300);
78
+ }
79
+
80
+ /**
81
+ * Gets the process response options for this client instance.
82
+ *
83
+ * @returns The configuration options for processing responses
84
+ * @protected
85
+ */
86
+ protected get processResponseOptions(): ProcessResponseOptions {
87
+ return {
88
+ unknownResponseHandling: this.unknownResponseHandling,
89
+ isSuccessStatusCode: this.isSuccessStatusCode,
90
+ };
56
91
  }
57
92
 
58
93
  /**
@@ -109,28 +144,17 @@ export abstract class ApiClient {
109
144
  throw new Error("Network error: Unknown error");
110
145
  }
111
146
 
112
- throw new Error(`Network error: ${error instanceof Error ? error.message : String(error)}`);
147
+ throw new Error(
148
+ `Network error: ${error instanceof Error ? error.message : String(error)}`
149
+ );
113
150
  }
114
151
  }
115
152
 
116
153
  private createResponse(response: AxiosResponse): IHttpResponse {
117
- const header: IHttpHeader = Object.entries(response.headers).reduce(
118
- (acc, [key, value]) => {
119
- if (!value) {
120
- return acc;
121
- }
122
-
123
- const lowerCaseKey = key.toLowerCase();
124
- const headerCaseKey = Case.header(lowerCaseKey);
125
-
126
- return {
127
- ...acc,
128
- [headerCaseKey]: value,
129
- [lowerCaseKey]: value,
130
- };
131
- },
132
- {}
133
- );
154
+ const header: IHttpHeader = {};
155
+ Object.entries(response.headers).forEach(([key, value]) => {
156
+ this.addMultiValue(header, key, String(value));
157
+ });
134
158
 
135
159
  return {
136
160
  body: response.data,
@@ -177,13 +201,32 @@ export abstract class ApiClient {
177
201
 
178
202
  private createUrl(path: string, query?: IHttpQuery): string {
179
203
  const url = new URL(path, this.baseUrl);
180
-
181
204
  this.addQuery(url, query);
182
-
183
205
  return url.toString();
184
206
  }
185
207
 
186
208
  private createHeader(header: any): any {
187
209
  return header;
188
210
  }
211
+
212
+ private addMultiValue(
213
+ record: Record<string, string | string[]>,
214
+ key: string,
215
+ value: AxiosHeaderValue
216
+ ): void {
217
+ const existing = record[key];
218
+ const preparedValue = Array.isArray(value)
219
+ ? value.map(String)
220
+ : [String(value)];
221
+ if (existing) {
222
+ if (Array.isArray(existing)) {
223
+ existing.push(...preparedValue);
224
+ } else {
225
+ record[key] = [existing, ...preparedValue];
226
+ }
227
+ } else {
228
+ record[key] =
229
+ preparedValue.length > 1 ? preparedValue : (preparedValue[0] as string);
230
+ }
231
+ }
189
232
  }
@@ -1,13 +1,29 @@
1
- import {
2
- type HttpMethod,
3
- type IHttpRequest,
4
- type IHttpHeader,
5
- type IHttpParam,
6
- type IHttpQuery,
7
- type IHttpBody,
8
- type IHttpResponse,
9
- HttpResponse,
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
8
+ import { HttpResponse } from "@rexeus/typeweaver-core";
9
+ import type {
10
+ HttpMethod,
11
+ IHttpBody,
12
+ IHttpHeader,
13
+ IHttpParam,
14
+ IHttpQuery,
15
+ IHttpRequest,
16
+ IHttpResponse,
10
17
  } from "@rexeus/typeweaver-core";
18
+ import type { UnknownResponseHandling } from "./ApiClient";
19
+
20
+ /**
21
+ * Configuration options for processing HTTP responses.
22
+ */
23
+ export type ProcessResponseOptions = {
24
+ readonly unknownResponseHandling: UnknownResponseHandling;
25
+ readonly isSuccessStatusCode: (statusCode: number) => boolean;
26
+ };
11
27
 
12
28
  /**
13
29
  * Abstract base class for type-safe API request commands.
@@ -55,7 +71,11 @@ export abstract class RequestCommand<
55
71
  * - Error response handling
56
72
  *
57
73
  * @param response - The raw HTTP response from the server
74
+ * @param options - Configuration options for response processing
58
75
  * @returns The processed, type-safe response object
59
76
  */
60
- public abstract processResponse(response: IHttpResponse): HttpResponse;
77
+ public abstract processResponse(
78
+ response: IHttpResponse,
79
+ options: ProcessResponseOptions
80
+ ): HttpResponse;
61
81
  }
package/dist/lib/index.ts CHANGED
@@ -1,2 +1,9 @@
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
1
8
  export * from "./ApiClient";
2
9
  export * from "./RequestCommand";
@@ -1,7 +1,17 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * This file was automatically generated by typeweaver.
4
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
5
+ *
6
+ * @generated by @rexeus/typeweaver
7
+ */
8
+
1
9
  import { ApiClient, type ApiClientProps } from "../lib/clients";
2
10
  <% for (const operation of operations) { %>
3
11
  import { <%= operation.operationId %>RequestCommand } from "./<%= operation.operationId %>RequestCommand";
4
- import type { Successful<%= operation.operationId %>Response } from "<%= operation.requestFile %>";
12
+ import type {
13
+ Successful<%= operation.operationId %>Response
14
+ } from "<%= operation.requestFile %>";
5
15
  <% } %>
6
16
 
7
17
  export type <%= pascalCaseEntityName %>RequestCommands =
@@ -25,16 +35,6 @@ export class <%= pascalCaseEntityName %>Client extends ApiClient {
25
35
  <% } %>
26
36
  public async send(command: <%= pascalCaseEntityName %>RequestCommands): Promise<Successful<%= pascalCaseEntityName %>Responses> {
27
37
  const response = await this.execute(command);
28
-
29
- switch (true) {
30
- <% for (const operation of operations) { %>
31
- case command instanceof <%= operation.operationId %>RequestCommand: {
32
- return command.processResponse(response);
33
- }
34
- <% } %>
35
- default: {
36
- throw new Error("Command is not supported");
37
- }
38
- }
38
+ return command.processResponse(response, this.processResponseOptions);
39
39
  }
40
40
  }
@@ -1,6 +1,14 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * This file was automatically generated by typeweaver.
4
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
5
+ *
6
+ * @generated by @rexeus/typeweaver
7
+ */
8
+
1
9
  import definition from "<%= sourcePath %>";
2
- import { HttpMethod, type IHttpResponse } from "@rexeus/typeweaver-core";
3
- import { RequestCommand } from "../lib/clients";
10
+ import { HttpMethod, type IHttpResponse, ResponseValidationError, UnknownResponse } from "@rexeus/typeweaver-core";
11
+ import { RequestCommand, type ProcessResponseOptions } from "../lib/clients";
4
12
  import { <%= pascalCaseOperationId %>ResponseValidator } from "<%= responseValidatorFile %>";
5
13
  import type {
6
14
  I<%= pascalCaseOperationId %>Request,
@@ -47,15 +55,36 @@ export class <%= pascalCaseOperationId %>RequestCommand extends RequestCommand i
47
55
  this.responseValidator = new <%= pascalCaseOperationId %>ResponseValidator();
48
56
  }
49
57
 
50
- public processResponse(response: IHttpResponse): Successful<%= pascalCaseOperationId %>Response {
51
- const result = this.responseValidator.validate(response);
58
+ public processResponse(
59
+ response: IHttpResponse,
60
+ options: ProcessResponseOptions
61
+ ): Successful<%= pascalCaseOperationId %>Response {
62
+ try {
63
+ const result = this.responseValidator.validate(response);
52
64
 
53
- <% for (const successResponse of [...ownSuccessResponses, ...sharedSuccessResponses]) { %>
54
- if (result instanceof <%= successResponse.name %>Response) {
55
- return result;
56
- }
57
- <% } %>
65
+ <% for (const successResponse of [...ownSuccessResponses, ...sharedSuccessResponses]) { %>
66
+ if (result instanceof <%= successResponse.name %>Response) {
67
+ return result;
68
+ }
69
+ <% } %>
58
70
 
59
- throw result;
71
+ throw result;
72
+ } catch (error) {
73
+ if (error instanceof ResponseValidationError) {
74
+ const unknownResponse = new UnknownResponse(
75
+ response.statusCode,
76
+ response.header,
77
+ response.body,
78
+ error
79
+ );
80
+
81
+ if (options.unknownResponseHandling === "passthrough" && options.isSuccessStatusCode(response.statusCode)) {
82
+ return unknownResponse as any;
83
+ }
84
+
85
+ throw unknownResponse;
86
+ }
87
+ throw error;
88
+ }
60
89
  }
61
90
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rexeus/typeweaver-clients",
3
- "version": "0.0.3",
4
- "description": "HTTP client generator for TypeWeaver API framework",
3
+ "version": "0.1.0",
4
+ "description": "HTTP client generator for typeweaver API framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -14,7 +14,9 @@
14
14
  "files": [
15
15
  "dist",
16
16
  "package.json",
17
- "README.md"
17
+ "README.md",
18
+ "LICENSE",
19
+ "NOTICE"
18
20
  ],
19
21
  "keywords": [
20
22
  "api",
@@ -26,7 +28,7 @@
26
28
  "typeweaver"
27
29
  ],
28
30
  "author": "Dennis Wentzien <dw@rexeus.com>",
29
- "license": "ISC",
31
+ "license": "Apache-2.0",
30
32
  "repository": {
31
33
  "type": "git",
32
34
  "url": "git+https://github.com/rexeus/typeweaver.git",
@@ -38,22 +40,25 @@
38
40
  "homepage": "https://github.com/rexeus/typeweaver#readme",
39
41
  "peerDependencies": {
40
42
  "axios": "^1.7.0",
41
- "@rexeus/typeweaver-core": "^0.0.3",
42
- "@rexeus/typeweaver-gen": "^0.0.3"
43
+ "@rexeus/typeweaver-core": "^0.1.0",
44
+ "@rexeus/typeweaver-gen": "^0.1.0"
43
45
  },
44
46
  "devDependencies": {
45
- "axios": "^1.9.0",
46
- "@rexeus/typeweaver-core": "^0.0.3",
47
- "@rexeus/typeweaver-gen": "^0.0.3"
47
+ "@hono/node-server": "^1.19.1",
48
+ "axios": "^1.11.0",
49
+ "test-utils": "file:../test-utils",
50
+ "@rexeus/typeweaver-gen": "^0.1.0",
51
+ "@rexeus/typeweaver-core": "^0.1.0"
48
52
  },
49
53
  "dependencies": {
50
54
  "case": "^1.6.3",
51
- "@rexeus/typeweaver-zod-to-ts": "^0.0.3"
55
+ "@rexeus/typeweaver-zod-to-ts": "^0.1.0"
52
56
  },
53
57
  "scripts": {
54
58
  "typecheck": "tsc --noEmit",
55
59
  "format": "prettier --write .",
56
- "build": "pkgroll --clean-dist && cp -r ./src/templates ./dist/templates && cp -r ./src/lib ./dist/lib",
60
+ "build": "pkgroll --clean-dist && cp -r ./src/templates ./dist/templates && cp -r ./src/lib ./dist/lib && cp ../../LICENSE ../../NOTICE ./dist/",
61
+ "test": "vitest --run",
57
62
  "preversion": "npm run build"
58
63
  }
59
64
  }