@appweaver/skill 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,884 @@
1
+ # Client
2
+
3
+ `@appweaver/client` is a type-safe HTTP client generator and runtime library for consuming Appweaver APIs. It has two
4
+ distinct parts:
5
+
6
+ - **`weaver-client` CLI** — reads an OpenAPI v3 schema and emits TypeScript types and a typed client class.
7
+ - **Runtime library** — provides `FetchClient` and a set of module clients used directly in application code.
8
+
9
+ ---
10
+
11
+ ## Module formats (ESM & CommonJS)
12
+
13
+ The package ships **both** an ESM and a CommonJS build, selected automatically via the `exports` map — no configuration
14
+ needed. Both import styles work for the main entry and the `/angular` subpath:
15
+
16
+ ```ts
17
+ // ESM (tree-shakable — preferred for bundlers like Angular/Vite/webpack prod builds)
18
+ import { FetchClient, ClientError } from '@appweaver/client';
19
+ import { AngularClient } from '@appweaver/client/angular';
20
+
21
+ // CommonJS (e.g. plain Node scripts without a build step)
22
+ const { FetchClient, ClientError } = require('@appweaver/client');
23
+ const { AngularClient } = require('@appweaver/client/angular');
24
+ ```
25
+
26
+ ---
27
+
28
+ ## `weaver-client` CLI
29
+
30
+ ```
31
+ weaver-client <command>
32
+ ```
33
+
34
+ | Command | Alias | Description |
35
+ |-------------|-------|-------------------------------------------------|
36
+ | `generate` | `g` | Generate TypeScript types and/or a client class |
37
+ | `--version` | `-v` | Output package version |
38
+ | `--help` | `-h` | Output usage information |
39
+
40
+ ---
41
+
42
+ ### `weaver-client generate`
43
+
44
+ ```
45
+ weaver-client generate|g <schema-path> [options]
46
+ ```
47
+
48
+ Reads an OpenAPI v3 schema and generates TypeScript types and a typed client class.
49
+
50
+ **Arguments:**
51
+
52
+ | Argument | Description |
53
+ |-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
54
+ | `<schema-path>` | Path to the OpenAPI schema. Accepts a relative or absolute file path (including a Windows drive path such as `C:\api\openapi.json`) or a URL (`http://`, `https://`, `file://`). JSON and YAML formats are both supported. |
55
+
56
+ **Options:**
57
+
58
+ | Option | Description | Default |
59
+ |----------------------------|----------------------------------------------------------------------------------------------|---------------------------|
60
+ | `--types-only` | Generate TypeScript types only, skip client class generation | `false` |
61
+ | `--client-only` | Generate client class only, skip TypeScript types generation | `false` |
62
+ | `-o, --output-path <path>` | Output path of the client (and of the types with `--types-only`) | `./generated/client.ts` |
63
+ | `--types-path <path>` | Output path of the types, the output path for a single file | `<output>.types.ts` |
64
+ | `--client-path <path>` | Output path for generated client class only | same as `--output-path` |
65
+ | `--client-name <name>` | Custom name for the generated client class | derived from schema title |
66
+ | `--framework <framework>` | Framework for the generated client class (`fetch` or `angular`) | `fetch` |
67
+ | `--no-types` | Generate an untyped client class, without the TypeScript types | typed |
68
+ | `--comments` | Keep the descriptions and the constraints of the schema as doc comments of the types | false |
69
+
70
+ **Generation process:**
71
+
72
+ 1. Reads and parses the schema (JSON or YAML, local or remote).
73
+ 2. Generates TypeScript interfaces via `openapi-typescript`. With `--comments`, they keep the descriptions of the schema
74
+ and JSDoc validation tags (`@minLength`, `@maxLength`, `@minimum`, `@maximum`, `@pattern`, `@format`); without it,
75
+ the default, no doc comment is written.
76
+ 3. Deduplicates union types and extracts inline schemas to named exported types, including the ones carrying a
77
+ description (i.e. `PostQuerySort`).
78
+ 4. Hoists the schemas the document repeats inline into a shared definition each, so the generated types declare them
79
+ once and reference them everywhere else. This covers the enums (every sortable field of every resource shares one
80
+ `SortDirection` rather than declaring an `asc | desc` enum of its own) and the value a filterable field accepts
81
+ (`QueryFilterValue`, built from the plain `QueryFilterScalar`), while every property keeps its own description.
82
+ 5. Emits every enum as a constant object plus a type alias of its values, so both the member (`SortDirection.asc`) and
83
+ the plain literal (`'asc'`) are accepted wherever the enum is used. When the types are written to a declaration file
84
+ (`.d.ts`), the constant is declared rather than initialized, since such a file carries no runtime values.
85
+ 6. Classifies all API paths into route groups: resources, auth, account, health, files, and custom. `paths` keeps the
86
+ custom routes only, the module and resource clients typing their requests by their module types; the other routes
87
+ keep their error codes in `routeErrors`, so `RouteErrorCode` and `isRouteError` type every route.
88
+ 7. Derives the types of a resource that equal another one instead of declaring them again: `Replace` and
89
+ `RelationCreate` as `Create`, `Update` as `Partial<Create>`, `Multiple` as `Single` or `Omit<Single, ...>`, and
90
+ `ExportRequest` as `Pick<QueryRequest, 'filter' | 'sort'>`.
91
+ 8. Emits a typed client class extending `FetchClient<Paths>` with a property for each route group. A resource lists its
92
+ omitted operations, or its used ones (`{ only: [...] }`) when shorter, and the operations its model cannot have
93
+ (files, time series) are left out by the types of the library.
94
+ 9. Formats all output with Prettier.
95
+ 10. Writes the client and the types (`client.ts` and `client.types.ts` by default), the client re-exporting the types,
96
+ each with an autogenerated header comment.
97
+
98
+ **Examples:**
99
+
100
+ ```bash
101
+ # Generate the client and its types from a local OpenAPI file (client.ts and client.types.ts)
102
+ weaver-client generate ./openapi.json --output-path ./src/generated/client.ts
103
+
104
+ # Generate the client and its types into a single file, with the doc comments
105
+ weaver-client generate ./openapi.json -o ./src/generated/client.ts --types-path ./src/generated/client.ts --comments
106
+
107
+ # Generate types + client from a running server
108
+ weaver-client generate http://localhost:3000/openapi.json --output-path ./src/generated/client.ts
109
+
110
+ # Generate types only
111
+ weaver-client generate ./openapi.json --types-only --output-path ./src/types/api.ts
112
+
113
+ # Generate client class only
114
+ weaver-client generate ./openapi.json --client-only --output-path ./src/client.ts
115
+
116
+ # Generate client class without TypeScript types
117
+ weaver-client generate ./openapi.json --no-types --output-path ./src/client.ts
118
+
119
+ # Separate output files with a custom class name
120
+ weaver-client generate ./openapi.json \
121
+ --types-path ./src/types/api.ts \
122
+ --client-path ./src/client.ts \
123
+ --client-name CmsApiClient
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Typical end-to-end workflow
129
+
130
+ The specification comes from [`weaver openapi`](./cli.md#weaver-openapi) of the API project:
131
+
132
+ ```bash
133
+ # 1. Export the OpenAPI spec from the running Appweaver API
134
+ weaver openapi --output-path ./openapi.json
135
+
136
+ # 2. Generate the typed client
137
+ weaver-client generate ./openapi.json --output-path ./generated/client.ts
138
+
139
+ # 3. Use the generated client in application code
140
+ import { createClient } from './generated/client';
141
+
142
+ const client = createClient({ baseUrl: 'http://localhost:3000', auth: { jwt: 'token' } });
143
+ const users = await client.user.query({ filter: { enabled: true } });
144
+ ```
145
+
146
+ ---
147
+
148
+ ## Generated output
149
+
150
+ Running `weaver-client generate` produces the client and its types in two files by default (`client.ts` and
151
+ `client.types.ts`), the client re-exporting the types, so every type is imported from the client.
152
+
153
+ ### Types file
154
+
155
+ Contains all TypeScript interfaces and type aliases derived from the OpenAPI schema. The key export is the `paths`
156
+ type used to parameterise `FetchClient`, holding the custom routes and the error codes of the other ones
157
+ (`routeErrors`). Module-level types (`AuthModuleType`, `AccountModuleType`, `HealthModuleType`, per-resource
158
+ `*ResourceModuleType`, holding only the kinds of types the resource has) are also exported and consumed by the client
159
+ class.
160
+
161
+ Every schema definition becomes an exported type named after it, so the request and response shapes can be referenced
162
+ directly. The per-resource module type holds the same types under the keys the `ResourceClient` methods use:
163
+
164
+ ```ts
165
+ import { PostQuerySort, SortDirection } from './generated/client';
166
+
167
+ const sort: PostQuerySort = {
168
+ createdAt: SortDirection.desc,
169
+ title: SortDirection.asc
170
+ };
171
+ const posts = await client.post.query({ sort, page: 1, size: 20 });
172
+ ```
173
+
174
+ Enums are generated as a constant object together with a type alias of its values, so the members and the raw literals
175
+ are interchangeable and no import is needed for the literal form:
176
+
177
+ ```ts
178
+ export const SortDirection = { asc: 'asc', desc: 'desc' } as const;
179
+ export type SortDirection = (typeof SortDirection)[keyof typeof SortDirection];
180
+
181
+ // Both are valid and equally type safe
182
+ const byMember: PostQuerySort = { createdAt: SortDirection.desc };
183
+ const byLiteral: PostQuerySort = { createdAt: 'desc' };
184
+ ```
185
+
186
+ The value a filterable field accepts is declared once as well, rather than being spelled out again for every field of
187
+ every resource. A scalar field references `QueryFilterValue`, and a relation field adds the filter of the related
188
+ resource to the plain values it accepts:
189
+
190
+ ```ts
191
+ export type QueryFilterScalar = string | number | boolean | null;
192
+ export type QueryFilterValue =
193
+ | QueryFilterScalar
194
+ | QueryFilterScalar[]
195
+ | QueryCondition;
196
+
197
+ export type PostQueryFilter = {
198
+ /** @description Filter by the title field */
199
+ title?: QueryFilterValue;
200
+ /** @description Filter by the author relation, matching an id, a list of ids, or a nested User filter */
201
+ author?:
202
+ | QueryFilterScalar
203
+ | QueryFilterScalar[]
204
+ | UserQueryFilter
205
+ | UserQueryFilter[];
206
+ // ...
207
+ };
208
+ ```
209
+
210
+ ### Client file
211
+
212
+ ```ts
213
+ // Generated by Appweaver. Please do not edit this file manually.
214
+
215
+ import { ClientConfig, FetchClient } from '@appweaver/client';
216
+ import * as Type from './client.types';
217
+
218
+ export * from './client.types';
219
+
220
+ export class CMSAPIClient extends FetchClient<Type.paths> {
221
+ public auth = this.authClient<Type.AuthModuleType>('/auth');
222
+
223
+ public account = this.accountClient<Type.AccountModuleType>('/auth/account');
224
+
225
+ public health = this.healthClient<Type.HealthModuleType>('/health');
226
+
227
+ public files = this.filesClient('/files');
228
+
229
+ // Resource with some operations excluded (compile-time Omit)
230
+ public apiKey = this.resourceClient<
231
+ Type.ApiKeyResourceModuleType,
232
+ ['aggregate', 'export']
233
+ >('/api/api-keys');
234
+
235
+ // Resource with only a few operations, listed instead of the omitted ones
236
+ public role = this.resourceClient<
237
+ Type.RoleResourceModuleType,
238
+ { only: ['find', 'query'] }
239
+ >('/api/roles');
240
+
241
+ public post = this.resourceClient<Type.PostResourceModuleType, ['delete']>(
242
+ '/api/posts'
243
+ );
244
+
245
+ public user = this.resourceClient<Type.UserResourceModuleType>('/api/users');
246
+
247
+ // Custom routes that don't match a standard module
248
+ public info = this.customRequest('get', '/api/');
249
+ public postApiPublishPosts = this.customRequest('post', '/api/publish-posts');
250
+ }
251
+
252
+ export function createClient(config: ClientConfig): CMSAPIClient {
253
+ return new CMSAPIClient(config);
254
+ }
255
+ ```
256
+
257
+ The generated second type argument to `resourceClient` (e.g., `['aggregate', 'export']`, or `{ only: ['find', 'query'] }`)
258
+ removes the omitted methods from the returned `ResourceClient` at the TypeScript level, preventing accidental calls to
259
+ operations not exposed by the API. The file and time series methods of a resource whose module type has no `files` or
260
+ `seriesQuery` are removed without being listed.
261
+
262
+ When a `query` or `aggregate` route is GET-only, the generator passes `{ query: 'get' }` (or `aggregate`), and the
263
+ client sends the request as query parameters. With both methods available, it uses POST.
264
+
265
+ ```ts
266
+ tag = this.resourceClient<Type.TagResourceModuleType>('/api/tags', {
267
+ query: 'get'
268
+ });
269
+ ```
270
+
271
+ ### Angular client (`--framework angular`)
272
+
273
+ Passing `--framework angular` generates a client class extending `AngularClient` instead of `FetchClient`. The generated
274
+ class is constructed with Angular's `HttpClient` and all its methods return RxJS `Observable`s instead of
275
+ `Promise`s:
276
+
277
+ ```ts
278
+ import { ClientConfig, ClientError } from '@appweaver/client';
279
+ import { AngularClient } from '@appweaver/client/angular';
280
+ import { HttpClient } from '@angular/common/http';
281
+
282
+ // In an Angular service or provider:
283
+ const client = new CMSAPIClient(httpClient, {
284
+ baseUrl: 'http://localhost:3000'
285
+ });
286
+ client.user.query({ filter: { enabled: true } }).subscribe((users) => {});
287
+ ```
288
+
289
+ An error response reaches the `error` callback as a `ClientError`, as with `FetchClient`, not as Angular's
290
+ `HttpErrorResponse`. Only a network error (status 0) is passed on as the `HttpErrorResponse` itself:
291
+
292
+ ```ts
293
+ client.user.find(123).subscribe({
294
+ error: (err) => {
295
+ if (isApiError(err) && err.is(ErrorCode.ResourceNotFound)) {
296
+ // the user does not exist
297
+ }
298
+ }
299
+ });
300
+ ```
301
+
302
+ **Important:** `AngularClient` is only available from the `@appweaver/client/angular` subpath — it is not exported from
303
+ the main `@appweaver/client` entry point. This keeps `rxjs` completely out of the module graph (runtime and types) for
304
+ `FetchClient` users. `rxjs` is an **optional peer dependency**: Angular projects already have it installed, while
305
+ fetch-only projects do not need it at all.
306
+
307
+ ---
308
+
309
+ ## Runtime library
310
+
311
+ ### `ClientConfig`
312
+
313
+ ```ts
314
+ type ClientConfig = {
315
+ baseUrl: string; // Base URL prepended to every request path
316
+ timeout?: number; // Request timeout in milliseconds
317
+ middlewares?: Middleware[]; // Additional openapi-fetch middlewares
318
+ auth?: AuthConfig; // Authentication strategy
319
+ fetch?: FetchHandler; // Custom fetch implementation
320
+ realtime?: RealtimeClientOptions; // Options of client.realtime
321
+ };
322
+ ```
323
+
324
+ ### Authentication
325
+
326
+ Exactly one authentication strategy may be provided via `auth`. Each strategy accepts a static value, a typed config
327
+ object, or an async function that receives the outgoing `Request` and returns the auth value dynamically.
328
+
329
+ ```ts
330
+ // JWT Bearer — plain token string
331
+ let client = createClient({
332
+ baseUrl: 'https://api.example.com',
333
+ auth: { jwt: 'my-access-token' }
334
+ });
335
+
336
+ // JWT Bearer — object with optional refresh token
337
+ client = createClient({
338
+ baseUrl: 'https://api.example.com',
339
+ auth: { jwt: { accessToken: 'access', refreshToken: 'refresh' } }
340
+ });
341
+
342
+ // JWT Bearer — dynamic async function
343
+ client = createClient({
344
+ baseUrl: 'https://api.example.com',
345
+ auth: { jwt: async (req) => await tokenStore.getToken() }
346
+ });
347
+
348
+ // API Key — plain string (uses X-Api-Key header by default)
349
+ client = createClient({
350
+ baseUrl: 'https://api.example.com',
351
+ auth: { apiKey: 'my-api-key' }
352
+ });
353
+
354
+ // API Key — custom header name
355
+ client = createClient({
356
+ baseUrl: 'https://api.example.com',
357
+ auth: { apiKey: { key: 'my-api-key', header: 'X-Custom-Key' } }
358
+ });
359
+
360
+ // HTTP Basic — plain Base64 string
361
+ client = createClient({
362
+ baseUrl: 'https://api.example.com',
363
+ auth: { basic: btoa('user:pass') }
364
+ });
365
+
366
+ // HTTP Basic — username/password object (auto-encodes)
367
+ client = createClient({
368
+ baseUrl: 'https://api.example.com',
369
+ auth: { basic: { username: 'user', password: 'pass' } }
370
+ });
371
+ ```
372
+
373
+ ### Request timeout
374
+
375
+ ```ts
376
+ const client = createClient({
377
+ baseUrl: 'https://api.example.com',
378
+ timeout: 5000 // abort requests after 5 seconds
379
+ });
380
+ ```
381
+
382
+ ### Custom middlewares
383
+
384
+ Additional `openapi-fetch` middlewares are applied after the built-in timeout and auth middlewares:
385
+
386
+ ```ts
387
+ const client = createClient({
388
+ baseUrl: 'https://api.example.com',
389
+ middlewares: [
390
+ {
391
+ async onRequest({ request }) {
392
+ request.headers.set('X-Request-Id', crypto.randomUUID());
393
+ return request;
394
+ }
395
+ }
396
+ ]
397
+ });
398
+ ```
399
+
400
+ ---
401
+
402
+ ## Module clients
403
+
404
+ ### `ResourceClient`
405
+
406
+ Exposes CRUD and file operations for a single resource endpoint. The `filter` and `sort` of `query`, `aggregate` and
407
+ `export` take the syntax of [resources.md](./resources.md#query-filters).
408
+
409
+ | Method | HTTP | Description |
410
+ |----------------------------------------------|----------------------------------------------|------------------------------------------------------------------|
411
+ | `find(id, options?)` | `GET /{resource}/{id}` | Fetch a single record by ID |
412
+ | `query(request, options?)` | `POST /{resource}/query` | Filter, sort, and paginate the collection |
413
+ | `aggregate(request, options?)` | `POST /{resource}/aggregate` | Aggregation query (count, sum, avg, etc.) |
414
+ | `create(resource, options?)` | `POST /{resource}` | Create a new record |
415
+ | `update(resource, options?)` | `PATCH /{resource}/{id}` | Update an existing record (`resource` must include `id`) |
416
+ | `replace(resource, options?)` | `PUT /{resource}/{id}` | Replace a whole record (`resource` must include `id`) |
417
+ | `delete(id, options?)` | `DELETE /{resource}/{id}` | Delete a record by ID |
418
+ | `export(request, options?)` | `POST /{resource}/export` | Export collection as a file; returns `FileDataResponse` |
419
+ | `uploadFiles(files, options?)` | `POST /{resource}/{id}/files` | Upload files to a record |
420
+ | `deleteFiles(files, options?)` | `POST /{resource}/{id}/delete-files` | Remove files from a record |
421
+ | `fileVersions(id, name, options?)` | `GET /{resource}/{id}/file-versions` | List the versions of a file, newest first |
422
+ | `deleteFileVersions(id, versions, options?)` | `POST /{resource}/{id}/delete-file-versions` | Delete versions of files |
423
+ | `bulkCreate(resources, options?)` | `POST /{resource}/bulk` | Create many records (all or none) |
424
+ | `bulkUpdate(items, options?)` | `PATCH /{resource}/bulk` | Update many `{ id, data }` items |
425
+ | `bulkReplace(items, options?)` | `PUT /{resource}/bulk` | Replace many `{ id, data }` items |
426
+ | `bulkDelete(ids, options?)` | `DELETE /{resource}/bulk` | Delete many records by ID |
427
+ | `writeSeries(id, points, options?)` | `POST /{resource}/{id}/series` | Write time series points, `{ direct: true }` skips the queue |
428
+ | `writeManySeries(points, options?)` | `POST /{resource}/series` | Write the points of many records, each with `resourceId` |
429
+ | `querySeries(id, query?, options?)` | `GET /{resource}/{id}/series` | Query the points, `fields` an array, by `bucket` and `aggregate` |
430
+ | `queryManySeries(request, options?)` | `POST /{resource}/series/query` | Query the points of the records of `ids` and `filter` |
431
+ | `deleteSeries(id, range?, options?)` | `POST /{resource}/{id}/delete-series` | Delete the points of a `{ from, to }` range |
432
+
433
+ ```ts
434
+ // Find a single record
435
+ const post = await client.post.find(1);
436
+
437
+ // Query with filters, sorting and pagination. The sort accepts a comma-separated
438
+ // field list ('-createdAt,id') or an object of field directions
439
+ const result = await client.post.query({
440
+ filter: { published: true },
441
+ sort: { author: { lastName: 'asc' }, createdAt: 'desc' },
442
+ page: 1,
443
+ size: 20
444
+ });
445
+
446
+ // Page by cursor instead of by offset, sending back the cursor of the response
447
+ // and skipping the count the first page already returned
448
+ const next = await client.post.query({
449
+ filter: { published: true },
450
+ sort: { author: { lastName: 'asc' }, createdAt: 'desc' },
451
+ size: 20,
452
+ cursor: result.nextCursor,
453
+ totalCount: false
454
+ });
455
+
456
+ // Aggregate. The select holds the operators to apply per numeric or date field
457
+ const stats = await client.post.aggregate({
458
+ select: { counter: { count: true, sum: true }, createdAt: { min: true } },
459
+ dateField: 'createdAt'
460
+ });
461
+
462
+ // Create
463
+ const newPost = await client.post.create({ title: 'Hello', body: '...' });
464
+
465
+ // Update (id must be part of the payload, the client sends it in the path only)
466
+ const updated = await client.post.update({ id: 1, title: 'Updated' });
467
+
468
+ // Replace the whole record (omitted fields reset to their default or null)
469
+ const replaced = await client.post.replace({
470
+ id: 1,
471
+ title: 'Replaced',
472
+ body: '...'
473
+ });
474
+
475
+ // Delete
476
+ const deleted = await client.post.delete(1);
477
+
478
+ // Bulk, generated only for resources enabling the routes, resolves the created records
479
+ const posts = await client.post.bulkCreate([
480
+ { title: 'One' },
481
+ { title: 'Two' }
482
+ ]);
483
+ // A route returning no records (`returnRecords: false`) is typed by the call: { success: true, count: 2 }
484
+ const { count } = await client.post.bulkCreate<BulkResponse>([
485
+ { title: 'One' },
486
+ { title: 'Two' }
487
+ ]);
488
+
489
+ // Export as CSV
490
+ const file = await client.post.export({ filter: { published: true } });
491
+ // file.stream — ReadableStream, file.fileName — string, file.type — string
492
+
493
+ // Upload files
494
+ const files = await client.post.uploadFiles({
495
+ cover: new File([], 'cover.jpg')
496
+ });
497
+
498
+ // Delete files
499
+ await client.post.deleteFiles({ fileIds: [42, 43] });
500
+
501
+ // Upload a new version of a file (with `storage.versions.enabled`)
502
+ await client.post.uploadFiles(1, {
503
+ gallery: [{ file: newImage, replace: 'gallery/a-1f2e.png' }]
504
+ });
505
+
506
+ // List the versions, read a previous one from its URL (`?version=2`), delete the latest one
507
+ const versions = await client.post.fileVersions(1, 'gallery/a-9c8d.png');
508
+ await client.post.deleteFileVersions(1, {
509
+ gallery: { name: 'gallery/a-9c8d.png', version: 'latest' }
510
+ });
511
+ ```
512
+
513
+ ### `AuthClient`
514
+
515
+ The routes of [security.md](./security.md#auth-routes).
516
+
517
+ | Method | HTTP | Description |
518
+ |-------------------------------------|------------------------------|---------------------------------------------|
519
+ | `login(request, options?)` | `POST /auth/login` | Authenticate with credentials |
520
+ | `logout(options?)` | `POST /auth/logout` | Invalidate the current session |
521
+ | `refresh(options?)` | `POST /auth/refresh` | Renew access token |
522
+ | `changePassword(request, options?)` | `POST /auth/change-password` | Change the authenticated user's password |
523
+ | `exchangeToken(request, options?)` | `POST /auth/exchange-token` | Exchange a third-party token for app tokens |
524
+ | `me(options?)` | `GET /auth/me` | Get the current user's identity |
525
+
526
+ ```ts
527
+ const session = await client.auth.login({
528
+ email: 'user@example.com',
529
+ password: 'secret'
530
+ });
531
+ const me = await client.auth.me();
532
+ await client.auth.logout();
533
+ ```
534
+
535
+ ### `AccountClient`
536
+
537
+ The routes of [security.md](./security.md#account-management) and its
538
+ [phone verification](./security.md#phone-verification).
539
+
540
+ | Method | HTTP | Description |
541
+ |----------------------------------------|-------------------------------------------|------------------------------------|
542
+ | `sendVerifyEmail(request, options?)` | `POST /auth/account/send-verify-email` | Send email verification link |
543
+ | `verifyEmail(request, options?)` | `POST /auth/account/verify-email` | Verify email with token |
544
+ | `verifyEmailRedirect(token, options?)` | `GET /auth/account/verify-email-redirect` | Handle redirect-based verification |
545
+ | `sendResetPassword(request, options?)` | `POST /auth/account/send-reset-password` | Send password reset email |
546
+ | `resetPassword(request, options?)` | `POST /auth/account/reset-password` | Reset password with token |
547
+ | `sendVerifyPhone(request?, options?)` | `POST /auth/account/send-verify-phone` | Send a phone verification code |
548
+ | `verifyPhone(request, options?)` | `POST /auth/account/verify-phone` | Verify the phone with the code |
549
+
550
+ ```ts
551
+ await client.account.sendVerifyEmail({ email: 'user@example.com' });
552
+ await client.account.verifyEmail({ token: 'abc123' });
553
+ await client.account.sendResetPassword({ email: 'user@example.com' });
554
+ await client.account.resetPassword({ token: 'abc123', password: 'newpass' });
555
+ ```
556
+
557
+ ### `TwoFactorClient`
558
+
559
+ The two-factor authentication, under the `/two-factor` path of the account routes (`twoFactor` of the
560
+ `x-appweaver-config.routePrefixes` of the schema), described in
561
+ [security.md](./security.md#two-factor-authentication-2fa).
562
+
563
+ | Method | HTTP | Description |
564
+ |---------------------------------------------|----------------------------------------------------|----------------------------------------------|
565
+ | `challenge(request?, options?)` | `POST /auth/account/two-factor/challenge` | Send a challenge by a method, or the default |
566
+ | `verify(request, options?)` | `POST /auth/account/two-factor/verify` | Verify a code, returns the token to exchange |
567
+ | `listMethods(options?)` | `GET /auth/account/two-factor/methods` | List the enabled and the available methods |
568
+ | `enableMethod(request, options?)` | `POST /auth/account/two-factor/methods` | Enable the email or SMS method |
569
+ | `orderMethods(request, options?)` | `PUT /auth/account/two-factor/methods/order` | Order the methods, the first is the default |
570
+ | `disableMethod(method, request?, options?)` | `DELETE /auth/account/two-factor/methods/{method}` | Disable a method, with the password |
571
+ | `setupTotp(options?)` | `POST /auth/account/two-factor/totp/setup` | Start the setup of an authenticator app |
572
+ | `confirmTotp(request, options?)` | `POST /auth/account/two-factor/totp/confirm` | Confirm the setup with a code of the app |
573
+ | `generateRecoveryCodes(request?, options?)` | `POST /auth/account/two-factor/recovery-codes` | Generate the recovery codes, shown once |
574
+ | `listDevices(options?)` | `GET /auth/account/two-factor/devices` | List the trusted devices (`rememberDevice`) |
575
+ | `forgetDevice(id, options?)` | `DELETE /auth/account/two-factor/devices/{id}` | Forget a trusted device |
576
+ | `forgetAllDevices(options?)` | `DELETE /auth/account/two-factor/devices` | Forget every trusted device |
577
+
578
+ ```ts
579
+ const session = await client.auth.login({
580
+ username: 'user@example.com',
581
+ password: 'secret'
582
+ });
583
+ if (session.twoFactorMethods) {
584
+ // The tokens of the twoFactor scope, used by the challenge and its verification only
585
+ const { challengeId } = await client.twoFactor.challenge({ method: 'Totp' });
586
+ const { token } = await client.twoFactor.verify({
587
+ challengeId,
588
+ code: '123456'
589
+ });
590
+ await client.auth.exchangeToken({ token });
591
+ }
592
+ ```
593
+
594
+ ### `HealthClient`
595
+
596
+ | Method | HTTP | Description |
597
+ |-------------------|---------------------|---------------------------------------------------------------|
598
+ | `check(options?)` | `GET /health` | Health check status, the body of its 503 when a check is down |
599
+ | `ready(options?)` | `GET /health/ready` | Readiness probe, `{ ready: false }` on its 503 |
600
+
601
+ ```ts
602
+ const status = await client.health.check();
603
+ ```
604
+
605
+ ### `FilesClient`
606
+
607
+ | Method | HTTP | Description |
608
+ |-----------------------------|-----------------------|---------------------------|
609
+ | `public(path, options?)` | `GET /files/{path}` | Download a public file |
610
+ | `protected(path, options?)` | `GET /files/p/{path}` | Download a protected file |
611
+
612
+ ```ts
613
+ const file = await client.files.public('images/photo.jpg');
614
+ const fileData = await file.base64(); // or use file.stream to pipe output to file etc.
615
+ ```
616
+
617
+ ### Realtime client
618
+
619
+ `client.realtime` (`RealtimeClient`) is generated for an API with `@appweaver/realtime`, typed by the
620
+ `RealtimeModuleType` of the `x-appweaver-realtime` extension. It connects on the first subscription or action with a
621
+ ticket of the client's `auth`, over a WebSocket, or SSE where the runtime or the server has none (SSE reopens its stream
622
+ on a change of the subscriptions, and sends the actions over HTTP). It reconnects with its subscriptions after a lost
623
+ connection or a failed attempt, with a backoff randomized from its half to itself, at once on an expired token (`4401`),
624
+ and within a random part of `reconnectDelay` on a server restarting (`1012`, a rolling update), resuming the streams
625
+ of its calls on the new instance.
626
+
627
+ | Method | Description |
628
+ |-------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
629
+ | `subscribe(channel, handler, params?)` | `handler(payload, { eventId, channel })`; returns `{ id, ready, unsubscribe }` |
630
+ | `on(model, handler, { action?, filter? })` | Resource events, `handler({ model, action, current, previous? })` |
631
+ | `observe(channel, params?)` | An observable of the payloads, for `from(...)` of RxJS |
632
+ | `send(action, payload)` / `emit(...)` | Calls an action, resolving to its result / fire-and-forget |
633
+ | `call(action, payload, { input? })` | Calls a streaming action: an async iterable of its chunks, with `result`, `stream`, `onChunk(listener)`, `cancel()` and `input` (`write(chunk)`, `end()`) |
634
+ | `stream(name, handlers, { key?, params? })` | Subscribes to the streams of a key, `handlers`: `onStart(info)`, `onChunk(chunk, { streamId, seq, gap, sync })`, `onEnd(result, info)`, `onError(error, info)` |
635
+ | `connect()`, `disconnect()`, `reconnect()` | Opens, closes (keeping the subscriptions), or reopens with a new ticket, i.e. after a login |
636
+ | `onStateChange(listener)`, `onError(...)` | `idle`, `connecting`, `open`, `reconnecting`; the errors answering no subscription or action |
637
+ | `state`, `connectionId`, `transport`, `authenticated` | The state of the connection, and whether it is of a user |
638
+
639
+ `subscription.ready` rejects with the `ClientError` of a refused subscription, which a reconnection does not renew.
640
+
641
+ The chunks of a `binary` stream are `Uint8Array`s. Over the WebSocket, a call and a stream subscription resume after a
642
+ reconnection from the last chunk received, without duplicates; over SSE, a call is the response of an HTTP request,
643
+ failing with the connection. `call.result` rejects with the error of the stream, or once cancelled (`cancel()`, or
644
+ leaving a `for await` early), which ends the iteration instead of throwing in it.
645
+
646
+ An action with an input receives the chunks of `call.input.write(chunk)` (resolving once sent, waiting for the
647
+ credits of the server) and `call.input.end()`, or of an `AsyncIterable` or a `ReadableStream` given as
648
+ `{ input }`, ended with it and cancelling the call when it fails. A `Uint8Array` is sent as a binary message, any other
649
+ chunk as JSON; keep a chunk under the `realtime.maxMessageSize` of the server. An input needs the WebSocket, fails the
650
+ call over SSE, and fails it when the connection is lost before the input ended.
651
+
652
+ ```ts
653
+ const recorder = new MediaRecorder(
654
+ await navigator.mediaDevices.getUserMedia({ audio: true })
655
+ );
656
+ const call = client.realtime.call('voice.transcribe', { language: 'en' });
657
+ recorder.ondataavailable = async (event) =>
658
+ call.input.write(new Uint8Array(await event.data.arrayBuffer()));
659
+ recorder.onstop = () => call.input.end();
660
+ recorder.start(250);
661
+ for await (const text of call) showCaption(text);
662
+ ```
663
+
664
+ ```ts
665
+ const call = client.realtime.call('assistant.prompt', { prompt: 'Hello' });
666
+ call.onChunk((token) => render(token));
667
+ try {
668
+ const { stopReason } = await call.result;
669
+ } catch (e) {
670
+ // ClientError of the stream, or of the cancellation
671
+ }
672
+ ```
673
+
674
+ ```ts
675
+ type RealtimeClientOptions = {
676
+ transport?: 'auto' | 'websocket' | 'sse'; // default: auto
677
+ anonymous?: boolean | 'auto'; // true: no ticket; 'auto': anonymous when the ticket is refused (401). Default: false
678
+ reconnect?: boolean; // default: true
679
+ reconnectDelay?: number; // ms, doubled each attempt, randomized (default: 500)
680
+ maxReconnectDelay?: number; // default: 30000
681
+ actionTimeout?: number; // default: 30000
682
+ WebSocket?: typeof WebSocket; // default: the global one
683
+ };
684
+ ```
685
+
686
+ See [realtime.md](./realtime.md) for the server side and the protocol.
687
+
688
+ ### `FileDataResponse`
689
+
690
+ Both `FilesClient` methods and `ResourceClient.export` return a `FileDataResponse` instance instead of a raw response
691
+ body. It exposes file metadata as properties and provides helper methods to consume the content.
692
+
693
+ **Properties:**
694
+
695
+ | Property | Type | Description |
696
+ |-------------|---------------------|-----------------------------------------------------------------|
697
+ | `stream` | `ReadableStream` | Readable stream of the file content |
698
+ | `fileName` | `string` | File name of the `Content-Disposition` header (see below) |
699
+ | `type` | `string` | MIME type from the `Content-Type` header |
700
+ | `length` | `number` | File size in bytes from the `Content-Length` header |
701
+ | `range` | `FileContentRange?` | Byte range info present on partial-content (HTTP 206) responses |
702
+ | `maxAge` | `number?` | Cache duration in seconds from `Cache-Control: max-age` |
703
+ | `expiresAt` | `string?` | Expiration timestamp from the `Expires` header |
704
+
705
+ The file name is the decoded `filename*` of the header (RFC 6266 and 8187, the UTF-8 name of a file such as
706
+ `naïve.txt`), else its unquoted `filename`, else the requested name (the path of `FilesClient`, `unknown` for an
707
+ export).
708
+
709
+ **Methods:**
710
+
711
+ | Method | Returns | Description |
712
+ |--------------------------|------------------------|-----------------------------------------------------------------------|
713
+ | `buffer()` | `Promise<ArrayBuffer>` | Raw binary content as an `ArrayBuffer` |
714
+ | `blob()` | `Promise<Blob>` | Content wrapped in a `Blob` with the correct MIME type |
715
+ | `text(encoding: string)` | `Promise<string>` | Content decoded to string using specified encoding (default is UTF-8) |
716
+ | `base64()` | `Promise<string>` | Content as a Base64 data URL (`data:<type>;base64,...`) |
717
+
718
+ The stream is read lazily on the first call to any consumption method, and the result is cached — later calls return the
719
+ same `ArrayBuffer` without re-reading the stream.
720
+
721
+ The `FileContentRange` type describes a partial-content range:
722
+
723
+ ```ts
724
+ type FileContentRange = {
725
+ start: number; // Starting byte position (inclusive)
726
+ end: number; // Ending byte position (inclusive)
727
+ total: number; // Total size of the complete file in bytes
728
+ };
729
+ ```
730
+
731
+ **Examples:**
732
+
733
+ ```ts
734
+ // Download a public file and convert to a data URL for display
735
+ let file = await client.files.public('images/photo.jpg');
736
+ const dataUrl = await file.base64();
737
+ img.src = dataUrl;
738
+
739
+ // Download a protected file and save as a Blob
740
+ file = await client.files.protected('reports/data.pdf');
741
+ const blob = await file.blob();
742
+ const url = URL.createObjectURL(blob);
743
+
744
+ // Export a resource collection as CSV and read as text
745
+ file = await client.post.export({ filter: { published: true } });
746
+ const csv = await file.text();
747
+
748
+ // Inspect metadata before consuming
749
+ console.log(file.fileName); // e.g. "export.csv"
750
+ console.log(file.type); // e.g. "text/csv"
751
+ console.log(file.length); // e.g. 4096
752
+ ```
753
+
754
+ ---
755
+
756
+ ## Direct requests
757
+
758
+ ### `sendRequest`
759
+
760
+ Sends a typed request and returns the parsed response body. Throws `ClientError` on any non-2xx response.
761
+
762
+ ```ts
763
+ const data = await client.sendRequest('get', '/api/custom-endpoint');
764
+ ```
765
+
766
+ ### `sendRequestRaw`
767
+
768
+ Returns the raw `{ data, error, response }` tuple from `openapi-fetch` without throwing. Useful when the caller needs to
769
+ inspect error details or branch on status codes.
770
+
771
+ ```ts
772
+ const { data, error, response } = await client.sendRequestRaw(
773
+ 'post',
774
+ '/api/custom-endpoint',
775
+ {
776
+ body: { key: 'value' }
777
+ }
778
+ );
779
+
780
+ if (error) {
781
+ console.error(`Failed with ${response.status}`);
782
+ } else {
783
+ console.log(data);
784
+ }
785
+ ```
786
+
787
+ ### `getClient`
788
+
789
+ Returns the underlying `openapi-fetch` `Client` instance for advanced use cases not covered by the helper methods.
790
+
791
+ ```ts
792
+ const rawClient = client.getClient();
793
+ const { data } = await rawClient.GET('/api/custom-endpoint');
794
+ ```
795
+
796
+ ### Custom request (generated)
797
+
798
+ Routes that do not match any standard module pattern are exposed via `customRequest` in the generated class:
799
+
800
+ ```ts
801
+ // In the generated client:
802
+ const postApiPublishPosts = this.customRequest('post', '/api/publish-posts');
803
+
804
+ // Usage:
805
+ const result = await client.postApiPublishPosts({ body: { ids: [1, 2, 3] } });
806
+ ```
807
+
808
+ ---
809
+
810
+ ## Error handling
811
+
812
+ All module client methods and `sendRequest` throw `ClientError` on non-2xx responses:
813
+
814
+ ```ts
815
+ import { ClientError } from '@appweaver/client';
816
+
817
+ try {
818
+ const post = await client.post.find(999);
819
+ } catch (err) {
820
+ if (err instanceof ClientError) {
821
+ console.error(err.message); // The detail of the problem details response
822
+ console.error(err.status); // HTTP status code
823
+ console.error(err.code); // Error code, i.e. 'RESOURCE_NOT_FOUND' ('REQUEST_FAILED' without problem details)
824
+ console.error(err.errors); // Invalid fields, i.e. [{ field: 'email', rule: 'unique', message: 'must be unique' }]
825
+ console.error(err.details); // Details specific to the code
826
+ console.error(err.problem); // The whole RFC 9457 problem details body
827
+ console.error(err.response); // Native Response object
828
+ console.error(err.route); // The route of the request, i.e. { method: 'get', path: '/api/posts/{id}' }
829
+ }
830
+ }
831
+ ```
832
+
833
+ A plain `instanceof` check types `err.code` as `any`. The generated file exports the error types of the API to type it:
834
+
835
+ | Export | Description |
836
+ |--------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
837
+ | `ErrorCode` | Constant and union of every framework and application error code of the API, its keys PascalCase as on the server, i.e. `ErrorCode.ResourceNotFound` |
838
+ | `ApiError` | `ClientError<ErrorCode>` |
839
+ | `isApiError(err)` | Narrows a caught error to `ApiError`, so `err.is()` accepts the error codes of the API only |
840
+ | `RouteErrorCode<Method, Path>` | The error codes a route documents, i.e. `RouteErrorCode<'get', '/api/posts/{id}'>`, a module or resource route read from `routeErrors` |
841
+
842
+ `client.isRouteError(err, method, path)` narrows a caught error further, to the codes of the route the request was sent
843
+ to. It checks the route the error was thrown for, so it is true for the error of a request of that route only (a
844
+ module client method or `sendRequest`):
845
+
846
+ ```ts
847
+ import { ErrorCode, isApiError } from './generated/client';
848
+
849
+ try {
850
+ await client.user.create(data);
851
+ } catch (err) {
852
+ if (isApiError(err) && err.is(ErrorCode.DatabaseUniqueViolation)) {
853
+ showFieldErrors(err.errors); // [{ field: 'email', rule: 'unique', message: 'must be unique' }]
854
+ }
855
+ }
856
+
857
+ try {
858
+ await client.post.find(999);
859
+ } catch (err) {
860
+ if (client.isRouteError(err, 'get', '/api/posts/{id}')) {
861
+ err.code; // 'RESOURCE_NOT_FOUND' | 'RESOURCE_FORBIDDEN' | 'VALIDATION_FAILED' | ...
862
+ }
863
+ }
864
+ ```
865
+
866
+ Every operation types its error responses per status, narrowing the `code` of `ProblemDetails` to the codes the route
867
+ documents, i.e. `code: 'RESOURCE_NOT_FOUND'` for the 404 of a find. The responses the operations share are declared
868
+ once in `components['responses']` (i.e. `ResourceNotFoundError`) and referred to by every operation.
869
+
870
+ Use `sendRequestRaw` to avoid exceptions and handle errors inline:
871
+
872
+ ```ts
873
+ const { data, error, response } = await client.sendRequestRaw(
874
+ 'get',
875
+ '/api/posts/{id}',
876
+ {
877
+ params: { path: { id: 999 } }
878
+ }
879
+ );
880
+
881
+ if (error?.code === 'RESOURCE_NOT_FOUND') {
882
+ // handle not found
883
+ }
884
+ ```