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