@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,1216 @@
1
+ # Core patterns
2
+
3
+ The patterns of an Appweaver application with their code: scaffolding, the application, modules, resources (model,
4
+ service, routes, policy, auth model), filters, sorting, aggregates, custom routes, templates, errors, logging,
5
+ telemetry, audit, realtime, AI, MCP, custom models, plugins, dependency injection and seeders. Each part links to its
6
+ full reference.
7
+
8
+ ## Scaffolding a new application
9
+
10
+ Use `@appweaver/create` (the `create-appweaver` binary) to scaffold a new project. It copies the base template, a
11
+ minimal application of the core module, adds the selected modules (`data` and `web` by default), installs dependencies,
12
+ and generates the Prisma schema and the types with `data` (only the JSON Schema of `appweaver.json` without it). It is a
13
+ one-shot command without prompts.
14
+
15
+ ```sh
16
+ npx @appweaver/create <name> [description] [options]
17
+ npm create @appweaver <name> [description] -- [options] # the same, npm passes the options after --
18
+ ```
19
+
20
+ **Options:**
21
+
22
+ | Flag | Description | Default |
23
+ | ------------------------ | ----------------------------------------------------------------------------- | ------------ |
24
+ | `--add <modules...>` | Modules to add to the default ones, separated by spaces or commas | `data web` |
25
+ | `--all` | Add every module | false |
26
+ | `--exclude <modules...>` | Modules to leave out of the default ones or of `--all` (e.g. `--exclude web`) | none |
27
+ | `-o, --output-dir <dir>` | Output directory (use ./ for current working directory) | project name |
28
+ | `--database <type>` | Database of `data`: `sqlite`, `postgresql`, `mysql`, `sqlserver` | `sqlite` |
29
+ | `--host <host>` | Hostname or IP address the server of `web` binds to | `0.0.0.0` |
30
+ | `--port <port>` | Port number the server of `web` listens on | `5000` |
31
+ | `--bun` | Use Bun as the application runtime (Node and npm otherwise) | Node |
32
+ | `--agent <agent>` | The AI agent to configure the guidelines and skill files for | `claude` |
33
+ | `--no-install` | Skip the installation of the dependencies | installs |
34
+
35
+ **Modules:** the base project depends only on `@appweaver/cli`, `@appweaver/common`, `@appweaver/core` and TypeBox: an
36
+ application with neither a database nor a server (`src/main.ts`, an e2e test of its health checks). `data` and `web`
37
+ are the default modules, added to it unless excluded, so a project is a web API by default. Every other module is added
38
+ with `--add`, `--all`, or later with `weaver module add` (see [Managing modules](#managing-modules)). `--exclude` leaves
39
+ out any module, with or without `--all`: `--exclude web` for a database worker without a server, `--exclude data web`
40
+ for the core application alone, i.e. a one-shot task (`weaver run`). `--database`, `--host` and `--port` apply only
41
+ with `data` and `web`:
42
+
43
+ | Module | Adds | Without it |
44
+ | ---------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
45
+ | `data` (default) | `@appweaver/data`, `@appweaver/sharp`, Prisma, `database/`, the generated types, the test database | no database, no resources |
46
+ | `web` (default) | `@appweaver/web` (requires `data`), the server config, the `User` auth resource and its admin seeder, `public/` | no HTTP server, no auth model |
47
+ | `redis` | `@appweaver/redis`, the `memory.redis.url`, the docker-compose Redis service | memory, cache and rate limit in the process |
48
+ | `queue` | `@appweaver/bullmq` (requires `redis`, added along with it) | in-memory queue |
49
+ | `scheduler` | `@appweaver/cron` | scheduler disabled |
50
+ | `mailer` | `@appweaver/nodemailer` | mailer disabled (no email routes) |
51
+ | `templates` | `@appweaver/handlebars`, `templates/`, the account emails with the mailer | no template engine |
52
+ | `locales` | `locales/en.json`, the account email texts with the mailer | English texts written into the templates |
53
+ | `timeseries` | The `series` fields in the database (requires `data`), `timescale` and the TimescaleDB image on PostgreSQL | time series in the database (`auto`) |
54
+ | `telemetry` | `@appweaver/opentelemetry`, the OTLP endpoint, telemetry off in the `test` environment | no telemetry exported |
55
+ | `realtime` | `@appweaver/realtime` (requires `web`): channels, resource events, actions and streams over WebSocket and SSE | no realtime connections |
56
+ | `mcp` | `@appweaver/mcp` (requires `web`): the MCP server of the AI agents at `/mcp` | no MCP server |
57
+ | `ai` | `@appweaver/ai` and `@appweaver/openai`: `AiService` on a local Ollama in `dev`, the `mock` model in `test` | no AI models |
58
+ | `docker` | `Dockerfile`, `.dockerignore`, `docker-compose.yml`, `start.sh` | no Docker files |
59
+
60
+ Options are given after the positional arguments, since `--add` and `--exclude` take every following value up to the
61
+ next option.
62
+
63
+ **Example — PostgreSQL API with Redis, mailer and Docker:**
64
+
65
+ ```sh
66
+ npx @appweaver/create MyBlogAPI "My own CMS for blogging" --database postgresql --add redis mailer docker
67
+ npx @appweaver/create MyBlogAPI "My own CMS for blogging" --database postgresql --all --exclude queue
68
+ npx @appweaver/create Reports "Nightly reports" --add scheduler --exclude web # a database worker without a server
69
+ npx @appweaver/create Calculator "Loan calculator" --exclude data web # the core application alone
70
+ ```
71
+
72
+ This creates a `./my-blog-api` directory, installs all dependencies, and runs the initial schema and type generation.
73
+ The default test runner is `jest` with `swc` transpiler.
74
+
75
+ The connections are configured in the committed `appweaver.json` (the test database in its `environments.test`
76
+ section), whose `${VAR}` references are expanded from the environment. Only the database password goes to the gitignored
77
+ `.env` (copied to a committed `.env.example`):
78
+
79
+ ```json
80
+ {
81
+ "config": {
82
+ "database": {
83
+ "url": "postgresql://${DB_USER:-my-blog-api}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-my-blog-api}"
84
+ },
85
+ "memory": {
86
+ "redis": {
87
+ "url": "redis://${REDIS_HOST:-localhost}:6379/0"
88
+ }
89
+ }
90
+ },
91
+ "environments": {
92
+ "test": {
93
+ "database": {
94
+ "url": "postgresql://${DB_USER:-my-blog-api}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-my-blog-api}-test"
95
+ }
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ ```dotenv
102
+ NODE_ENV=dev
103
+
104
+ DB_PASSWORD=my-blog-api
105
+ ```
106
+
107
+ With the `docker` module, the generated `docker-compose.yml` of a PostgreSQL, MySQL, or SQL Server project runs the
108
+ database server (and Redis, with the `redis` module) on their default ports (`5432`, `3306`, `1433`, and `6379` for
109
+ Redis), also published on the host, with the `.env` credentials. So `docker compose up` runs the whole stack, while
110
+ `docker compose up -d postgres redis` and `npm run dev`
111
+ run the app locally against the same containers. The application containers read `.env` and set only `DB_HOST` and
112
+ `REDIS_HOST` to the service names, which the URLs default to `localhost` without. To use another server, change the
113
+ URL in `appweaver.json`, or set `DB_HOST` / `REDIS_HOST` in `.env`. Setting `DB_NAME` renames the database (the test
114
+ database is `${DB_NAME}-test`), also in the docker-compose database service, and `DB_USER` changes the user. For MySQL,
115
+ the generated `database/mariadb-init.sh` grants the user every database when the MariaDB container initializes its
116
+ volume, since Prisma Migrate creates a shadow database and the end-to-end tests the `-test` one.
117
+
118
+ The migrations connect with `database.migrationUrl`, `database.url` when not set, so the application can query the
119
+ data as a user that only reads and writes the rows, while the migrations run as the owner of the tables. `weaver
120
+ migrate` also sets up the TimescaleDB hypertables and the PostGIS geometry triggers with it (see
121
+ [database](./database.md#separate-migration-and-application-users)).
122
+
123
+ A SQLite project keeps its database file in the `data/` directory (`file:./data/<name>.db`), which the
124
+ generated `docker-compose.yml` mounts as the `sqlite-data` volume shared by the migration, seed, and application
125
+ containers.
126
+
127
+ The generated `Dockerfile` builds the application and its production dependencies in a build stage, so the final image
128
+ carries no build tools. The image runs as the unprivileged `node` user (`bun` for Bun) and defaults to `NODE_ENV=prod`.
129
+ It declares no health check, which belongs to the orchestrator: point the Docker Compose `healthcheck` or the Kubernetes
130
+ probes at `GET /health/ready`, which answers `{ "ready": true }` once every service has started (503 with
131
+ `{ "ready": false }` before, and again from the start of the shutdown) and needs no authentication. The
132
+ `docker-compose.yml` services read `NODE_ENV` from `.env`, so the environment a container starts
133
+ in stays up to the project. Mounted `storage`, `logs`, and `data` directories must be writable by the image user.
134
+
135
+ **Linux hosts:** the `docker-compose.yml` services bind-mount the project's `./storage` and `./logs` directories, which
136
+ on Linux keep the owner they have on the host. A directory Docker creates itself is owned by `root`, so the image user
137
+ (uid `1000`) cannot write uploaded files, logs, or the generated JWT keys into it. Create both directories before the
138
+ first `docker compose up` and give them to uid `1000`:
139
+
140
+ ```sh
141
+ mkdir -p storage logs && sudo chown -R 1000:1000 storage logs
142
+ ```
143
+
144
+ Volumes created by an image version that still ran as `root` need the same change of owner, or recreating. Docker
145
+ Desktop on macOS and Windows maps the ownership of bind mounts itself and needs neither step.
146
+
147
+ **Example — Bun project with Sqlite:**
148
+
149
+ ```sh
150
+ npx @appweaver/create BunApp "Bun application with simple API" --bun --database sqlite
151
+ ```
152
+
153
+ This creates a `./bun-app` directory, installs all dependencies using bun package manager, and runs the initial schema
154
+ and type generation. The default test runner is `bun`.
155
+
156
+ After the application is scaffolded, the following commands need to be run to finish the application setup:
157
+
158
+ ```sh
159
+ npx weaver migration new init # use --no-install flag if npx tries to install package
160
+ npm run seed
161
+ ```
162
+
163
+ Or, for bun runtime:
164
+
165
+ ```sh
166
+ bun weaver migration new init
167
+ bun run seed
168
+ ```
169
+
170
+ **Install scripts:** npm 12+ blocks dependency install scripts by default. The scaffolded `package.json` ships an
171
+ `allowScripts` field (Bun: `trustedDependencies`) covering the packages Appweaver needs to build. Without it,
172
+ `npm install` skips the native builds and `weaver generate` fails. It also denies (`false`) `@parcel/watcher`, which
173
+ Jest pulls in with prebuilt binaries, so its fallback native build is never needed. To approve a newly added
174
+ dependency, run `npm install-scripts approve <pkg>`, or `npm deny-scripts <pkg>` to silence the warning for one that
175
+ does not need its script; both write the entry to the root `package.json`. Note that a `package.json`
176
+ `allowScripts` field makes npm ignore `.npmrc` `allow-scripts` entirely.
177
+
178
+ ## Creating and starting the application server
179
+
180
+ The main entrypoint to the application. This function creates an application object and initializes all resources and
181
+ services.
182
+
183
+ Default application bootstrap:
184
+
185
+ ```ts
186
+ // src/main.ts
187
+ import { createApp } from '@appweaver/core';
188
+ import { logger } from '@appweaver/common';
189
+
190
+ createApp().catch((err) => logger.error(err));
191
+ ```
192
+
193
+ Manually starting an application:
194
+
195
+ ```ts
196
+ // src/main.ts
197
+ import { createApp } from '@appweaver/core';
198
+
199
+ const app = await createApp({
200
+ autoStart: false,
201
+ scanPath: './dist/my/app/path'
202
+ });
203
+
204
+ // custom init logic...
205
+
206
+ await app.start(); // with SERVER_LISTEN=false, every service starts without the server listening
207
+ ```
208
+
209
+ `app.server` is the Fastify instance of the `HttpServer` service (`inject(HttpServer).instance`), and `app.spec()`
210
+ returns the OpenAPI document. `@appweaver/web` adds both to `Application`, so neither is available when the module is
211
+ not installed or disabled.
212
+
213
+ ## Modules and application kinds
214
+
215
+ Every part of the framework is a module declared with `defineModule`: `@appweaver/core` (always), `@appweaver/data`
216
+ (Prisma, the resources), `@appweaver/web` (the Fastify server, authentication, requires data) and one driver package
217
+ per library or service (`@appweaver/redis`, `@appweaver/bullmq`, `@appweaver/cron`, `@appweaver/nodemailer`,
218
+ `@appweaver/twilio`, `@appweaver/handlebars`, `@appweaver/sharp`). Every package but core is enabled by being a
219
+ dependency of the application's `package.json`, and carries the library it wraps, so install `@appweaver/redis`, not
220
+ `ioredis`. The
221
+ `provider` key of each contract (`auto` by default) picks the driver of an enabled module, `none` turns the contract
222
+ off. An application adds its own modules in `src/modules/<name>/module.ts` (`weaver module new <name>`) or as npm
223
+ packages (`weaver module add <package>`), and a module package is created with `npm create @appweaver module
224
+ <package>`, its driver tested with the contract suites of `@appweaver/testing`. See [modules.md](./modules.md)
225
+ and the [providers](./configuration.md#providers).
226
+
227
+ | Application | How |
228
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
229
+ | HTTP API | The default: `createApp()` starts the server on `SERVER_PORT`. |
230
+ | Queue worker, scheduled jobs | `APP_MODULES_DISABLED=@appweaver/web`: no server, kept alive by its workers or cron jobs. `HEALTH_CHECK_PORT` answers the health checks. |
231
+ | One-shot task | `weaver run <task> [args...]`: runs a `createTask` of `src/tasks/` by its name (`weaver run` lists them), then exits. |
232
+
233
+ ```ts
234
+ // src/tasks/orders/count.ts, run with `weaver run orders:count Pending`
235
+ import { createTask, injectService } from '@appweaver/core';
236
+
237
+ export default createTask({
238
+ description: 'Counts the orders of a status.',
239
+ arguments: { status: { required: true, choices: ['Pending', 'Paid'] } },
240
+ options: { min: { type: 'number', default: 1 } }, // --min <min>
241
+ run: async ({ args, options }) => {
242
+ const count = await injectService('Order').count({ status: args.status });
243
+ console.log(`${count} orders`);
244
+ return count >= options.min ? 0 : 1; // the exit code
245
+ }
246
+ });
247
+ ```
248
+
249
+ `weaver run` runs the task without the server or the scheduled jobs, `--help` showing its arguments. A task is named by
250
+ its path in `src/tasks/` (`orders/count.ts` is `orders:count`) unless it has a `name`. See
251
+ [cli.md](./cli.md#weaver-run).
252
+
253
+ ## Creating resources
254
+
255
+ Resources are the core building blocks for a web application. There are four resource types: **model**, **service**,
256
+ **routes**, and **policy**. Created and exported resources are loaded automatically on application start. Except for a
257
+ resource model, other resource types are optional and do not need to be created. A service requires the model, and
258
+ routes require the service. A policy only requires the model and applies to the service whether routes exist or not.
259
+
260
+ Dependencies: **model** ← **service** ← **routes**, and **model** ← **policy** (optional)
261
+
262
+ **DOS:**
263
+
264
+ - Use default configuration values whenever possible
265
+ - Rely on library defaults for `omit`/`pick`, ad `input`/`output` settings
266
+ - Use default `mimeType` and `namePattern` patterns in file configurations unless specifically requested
267
+ - Prefer storing configuration in JSON file (`appweaver.json`) over environment (`.env`) file, but keep secrets in
268
+ `.env`
269
+ and reference them from the JSON file as `${VAR}` (i.e. `"url": "postgresql://${DB_USER:-app}:${DB_PASSWORD}@..."`)
270
+ - Always create all four resource configs (model, service, routes, and policy) unless specified otherwise
271
+
272
+ **DON'TS:**
273
+
274
+ - Don't explicitly set default values in configuration unless specifically requested
275
+ - Don't override `omit`/`pick` for `read`, `create` and `update` settings unnecessarily
276
+ - Don't specify `input`/`output` configurations if defaults suffice
277
+ - Don't modify file's `mimeType` and `namePattern` patterns unless specifically instructed
278
+ - Don't customize index arrays without an explicit requirement
279
+
280
+ ### Creating a resource model
281
+
282
+ Resource model defines all aspects of the domain model: database table fields, relations, files, virtual fields, CRUD
283
+ data transfer objects. The exported model is used to construct Prisma schema, generate TypeScript types for all model
284
+ variations, define schema for CRUD routes, and input/output arguments to resource service methods.
285
+
286
+ `weaver resource new <name>` creates the `model.ts`, `service.ts`, `routes.ts` and `policy.ts` of a new resource
287
+ (`--no-service`, `--no-routes` and `--no-policy` leave them out), to edit before `weaver generate`.
288
+
289
+ ```ts
290
+ // src/resources/product/model.ts
291
+ import { createModel } from '@appweaver/data';
292
+
293
+ export default createModel({
294
+ name: 'Product',
295
+ scalars: {
296
+ title: {
297
+ type: 'string',
298
+ minLength: 1,
299
+ maxLength: 200
300
+ },
301
+ price: {
302
+ type: 'float',
303
+ minimum: 0
304
+ },
305
+ status: {
306
+ type: 'enum',
307
+ default: 'Draft',
308
+ values: ['Draft', 'Active', 'Sold']
309
+ },
310
+ description: {
311
+ type: 'string',
312
+ required: false
313
+ },
314
+ lastViewedAt: {
315
+ type: 'dateTime',
316
+ defaultGenerator: 'now()'
317
+ },
318
+ enabled: {
319
+ type: 'boolean',
320
+ default: true
321
+ }
322
+ },
323
+ relations: {
324
+ category: {
325
+ model: 'Category',
326
+ type: 'manyToOne',
327
+ mappedBy: 'products',
328
+ output: {
329
+ type: 'always'
330
+ }
331
+ }
332
+ },
333
+ files: {
334
+ photo: {
335
+ mimeType: 'image/*',
336
+ maxSize: '2 MB',
337
+ image: { quality: 80, maxWidth: 1200 }
338
+ }
339
+ },
340
+ create: {
341
+ omit: ['status']
342
+ },
343
+ update: {
344
+ pick: ['title', 'price', 'status', 'description']
345
+ },
346
+ index: ['title']
347
+ });
348
+ ```
349
+
350
+ A model has an auto-incrementing integer primary key unless the `id` block asks for a generated string one:
351
+
352
+ ```ts
353
+ export default createModel({
354
+ name: 'Comment',
355
+ id: {
356
+ type: 'string',
357
+ generator: 'cuid(2)' // or uuid(), uuid(7), cuid(), nanoid()
358
+ },
359
+ scalars: { body: { type: 'string' } }
360
+ });
361
+ ```
362
+
363
+ The choice flows through the Prisma column, the generated TypeScript type, the `:id` route path parameter, and the
364
+ relation inputs and foreign keys of every model pointing at it. Both ID types can be mixed across models.
365
+
366
+ A relation holding the foreign key of a one-to-many relation is declared with `type: 'manyToOne'`, as `category` above,
367
+ and the model it points at lists the inverse side with `type: 'oneToMany'`. The `omit` and `pick` lists of `read`,
368
+ `create`, and `update` only accept the fields the model declares, its `id`, and its audit fields.
369
+
370
+ A field to hide everywhere is `hidden`. One to hide only where a relation shows it, i.e. the email of the author of a
371
+ public post, goes into the `omit` of that relation's `output` (`output: { type: 'always', omit: ['email'] }`), which
372
+ leaves it out of the routes, the MCP tools and the realtime events while the related model's own routes keep it.
373
+
374
+ Index entries are field names, nested in an array for a composite index. Prefix a name with `-` for a descending index
375
+ or `+` for an ascending one; without a prefix, the database default order is used:
376
+
377
+ ```ts
378
+ index: ['-createdAt', ['status', '-createdAt']];
379
+ ```
380
+
381
+ Foreign key columns are indexed automatically, unless an explicit index already leads with them. `unique` takes the
382
+ same shape as `index` for composite unique constraints, i.e. `unique: [['provider', 'providerAccountId']]`. An entry
383
+ can be a definition with a `type` and `ops` (PostgreSQL), a `where` (partial index) or an `expression`, and
384
+ `generatedColumns` declares the columns PostgreSQL computes, i.e. a `tsvector` for a full-text search; both are
385
+ described in [resources.md](./resources.md#index-config).
386
+
387
+ `views` declares named projections of a model for one audience (`public: { read: { omit: ['seo'], audit: false },
388
+ write: { pick: ['viewCount'] } }`), bound by `createRoutes({ modelName, view })`, `createPolicy({ modelName, view })`
389
+ (composed with the policy of the model), a relation `output: { view: 'public' }` and the MCP tools of the routes; see
390
+ [resources.md](./resources.md#views).
391
+
392
+ Set `softDelete: true` to keep deleted records in the database, marked by the `deletedAt` and `deletedById` columns,
393
+ instead of removing them. Soft deleted records are hidden from every read, so the API behaves exactly as after a real
394
+ delete, and a record can only be restored manually in the database. The relations cascading on delete are soft deleted
395
+ with the record, so every model a soft deleted model cascades into must enable `softDelete` too, or the application
396
+ fails to start. Stored files are removed on a regular delete but kept on a soft delete by default, configurable per
397
+ file field with `onResourceDeleted` and `onResourceSoftDeleted`. A kept file stays in the storage, e.g. for audit, but
398
+ is never served again.
399
+
400
+ With `storage.versions.enabled` (off by default), uploading a file again keeps the replaced one as a previous version:
401
+ a single file field always does, an array field for a file named by a `<field>:replace` multipart text part. A previous
402
+ version is served only by the current file's name with `?version=<n>`, listed by `GET /:id/file-versions?name=` and
403
+ deleted by `POST /:id/delete-file-versions` (deleting the `latest` one restores the previous one), kept up to
404
+ `maxCount` (default `10`) and `maxAge` (unlimited by default), overridden per field by `versions` (`false` for none).
405
+ See [storage.md](./storage.md#file-versions).
406
+
407
+ The `series` section declares fields measured over time (`float`, `int`, `boolean`), whose points belong to a resource
408
+ and live apart from its record: in the `<Model>Series` table of the database (`database`, every database), or a
409
+ TimescaleDB hypertable on PostgreSQL (`timescale`). They are written and queried through the
410
+ series routes (`POST /:id/series`, `GET /:id/series?bucket=1h&aggregate=avg`, `POST /series/query`) and the
411
+ `TimeSeriesService`, directly or through the queue (`seriesOptions.ingest`):
412
+
413
+ ```ts
414
+ series: {
415
+ temperature: { type: 'float', minimum: -50, maximum: 150 },
416
+ online: { type: 'boolean' }
417
+ },
418
+ seriesOptions: { ingest: 'queue', retention: '365d', compressAfter: '30d' }
419
+ ```
420
+
421
+ See [timeseries.md](./timeseries.md) for the stores, the ingestion, the routes, the policies and the service.
422
+
423
+ The `spatial` section declares fields holding GeoJSON geometries (`point`, `multiPoint`, `lineString`, `multiLineString`,
424
+ `polygon`, `multiPolygon`, `geometry`), written and read like scalars (a point also as `{ lat, lng }`), and filtered
425
+ with the operators `_near` (meters), `_within`, `_withinBox`, `_intersects` and `_exists`. A record matched by `_near`
426
+ carries its distance as `<field>Distance`, and sorting by the spatial field orders by it. `_near`, `_within` and
427
+ `_intersects` are matched by PostGIS on PostgreSQL (`spatial.provider: postgis`, the default there, needing PostGIS on
428
+ the server) and by the application on every other database (`database`):
429
+
430
+ ```ts
431
+ spatial: {
432
+ location: { type: 'point' },
433
+ deliveryArea: { type: 'polygon', required: false }
434
+ }
435
+ // filter: { location: { _near: { point: { lat: 45.8, lng: 15.97 }, maxDistance: 5000 } } }, sort: 'location'
436
+ // items[0].locationDistance → 412.7
437
+ ```
438
+
439
+ See [spatial.md](./spatial.md) for the values, the operators, the providers and their limits.
440
+
441
+ ### Creating a resource service
442
+
443
+ Resource service defines the business logic layer for a resource: lifecycle hooks (before/after create, update, delete),
444
+ custom data access behavior, and text search configuration. The exported service is automatically invoked by the CRUD
445
+ route handlers to perform database operations for a bound model and trigger side effects.
446
+
447
+ ```ts
448
+ // src/resources/product/service.ts
449
+ import { createService } from '@appweaver/data';
450
+
451
+ export default createService({
452
+ modelName: 'Product',
453
+ afterCreate: (resource) => {
454
+ console.log('Product created:', resource.id);
455
+ },
456
+ textSearch: {
457
+ title: {
458
+ contains: '{input}', // replaced by the searched text
459
+ mode: 'insensitive' // PostgreSQL and MongoDB only
460
+ }
461
+ }
462
+ });
463
+ ```
464
+
465
+ Beyond a few thousand records, use the full-text mode, `textSearch: { mode: 'fts', fields: ['title', 'content'] }`:
466
+ the words of the text are matched with the full-text index of the database, which the application sets up when it
467
+ starts and `weaver migrate` creates (see [resources.md](./resources.md#text-search-example)).
468
+
469
+ The types `weaver generate` emits register every model by name, so the factories and `injectService` infer the model
470
+ types from the model name alone: the hooks of `createService({ modelName: 'Product' })` receive `Product`,
471
+ `ProductCreate`, and `ProductUpdate` values, and a misspelled model name fails to compile. Never pass the types as
472
+ generic arguments. Any code can reach a resource service with `injectService`, typed by the `<Model>ResourceService`
473
+ alias of the model:
474
+
475
+ ```ts
476
+ import { injectService } from '@appweaver/core';
477
+
478
+ const products = injectService('Product'); // ProductResourceService
479
+ const product = await products.find(1);
480
+ const cheapest = await products.single({ price: { _lt: 10 } }, 'price'); // the first match or null
481
+ const count = await products.count({ status: 'Active' });
482
+ const any = await products.exists({ status: 'Sold' });
483
+ ```
484
+
485
+ The `afterUpdate` hook receives the updated resource along with the state it had before the update, i.e.
486
+ `afterUpdate: (product, previous) => { ... }`. The update hooks also run for `replace` (`PUT`).
487
+
488
+ ### Creating the resource routes
489
+
490
+ Resource routes define which endpoints are exposed for a resource and how they behave: the base URL path, the actions
491
+ registered (`actions`, the CRUD ones by default), per-action role and permission requirements, caching settings and
492
+ rate-limiting. The exported routes are registered automatically on application start and derive their request/response schemas
493
+ from the resource model.
494
+
495
+ ```ts
496
+ // src/resources/product/routes.ts
497
+ import { createRoutes } from '@appweaver/web';
498
+
499
+ export default createRoutes({
500
+ modelName: 'Product',
501
+ // Only the listed actions are registered, `crud` standing for find, query, create, update, replace and delete
502
+ actions: ['find', 'query', 'create', 'update', 'replace', 'export'],
503
+ // Applied to every route, unless the route sets the option itself
504
+ defaults: {
505
+ roles: ['Admin', 'User']
506
+ },
507
+ find: {
508
+ cache: true,
509
+ rateLimit: {
510
+ max: 100
511
+ }
512
+ },
513
+ query: {
514
+ cache: { ttl: 5000 },
515
+ // Also serve GET /products/query
516
+ method: 'get-post'
517
+ },
518
+ create: {
519
+ permissions: ['product:create']
520
+ }
521
+ });
522
+ ```
523
+
524
+ `actions` lists the routes of the resource: `crud` (the default) stands for `find`, `query`, `create`, `update`,
525
+ `replace` and `delete`; `aggregate`, `export` and the bulk routes are registered only when listed, i.e.
526
+ `actions: ['crud', 'aggregate', 'export']`. The file and time series routes of a model with such fields too: `files`
527
+ and `series` (`['crud', 'files']`), never for a read only route group that does not list them. The `events` and `mcp` of the routes list their actions the same way, none unless set.
528
+ `weaver routes` prints every route, event and tool of every model, with its access and cache.
529
+
530
+ The `method` option of `query` and `aggregate` (`post` by default, `get`, or `get-post`) registers a GET route taking
531
+ the criteria as query parameters. The defaults come from the `RESOURCE_QUERY_METHOD` and `RESOURCE_AGGREGATE_METHOD`
532
+ config (see `references/resources.md`).
533
+
534
+ The `update` config covers both `PATCH /:id` (partial update) and `PUT /:id` (full replace: required fields must be
535
+ present, omitted ones reset to their `default` or `null`). The `replace` config inherits it and overrides it for
536
+ `PUT /:id` only (i.e. `replace: { roles: ['Admin'] }`; leave `replace` out of `actions` for `PATCH` alone). Likewise the `update`
537
+ `omit`/`pick` of the model shapes the input of both routes, so they always accept the same fields.
538
+
539
+ The bulk routes (`POST`, `PATCH`, `PUT`, `DELETE` on `/bulk`) are registered when `actions` lists `bulkCreate`,
540
+ `bulkUpdate`, `bulkReplace` or `bulkDelete`; `bulkReplace` inherits the config of `bulkUpdate`. Each
541
+ request runs all items in one transaction, all or none, and responds with the array of created, updated, or deleted
542
+ records, like its single route, or only with `{ success, count }` when `RESOURCE_BULK_RETURN_RECORDS` or the route's
543
+ `returnRecords` is `false` (see `references/resources.md`).
544
+
545
+ ### Creating a resource policy
546
+
547
+ Resource policy defines row-level security for a resource: dynamic access checks against individual resource instances,
548
+ read restrictions that filter which records are visible to the requester, and file access control. The service layer
549
+ evaluates the exported policy on every CRUD operation to enforce fine-grained authorization beyond a static role or
550
+ permission checks.
551
+
552
+ ```ts
553
+ // src/resources/product/policy.ts
554
+ import { createPolicy } from '@appweaver/data';
555
+
556
+ export default createPolicy({
557
+ modelName: 'Product',
558
+ checkAccess: (user, resource, action) =>
559
+ action !== 'delete' || resource.status === 'Draft',
560
+ readRestrictions: (user) => (user ? undefined : { enabled: true }), // anonymous users see enabled products only
561
+ files: {
562
+ photo: {
563
+ accessType: 'public'
564
+ }
565
+ }
566
+ });
567
+ ```
568
+
569
+ `checkAccess` denies the action by returning `false`, `readRestrictions` returns extra filter conditions for the reads
570
+ (or nothing to restrict none), and `writeRestrictions` returns data merged into the created or updated record.
571
+
572
+ A record's creator is its `createdById`, an audit field every model has unless its `audit` leaves it out, set to the
573
+ user of the request on create. Restricting a write to the creator (the route keeping the roles allowed to write):
574
+
575
+ ```ts
576
+ // src/resources/book/policy.ts: editors update only the books they created, admins any book
577
+ import { createPolicy, hasRole } from '@appweaver/data';
578
+
579
+ export default createPolicy({
580
+ modelName: 'Book',
581
+ checkAccess: (user, resource, action) =>
582
+ action !== 'update' || (!!user && (hasRole(user, 'Admin') || resource.createdById === user.id))
583
+ });
584
+ ```
585
+
586
+ Policy and file policy callbacks may be `async`, and receive a `null` user for an unauthenticated request. The
587
+ application's own calls outside of a request (jobs, seeders, tasks, tests) skip the policies, unless run as a user with
588
+ `runAs(user, fn)`; inside a request, wrap trusted system code in `withoutPolicies(() => ...)`.
589
+
590
+ Wrap several service calls in `runTransaction(async () => ...)` (optionally with an isolation level first) to commit
591
+ or roll them back together.
592
+
593
+ ### Creating an authentication model and service
594
+
595
+ Use `createAuthModel` and `createAuthService` instead of `createModel`/`createService` when the resource represents an
596
+ authenticatable user. They cannot be used independently! If an auth model is created, then also auth service must exist.
597
+
598
+ `createAuthModel` extends the config with: `email`, `passwordHash`, `verifiedEmail`, `phone`, `verifiedPhone`,
599
+ `enabled`, `logoutAt` scalars; a virtual `password` field (write-only); a `roles` relation; a `twoFactorMethods`
600
+ relation (while 2FA is enabled, managed by the 2FA routes only); and an optional `apiKeys` relation (when
601
+ `SECURITY_API_KEY_ENABLED` is set). An API key acts as its owner, or within the `roles` and `permissions` it
602
+ lists,
603
+ a subset of its owner's (`AUTH_API_KEY_PERMISSION_DENIED` otherwise), narrowed on every request; see
604
+ [security.md](./security.md#api-key-scope). A declared `email` overrides only its `hidden`, `redact`,
605
+ `example`, `minLength`, `maxLength` and `pattern` (it stays the required unique address the sign-in looks the user up
606
+ by), a declared `phone` only its `unique`, `hidden`, `redact` and `example` (the routes never write it, the phone
607
+ verification does),
608
+ and any other auth field replaces a declared one of the same name.
609
+
610
+ `createAuthService` extends the config with automatic password hashing on create/update, an optional
611
+ `registrationData` callback to customize registration payload (for OAuth2 logins its `additionalData` argument includes
612
+ `firstName`, `lastName`, `avatarUrl`, and a downloaded `avatarFile` unless `SECURITY_OAUTH2_FETCH_AVATAR_ENABLED` is
613
+ turned off), an optional `registrationFiles` callback that maps the model's file fields to files stored right after
614
+ the user is created (the avatar included, since a file must be linked to an existing resource), and an optional
615
+ `checkOAuth2User` callback invoked before a user is registered or authenticated via OAuth2 (return nothing to proceed,
616
+ or a string, an `Error`, or an `AppweaverError` to abort the login, the last one thrown as it is).
617
+
618
+ ```ts
619
+ // src/resources/user/model.ts
620
+ import { createAuthModel } from '@appweaver/data';
621
+
622
+ export default createAuthModel({
623
+ name: 'User',
624
+ scalars: {
625
+ name: {
626
+ type: 'string',
627
+ maxLength: 100
628
+ }
629
+ },
630
+ files: {
631
+ avatar: {
632
+ mimeType: 'image/(png|jpeg|gif)',
633
+ maxSize: '2 MB',
634
+ image: { quality: 80, maxHeight: 800, fit: 'inside' }
635
+ }
636
+ }
637
+ });
638
+ ```
639
+
640
+ ```ts
641
+ // src/resources/user/service.ts
642
+ import { createAuthService } from '@appweaver/data';
643
+
644
+ export default createAuthService({
645
+ modelName: 'User',
646
+ registrationData: (_, email, password) => ({
647
+ email,
648
+ password,
649
+ roles: [1, 2]
650
+ }),
651
+ registrationFiles: (_, data) => ({ avatar: data?.avatarFile })
652
+ });
653
+ ```
654
+
655
+ The create and update inputs of an auth model include its `roles`, `password`, and `enabled` fields, so a project
656
+ scaffolded with `web` lets only the `Admin` role create, update, delete, and change the files of users through the
657
+ `User` routes, and
658
+ signs new users up with the `User` role. A policy on the auth model applies only to the API routes: the framework's own
659
+ sign-up, logout, password change, and 2FA flows run with `withoutPolicies`, so a policy never blocks them.
660
+
661
+ Two-factor authentication, off by default (`SECURITY_ACCOUNT_TWO_FACTOR_ENABLED`), offers three methods per user, `Email` and `Sms` codes and an authenticator app (`Totp`),
662
+ each enabled, ordered and disabled by the user with the `/auth/account/two-factor` routes; the first one is their default. A
663
+ sign-in of a user with a method (or of every user with `SECURITY_ACCOUNT_TWO_FACTOR_FORCED`) returns the tokens of the `twoFactor`
664
+ scope with `twoFactorMethods`, passed by `POST /auth/account/two-factor/challenge { method? }` and
665
+ `POST /auth/account/two-factor/verify { challengeId, code }`, then `POST /auth/exchange-token`. The SMS method needs a phone
666
+ number verified with `/auth/account/send-verify-phone` and an SMS sender (`@appweaver/twilio`), the TOTP method the
667
+ `SECURITY_ACCOUNT_TWO_FACTOR_TOTP_ENCRYPTION_KEY`. A user who lost their methods signs in once per code with the recovery codes
668
+ of `POST /auth/account/two-factor/recovery-codes` (challenge `method: 'Recovery'`). With
669
+ `SECURITY_ACCOUNT_TWO_FACTOR_REMEMBER_DEVICE_ENABLED`, `verify { rememberDevice: true }` makes the exchange answer a
670
+ `deviceToken`, sent with the next `login` (or OAuth2 exchange) to skip 2FA on that device. A route that needs a missing feature is not
671
+ registered, so the OpenAPI spec lists only the usable ones: the email verification and password reset need a mailer,
672
+ the phone verification an SMS sender, the 2FA routes 2FA enabled, and `/auth/exchange-token` an OAuth2 provider or 2FA. See
673
+ [security.md](./security.md#two-factor-authentication-2fa).
674
+
675
+ ### Querying resources with filters
676
+
677
+ The `filter` option of the `query` and `aggregate` service methods, the `filter` argument of `single`, `count`,
678
+ `exists`, and `export` (and the `filter` of the matching `POST /query`, `POST /aggregate`, `POST /export` bodies)
679
+ mirrors the WHERE part of a database query. It combines `_`-prefixed operators
680
+ with plain value shorthands and nests through relations:
681
+
682
+ - **Logical**: `_and`, `_or`, `_not`, `_nor` — take a filter object (each entry becomes one condition) or a list of
683
+ filter objects.
684
+ - **Comparison**: `_eq`, `_ne`, `_gt`, `_gte`, `_lt`, `_lte`, `_in`, `_nin`, `_between`, `_like`, `_ilike`, `_starts`,
685
+ `_ends`, `_contains`, `_exists`, `_not`. Operators combined in one object must all match.
686
+ - **List fields**: `_has`, `_hasSome`, `_hasEvery`, `_isEmpty`.
687
+ - **Relations**: `_some`, `_every`, `_none` for list relations, `_exists` for any relation.
688
+ - **Shorthands**: a bare value matches by equality, a list by inclusion, a two-value list on a numeric or date field as
689
+ an inclusive range, and a bare value or list on a relation matches by id.
690
+ - **Limits**: at most `resource.filterMaxConditions` conditions, `filterMaxDepth` levels and `filterMaxListValues`
691
+ values in a list, else `400 RESOURCE_FILTER_TOO_COMPLEX`; the fields a relation `omit`s from its output cannot be
692
+ filtered or sorted on through it.
693
+
694
+ ```ts
695
+ import { injectService } from '@appweaver/core';
696
+ import { UserQuery } from '@/types/generated';
697
+
698
+ const filter: UserQuery = {
699
+ _and: {
700
+ firstName: { _eq: 'John', _exists: true },
701
+ avatar: {
702
+ _or: { title: { _eq: 'Avatar' }, description: { _like: '%avatar%' } }
703
+ }
704
+ },
705
+ _or: [{ firstName: { _like: 'Jo%' } }, { lastName: 'Doe' }],
706
+ roles: { _some: { name: { _contains: 'Admin' } } }
707
+ };
708
+
709
+ const users = await injectService('User').query({
710
+ filter,
711
+ page: 1,
712
+ size: 50,
713
+ sort: '-createdAt'
714
+ });
715
+ ```
716
+
717
+ `query` takes a single options object, the same shape as the `POST /query` body: `filter`, `page` (default `1`),
718
+ `size` (default `50`), `sort` (default `-createdAt`), `cursor`, and `totalCount` (default `false`, bounded by
719
+ `resource.countLimit`; ask for it on the first page only). An offset beyond `resource.maxOffset` is refused, page deeper
720
+ with the cursors.
721
+
722
+ Filters are typed by `QueryFilter<T>` from `@appweaver/common`, and `weaver generate` emits a
723
+ `<Model>Query = QueryFilter<Model>` alias per model. Over HTTP, they are validated against a generated per-model
724
+ `<Model>QueryFilter` JSON schema, which rejects unknown and hidden fields with a `400` `VALIDATION_FAILED` error.
725
+
726
+ ## Sorting
727
+
728
+ The `sort` option of `query`, the `sort` argument of `single` and `export`, and the `sort` property of the `POST /query`
729
+ and `POST /export` bodies accept either a comma-separated field list, where a `-` prefix sorts descending, or an
730
+ object of `asc` and `desc` field directions. Both sort by a field of an included to-one relation and by the record
731
+ count of a to-many relation:
732
+
733
+ ```ts
734
+ await injectService('Post').query({ sort: '-author.createdAt,tagsCount,id' });
735
+ await injectService('Post').query({
736
+ sort: { author: { createdAt: 'desc' }, tagsCount: 'asc', id: 'asc' }
737
+ });
738
+ ```
739
+
740
+ A hidden, virtual, or array scalar field, a field of a to-many relation, or a relation the action does not include is
741
+ rejected with a `RESOURCE_INVALID_SORT` error (400). Sort inputs are typed by `QuerySort<T>` from `@appweaver/common`,
742
+ with a `<Model>Sort`
743
+ alias emitted per model and validated over HTTP against a generated `<Model>QuerySort` JSON schema. The default is
744
+ `-createdAt`, and every sort is terminated with the primary key so paging stays deterministic.
745
+
746
+ ## Optimistic concurrency
747
+
748
+ The single-record responses carry an `ETag` (the quoted `updatedAt`); sending it, or the `updatedAt` read, as
749
+ `If-Match` on `PATCH`, `PUT` or `DELETE /:id` (`update(id, data, { ifMatch })` in code) fails a write of a record
750
+ changed since with `412 RESOURCE_PRECONDITION_FAILED`. See
751
+ [resources.md](./resources.md#optimistic-concurrency-if-match).
752
+
753
+ ## Aggregating
754
+
755
+ `aggregate` takes a single options object, the same shape as the `POST /aggregate` body: `select`, `filter`,
756
+ `dateField` (default `createdAt`), `from` (inclusive), `to` (exclusive), and `interval`. Without `from` and `to` the
757
+ whole filter is aggregated; without `interval` only the `total`, `items` being empty. An `interval` is an amount and a
758
+ unit of `s`, `m`, `h`, `d`, `w`, `mo` or `y` (`'1d'`), its periods starting at `from` or at the earliest record
759
+ (truncated to the unit), at most `resource.aggregateMaxPeriods` (1000). The required `select` holds the operators
760
+ to apply per field. Only the numeric fields (`count`, `sum`, `avg`, `min`, `max`, `first`, `last`), the date fields (all
761
+ but `sum` and `avg`), and the numeric `id` and audit fields of the model can be aggregated:
762
+
763
+ ```ts
764
+ await injectService('Post').aggregate({
765
+ select: {
766
+ counter: { count: true, sum: true, avg: true, first: true, last: true },
767
+ publishedAt: { min: true, max: true }
768
+ },
769
+ dateField: 'createdAt',
770
+ from: '2026-01-01T00:00:00.000Z',
771
+ to: '2026-01-08T00:00:00.000Z',
772
+ interval: '1d'
773
+ });
774
+ ```
775
+
776
+ The aggregate runs in one SQL statement grouping the records by period. A filter it cannot express in SQL (a relation,
777
+ JSON or list filter) runs one Prisma aggregation per period instead, in a transaction. `first` and `last` take the
778
+ value held by the earliest and the latest record of a period, ordered by the aggregated `dateField` (ties broken by
779
+ `id`).
780
+
781
+ Any other field (string, boolean, enum, JSON, array, hidden, virtual, or a relation), an operator its type does not
782
+ support, an empty selection, or a `dateField` that is not a date field is rejected with a `RESOURCE_INVALID_AGGREGATE`
783
+ error (400). Selections are
784
+ typed by `AggregateSelect<T>` from `@appweaver/common`, with a `<Model>Aggregate` alias emitted per model, and validated
785
+ over HTTP against a generated `<Model>AggregateSelect` JSON schema.
786
+
787
+ The response type is inferred from the selection, so a selection given as an object literal (or declared with
788
+ `satisfies <Model>Aggregate`) narrows it to the selected fields, while one annotated as `<Model>Aggregate` keeps every
789
+ aggregatable field of the model:
790
+
791
+ ```ts
792
+ const stats = await injectService('Post').aggregate({
793
+ select: { counter: { sum: true } }
794
+ });
795
+ stats.total.counter?.sum; // typed
796
+ stats.total.publishedAt; // compile error, the field was not selected
797
+ ```
798
+
799
+ ## Registering a custom route
800
+
801
+ Use `registerRoute` to register a custom [Fastify route](https://fastify.dev/docs/latest/Reference/Routes/) handler. The
802
+ handler is a Fastify plugin function that defines one or more routes. An optional config object controls authentication,
803
+ caching, and the bot checks (`recaptcha`/`recaptchaAction` for reCAPTCHA, `turnstile`/`turnstileAction` for Cloudflare
804
+ Turnstile). When a custom route's 2xx response schema references resource output models (`<Name>`, `<Name>Single` or
805
+ `<Name>Multiple` — directly or nested inside custom schemas), virtual field values (e.g. `File.url`) are projected onto
806
+ the response payload automatically before serialization.
807
+
808
+ Route and model schemas are written with [TypeBox](https://github.com/sinclairzx81/typebox) 1.x (`typebox`), a
809
+ dependency of every scaffolded project at the version the framework uses, which `weaver upgrade` keeps in step.
810
+ TypeBox 1.x has no `Type.Composite`: merge object schemas with `Composite` of `@appweaver/common`. Its types declare
811
+ no JSON Schema keyword, so read one through `schemaNode(schema).$id` (`SchemaNode`). It ships ES modules only: the
812
+ Jest preset of `@appweaver/tooling` compiles them, and a project's own Jest config transforms `.mjs` and keeps `typebox`
813
+ out of `transformIgnorePatterns`.
814
+
815
+ Request validation is strict: a `body`, `querystring` or `params` property the route schema does not declare is
816
+ rejected with `VALIDATION_FAILED` (`rule: "additionalProperties"`, `message: "is not allowed"`), never silently dropped.
817
+ Every object schema declaring `properties` is closed, unless it sets `additionalProperties` itself, so an object meant
818
+ to accept arbitrary keys sets `additionalProperties: true`. The members of a `Type.Intersect` (an `allOf` of several
819
+ schemas) stay open, and `headers` are never closed.
820
+
821
+ ```ts
822
+ // src/plugins/custom-route.ts
823
+ import { registerRoute, Router } from '@appweaver/web';
824
+ import { Type } from 'typebox';
825
+
826
+ registerRoute(
827
+ async function (router: Router) {
828
+ router.get('/search-result', {
829
+ schema: {
830
+ summary: 'Sample search result response route',
831
+ response: {
832
+ 200: Type.Ref('SearchResult')
833
+ }
834
+ },
835
+ handler: async () => {
836
+ return { message: 'Hello, world!' };
837
+ }
838
+ });
839
+ },
840
+ { public: true, cache: { ttl: 15000 } }
841
+ );
842
+ ```
843
+
844
+ ## Rendering templates and translating
845
+
846
+ The `templates/` files render emails, HTML pages, XML documents or any text, and the `locales/<locale>.json` files
847
+ translate keys anywhere in the application. The two are independent: templates render without translation files, and
848
+ translations work without the template engine. The application always gives the locale (a request parameter, a user
849
+ field,
850
+ ...), falling back to `LOCALE_DEFAULT`. A template named `exports/orders.xml` is the file
851
+ `templates/exports/orders.xml.hbs`, and `templates/exports/orders.de.xml.hbs` is its `de` variant.
852
+ See [templates.md](./templates.md).
853
+
854
+ ```ts
855
+ import { TemplateEngine, templateContentType } from '@appweaver/common';
856
+ import { EmailService, inject, LocaleService } from '@appweaver/core';
857
+
858
+ // Any format, i.e. an XML document returned by a custom route
859
+ const xml = await inject(TemplateEngine).render(
860
+ 'exports/orders.xml',
861
+ { orders },
862
+ { locale }
863
+ );
864
+ reply.type(templateContentType('exports/orders.xml')).send(xml);
865
+
866
+ // An email of the emails/order-shipped.{html,subject}.hbs templates, its text derived from the HTML
867
+ await inject(EmailService).sendEmail({
868
+ to,
869
+ template: 'emails/order-shipped',
870
+ data: { order },
871
+ locale
872
+ });
873
+
874
+ // A translated string, i.e. in a service hook
875
+ inject(LocaleService).translate('inbox.unread', 'de', { msg_cnt: 3 });
876
+ ```
877
+
878
+ A translation is an ICU MessageFormat message in a JSON file of nested objects, translated by its dotted key
879
+ (`inbox.unread`), with plural forms by the CLDR categories of the locale: `{ "inbox": { "unread": "You have {msg_cnt,
880
+ plural, =0 {no unread messages} one {# unread message} other {# unread messages}}" } }`.
881
+
882
+ Inside the templates, `{{t "key" name=value}}` translates into the rendered locale, layouts and components are partials
883
+ (`{{#> layouts/page.html}}...{{/layouts/page.html}}`), and `formatDate`, `formatNumber`, `formatCurrency` format in the
884
+ locale. The account emails (verification, password reset, 2FA) render the `emails/*` templates of the application,
885
+ scaffolded by `@appweaver/create`, or without them are sent as plain text of the `emails.*` translations.
886
+
887
+ An email's `from` overrides the sender of the `mailer` config, see [the sender](./mailer.md#the-sender).
888
+
889
+ To check a template while editing it, enable `template.preview.enabled` in the `dev` environment: `GET
890
+ /templates/emails/order-shipped.html?_locale=de&order.number=WS-1` renders it with the query parameters as its data
891
+ (dotted names nest, `_data` takes a JSON object). It is open without authentication unless `template.preview.auth` is
892
+ `true`. See [templates.md](./templates.md#previewing-templates).
893
+
894
+ ## Handling errors
895
+
896
+ Services, policies, hooks, jobs and workers throw an `AppweaverError` subclass carrying a stable `code` (the `ErrorCode`
897
+ enum of `@appweaver/common`) and typed `details`, never an HTTP status. Only the API layer maps the code to a status and
898
+ responds with RFC 9457 problem details (`application/problem+json`), i.e.
899
+ `{ type, title, status, code, detail, instance, requestId, errors, details }`. A schema validation failure responds with
900
+ `VALIDATION_FAILED` and its invalid `errors`, and a database constraint violation with a `DATABASE_*` code naming the
901
+ violated fields, i.e. `DATABASE_UNIQUE_VIOLATION` (409) for a taken email, so there is no need to look a value up
902
+ before creating a record.
903
+
904
+ ```ts
905
+ import { ApplicationError, ErrorCode } from '@appweaver/common';
906
+ import { defineErrors, ResourceError } from '@appweaver/common';
907
+ import { errorResponses } from '@appweaver/web';
908
+
909
+ // A module of its own, imported where the codes are used
910
+ export const ShopErrors = defineErrors({
911
+ OutOfStock: { status: 409, title: 'Product out of stock' }
912
+ });
913
+
914
+ throw new ResourceError(ErrorCode.ResourceNotFound, 'Order not found', {
915
+ model: 'Order',
916
+ id
917
+ });
918
+ throw new ApplicationError(ShopErrors.OutOfStock, 'Only 2 left', { productId });
919
+
920
+ // The documented errors of a custom route, see the response schema of registerRoute
921
+ const response = {
922
+ 200: Type.Ref('OrderSingle'),
923
+ ...errorResponses(ShopErrors.OutOfStock)
924
+ };
925
+ ```
926
+
927
+ Use the framework class that fits (`ResourceError`, `RequestError` for invalid input, `AuthError`, `FileError`, ...),
928
+ and an `ApplicationError` with a code registered by `defineErrors` for a business rule of the application. Never throw a
929
+ plain `Error` for an expected failure, it responds with `INTERNAL_ERROR` (500). Translate the errors of a direct Prisma
930
+ call with `toDatabaseError(e, 'Model')`.
931
+
932
+ ## Logging
933
+
934
+ Log with a named logger, `createLogger('billing')` of `@appweaver/common`, so `log.levels.billing` can set its level
935
+ apart from `log.level`. A module lists the names of its loggers in the `loggers` of its manifest, so
936
+ `appweaver.schema.json` suggests them in `log.levels`. The application chooses its own levels: `info` for the behavior
937
+ worth seeing in the
938
+ production logs (a scheduled job's result, an order placed), `debug` for the details of how it got there. See
939
+ [logging.md](./logging.md) for the levels the framework logs at, its loggers and the config.
940
+
941
+ ## Telemetry
942
+
943
+ The framework records OpenTelemetry traces and metrics on its own: the HTTP requests, the database operations, the
944
+ queue jobs (in the trace of their sender), the scheduled jobs, the emails, the text messages and the tasks. They are
945
+ exported once the `telemetry` module is added (`weaver module add telemetry`, `@appweaver/opentelemetry`), over OTLP
946
+ to the `telemetry.endpoint`, and every log record carries the `trace_id` of its span. Add spans and metrics of the
947
+ application with the helpers of `@appweaver/common`, never with a vendor SDK:
948
+
949
+ ```ts
950
+ import { currentSpan, telemetryCounter, withSpan } from '@appweaver/common';
951
+
952
+ const invoices = telemetryCounter('billing.invoices');
953
+
954
+ currentSpan()?.setAttribute('order.id', orderId); // the span of the request or the job
955
+ const pdf = await withSpan(
956
+ 'invoice render',
957
+ { attributes: { 'order.id': orderId } },
958
+ () => render(orderId)
959
+ );
960
+ invoices().add(1);
961
+ ```
962
+
963
+ See [telemetry.md](./telemetry.md) for what is recorded, the config, the backends (`configureTelemetry`) and
964
+ `recordTelemetry` of `@appweaver/testing`.
965
+
966
+ ## Audit log
967
+
968
+ `audit.enabled` records every request (the user, the client address, the status, the error code) in the `AuditLog`
969
+ table and the changed fields of every record the resource services write in `AuditChange`, the passwords and secrets
970
+ redacted, both kept for `audit.retention`. The `auth`, `read`, `write`, `changes` and `custom` categories are switched
971
+ and kept on their own, the reads off by default. Leave out paths, models and actions with `audit.excludePaths`,
972
+ `audit.excludeModels` and `audit.excludeActions`, or a route with `audit: false`, and keep a field's values out with
973
+ `redact: true`. Code writing through Prisma directly records its changes with `AuditService.recordChange`. See
974
+ [audit.md](./audit.md).
975
+
976
+ ## Realtime events
977
+
978
+ With the `realtime` module (`@appweaver/realtime`), clients subscribe over WebSocket or SSE to the channels of the
979
+ application and the resource events of the models exposing them, and call custom actions. Nothing is exposed unless
980
+ declared, every event is checked against the access of the user, and `public: true` opens a part to anonymous clients
981
+ once `realtime.anonymousEnabled` is set:
982
+
983
+ ```ts
984
+ export const orderShipped = createChannel({
985
+ name: 'order.shipped',
986
+ payload: Type.Object({ orderId: Type.Integer(), customerId: Type.Integer() }),
987
+ deliver: (user, payload) => payload.customerId === user?.id
988
+ });
989
+ await orderShipped.publish({ orderId: 7, customerId: 1 });
990
+
991
+ createRoutes({
992
+ modelName: 'order',
993
+ events: { actions: ['create', { action: 'update', public: true }] }
994
+ });
995
+ createPolicy({
996
+ modelName: 'order',
997
+ events: (user, { current }) => current.customerId === user?.id
998
+ });
999
+ createRealtimeAction({
1000
+ name: 'chat.typing',
1001
+ payload: Type.Object({ roomId: Type.Integer() }),
1002
+ handler: ({ roomId }, { user }) =>
1003
+ typing.publish({ roomId, userId: user!.id })
1004
+ });
1005
+ ```
1006
+
1007
+ To stream chunks rather than events (the tokens of an LLM answer, bytes), use a **streaming action** for the caller
1008
+ alone, or `createStream` for the subscribers of a key. A subscriber is checked once, never per chunk, and a chunk
1009
+ reaches another instance only while one of them has a subscriber:
1010
+
1011
+ ```ts
1012
+ createRealtimeAction({
1013
+ name: 'assistant.prompt',
1014
+ payload: Type.Object({ prompt: Type.String() }),
1015
+ stream: { codec: 'text', coalesce: 16 },
1016
+ async *handler({ prompt }, { signal }) {
1017
+ for await (const token of llm.stream(prompt, { signal })) yield token; // signal: cancelled or client gone
1018
+ }
1019
+ });
1020
+
1021
+ export const roomAnswer = createStream({
1022
+ name: 'room.answer',
1023
+ subscribe: (user, _, key) => isMember(user, key)
1024
+ });
1025
+ const writer = roomAnswer.open(roomId);
1026
+ writer.write('Hello');
1027
+ writer.end();
1028
+ ```
1029
+
1030
+ An action with `input` receives the chunks a client streams over the WebSocket (`context.input`, paced by credits),
1031
+ i.e. the audio of a microphone. A stream with `resource: { model }` lets subscribe only the users able to `find` the
1032
+ record of the key, so the policy of the model decides. A logout, a disabling or a lost role ends the calls of a user at
1033
+ once (their `signal` aborts), over HTTP too.
1034
+
1035
+ On a rolling update an instance drains: it moves its clients to the other instances (`1012`), relays the streaming
1036
+ actions they resume there until they end, and waits for its calls at most `realtime.shutdownGracePeriod`.
1037
+
1038
+ The generated client calls `client.realtime.subscribe`, `on`, `send`, `emit`, `call` (a streaming action, an async
1039
+ iterable of its chunks, with `call.input` or `{ input }` for an input) and `stream`. See
1040
+ [realtime.md](./realtime.md).
1041
+
1042
+ ## AI models
1043
+
1044
+ With the `ai` module (`@appweaver/ai` and `@appweaver/openai`), `AiService` calls the models of the endpoints of the
1045
+ `ai` config: any OpenAI-compatible server (Ollama, LM Studio, OpenRouter, OpenAI, ...), all usable at once. A model is a
1046
+ reference `<endpoint>:<model>` (`local:qwen3:8b`) or an alias of `ai.aliases` (`fast`, any name), so each environment
1047
+ picks its models (the built-in `mock` endpoint in tests):
1048
+
1049
+ ```ts
1050
+ const ai = inject(AiService);
1051
+ const { text } = await ai.generate({
1052
+ model: 'fast',
1053
+ system: 'Be brief.',
1054
+ prompt: question
1055
+ });
1056
+ for await (const delta of ai.stream({
1057
+ prompt: { template: 'prompts/answer', data }
1058
+ }))
1059
+ send(delta);
1060
+ const { object } = await ai.generateObject({
1061
+ prompt: ticket.body,
1062
+ schema: TicketTriage
1063
+ });
1064
+ const label = await ai.classify(ticket.body, ['bug', 'billing']);
1065
+ await ai.generate({ prompt: 'Where is order 42?', tools: [getOrder] }); // createAiTool, run as the user
1066
+ await ai.generateQueued({ prompt: 'Summarize ...' }); // through the `ai` queue, on any instance
1067
+ ```
1068
+
1069
+ A stream is an async iterable of text: a streaming realtime action returns it, `pipeAiStream` writes it into a
1070
+ `createStream` writer, `aiEventStream` into an SSE response. See [ai.md](./ai.md).
1071
+
1072
+ ## MCP server
1073
+
1074
+ With the `mcp` module (`@appweaver/mcp`), AI agents call the application over the Model Context Protocol at
1075
+ `POST /mcp`, authenticated like the API (JWT, API keys) and running as that user, so the policies apply. Nothing is
1076
+ exposed unless declared: resource actions with the `mcp` key of `createRoutes`, custom tools with `createMcpTool`.
1077
+ `update`, `delete` and tools marked `destructive` also need `mcp.destructiveEnabled`:
1078
+
1079
+ ```ts
1080
+ createRoutes({
1081
+ modelName: 'post',
1082
+ mcp: { actions: ['find', 'query', 'create'], exclude: ['note'] }
1083
+ }); // the access of the API routes
1084
+ createMcpTool({
1085
+ name: 'refundOrder',
1086
+ input: Type.Object({ orderId: Type.Integer() }),
1087
+ roles: ['support'],
1088
+ destructive: true,
1089
+ handler: ({ orderId }) => refunds.refund(orderId)
1090
+ });
1091
+ ```
1092
+
1093
+ `mcp.cache.enabled` caches the read-only tool results per user, `mcp.rateLimit.enabled` limits the tool calls per
1094
+ user, and `mcp.oauth2.enabled` lets the MCP clients sign their users in by themselves (OAuth discovery, dynamic
1095
+ client registration, PKCE) through the OAuth2 providers of `security.oauth2`. See [mcp.md](./mcp.md).
1096
+
1097
+ ## Registering a custom model
1098
+
1099
+ Use `registerModel` to register a custom [TypeBox](https://github.com/sinclairzx81/typebox) schema as a named model.
1100
+ Registered models are added to the schema registry and can be referenced by `$ref` in route schemas.
1101
+
1102
+ ```ts
1103
+ // src/plugins/custom-model.ts
1104
+ import { registerModel } from '@appweaver/web';
1105
+ import { Type } from 'typebox';
1106
+
1107
+ registerModel(
1108
+ Type.Object(
1109
+ {
1110
+ id: Type.Number(),
1111
+ title: Type.String(),
1112
+ score: Type.Number({ minimum: 0, maximum: 1 })
1113
+ },
1114
+ { $id: 'SearchResult' }
1115
+ )
1116
+ );
1117
+ ```
1118
+
1119
+ ## Registering plugin
1120
+
1121
+ Use `registerPlugin` to register a custom [Fastify plugin](https://fastify.dev/docs/latest/Reference/Plugins/). Plugins
1122
+ are registered with `fastify-plugin` so their decorators and hooks are scoped to the entire server. You can declare
1123
+ optional dependencies on other named plugins.
1124
+
1125
+ ```ts
1126
+ // src/plugins/audit-log.ts
1127
+ import { registerPlugin } from '@appweaver/web';
1128
+
1129
+ registerPlugin('audit-log', async (server) => {
1130
+ server.addHook('onResponse', async (request, reply) => {
1131
+ console.log(`${request.method} ${request.url} → ${reply.statusCode}`);
1132
+ });
1133
+ });
1134
+ ```
1135
+
1136
+ ## Dependency injection
1137
+
1138
+ Use `define` to register a value or class in the app context, and `inject` to retrieve it. Class constructors are lazily
1139
+ instantiated as singletons on the first injection.
1140
+
1141
+ ```ts
1142
+ import { Cache } from '@appweaver/common';
1143
+ import { define, inject } from '@appweaver/core';
1144
+
1145
+ define(MyCacheService, Cache); // register class under abstract token
1146
+ define('https://api.example.com', 'ApiBaseUrl'); // register plain value
1147
+
1148
+ const cache = inject(Cache); // resolves singleton instance
1149
+ const url = inject<string>('ApiBaseUrl'); // resolves by string token
1150
+ ```
1151
+
1152
+ The infrastructure providers (`Storage`, `Mailer`, `Queue`, ...) are defined by the modules from the `provider` keys,
1153
+ so `main.ts` never wires them. Inject an optional one with a fallback, or check it first:
1154
+
1155
+ ```ts
1156
+ import { Mailer } from '@appweaver/common';
1157
+ import { inject, isDefined } from '@appweaver/core';
1158
+
1159
+ const mailer: Mailer | undefined = inject(Mailer, false); // undefined with MAILER_PROVIDER=none
1160
+ if (isDefined(Mailer)) {
1161
+ /* ... */
1162
+ }
1163
+ ```
1164
+
1165
+ A registered class setting the static `[LIFECYCLE] = true` tag has its hooks of `@appweaver/common` called:
1166
+ `onInit()` when the application starts, `onReady()` once every service is initialized, `onShutdown()`
1167
+ first on stop, and `onDestroy()` last;
1168
+ see [dependency-injection.md](./dependency-injection.md#lifecycle-hooks).
1169
+
1170
+ ## Writing a seeder
1171
+
1172
+ A seeder is a TypeScript file that must export at least one asynchronous function responsible for executing database
1173
+ seeding logic. Seeder files follow the same conventions as migration files: they can only be executed once, and their
1174
+ execution status is recorded in the database table `_seeders`. Seeders are executed in alphabetical order; therefore,
1175
+ the recommended naming convention is to prefix the filename with an ordinal number (e.g., `001-create-admin-user.ts`).
1176
+
1177
+ During execution of seeder functions, the full application context is available, which means it is possible to inject
1178
+ any service or model previously defined in the main application logic or exported from other NPM packages.
1179
+
1180
+ ```ts
1181
+ // database/seeders/001-create-admin-user.ts
1182
+
1183
+ import { hashPassword, systemConfig } from '@appweaver/data';
1184
+ import { randomString } from '@appweaver/common';
1185
+ import { db } from '@db/client';
1186
+
1187
+ export async function createAdminUser(): Promise<void> {
1188
+ const password =
1189
+ systemConfig.ADMIN_INITIAL_PASSWORD || randomString(16, { extra: false });
1190
+
1191
+ await db.user.create({
1192
+ data: {
1193
+ firstName: 'Admin',
1194
+ lastName: 'Admin',
1195
+ email: systemConfig.ADMIN_INITIAL_EMAIL,
1196
+ passwordHash: await hashPassword(password),
1197
+ roles: {
1198
+ connectOrCreate: [
1199
+ {
1200
+ where: { name: 'Admin' },
1201
+ create: {
1202
+ name: 'Admin',
1203
+ permissions: {
1204
+ connectOrCreate: [
1205
+ { where: { name: 'manage' }, create: { name: 'manage' } },
1206
+ { where: { name: 'view' }, create: { name: 'view' } }
1207
+ ]
1208
+ }
1209
+ }
1210
+ }
1211
+ ]
1212
+ }
1213
+ }
1214
+ });
1215
+ }
1216
+ ```