@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Luka Matosevic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://appweaver.co" target="_blank"><img src="https://raw.githubusercontent.com/lmatosevic/appweaver/refs/heads/main/resources/appweaver-logo.svg" width="460" alt="Appweaver Logo" /></a>
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <p align="center">
6
+ The AI agent skill of Appweaver, the AI-first <a href="https://nodejs.org" target="_blank">Node.js</a> framework for backends built with agents.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@appweaver/skill" target="_blank"><img src="https://img.shields.io/npm/v/@appweaver/skill.svg" alt="NPM Version" /></a>
11
+ <a href="https://github.com/lmatosevic/appweaver/blob/main/LICENSE" target="_blank"><img src="https://img.shields.io/npm/l/@appweaver/skill.svg" alt="Package License" /></a>
12
+ <a href="https://www.npmjs.com/package/@appweaver/skill" target="_blank"><img src="https://img.shields.io/npm/dw/@appweaver/skill.svg" alt="NPM Downloads" /></a>
13
+ <a href="https://github.com/lmatosevic/appweaver/actions/workflows/ci.yml?query=branch%3Amain" target="_blank"><img src="https://img.shields.io/github/actions/workflow/status/lmatosevic/appweaver/ci.yml?branch=main&label=CI" alt="CI Status" /></a>
14
+ <a href="https://codecov.io/gh/lmatosevic/appweaver" target="_blank"><img src="https://codecov.io/gh/lmatosevic/appweaver/graph/badge.svg" alt="Test Coverage" /></a>
15
+ <a href="https://nodejs.org" target="_blank"><img src="https://img.shields.io/node/v/@appweaver/skill.svg" alt="Node Version" /></a>
16
+ </p>
17
+
18
+ ## Description
19
+
20
+ The AI agent skill of [Appweaver](https://github.com/lmatosevic/appweaver): `SKILL.md`, the framework guidelines
21
+ (`GUIDELINES.md`) and the references of every module, released with the framework.
22
+
23
+ A project created with `npm create @appweaver` has it as a dev dependency. `weaver skill sync` copies it into the
24
+ `skills/appweaver/` of the agent directories of the project (`.claude`, `.agents`, `.github`, ...), and `weaver upgrade`
25
+ runs it after upgrading the packages, so the skill always matches the installed framework version.
26
+
27
+ ```bash
28
+ npm install --save-dev @appweaver/skill
29
+ npx weaver skill sync
30
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /** The directories of the AI agents a project may have, each holding its skills in `skills/`. */
2
+ export declare const AGENT_DIRS: readonly [".claude", ".junie", ".kiro", ".pi", ".github", ".opencode", ".agents"];
3
+ /** The name of the skill directory in the `skills/` of an agent directory. */
4
+ export declare const SKILL_NAME = "appweaver";
5
+ /**
6
+ * The directory of the skill files (`SKILL.md`, `GUIDELINES.md` and `references/`): the `skill/` of the published
7
+ * package, or the `skill/` of the repository when running from the sources.
8
+ *
9
+ * @return {string} The absolute path of the skill directory.
10
+ */
11
+ export declare function skillDir(): string;
12
+ /**
13
+ * Checks if a project has an agent directory.
14
+ *
15
+ * @param {string} projectDir - The root directory of the project.
16
+ * @param {string} agentDir - The agent directory, relative to the project (`.claude`).
17
+ * @return {boolean} `true` when the directory exists.
18
+ */
19
+ export declare function hasAgentDir(projectDir: string, agentDir: string): boolean;
20
+ /**
21
+ * Copies the skill files into the `skills/appweaver/` of the agent directories of a project, replacing the files of an
22
+ * older version. The project's own `AGENTS.md` or `CLAUDE.md` is never touched.
23
+ *
24
+ * @param {string} projectDir - The root directory of the project.
25
+ * @param {string[]} [agentDirs] - The agent directories to write to, relative to the project; by default the ones of
26
+ * `AGENT_DIRS` the project has.
27
+ * @return {string[]} The skill directories written, relative to the project.
28
+ */
29
+ export declare function syncSkill(projectDir: string, agentDirs?: string[]): string[];
30
+ /**
31
+ * Compares the skill files of an agent directory of a project with the ones of the package: every file of the skill,
32
+ * `SKILL.md`, `GUIDELINES.md` and `references/`.
33
+ *
34
+ * @param {string} projectDir - The root directory of the project.
35
+ * @param {string} agentDir - The agent directory, relative to the project (`.claude`).
36
+ * @return {string[]} The files changed, missing, or left from an older version, relative to the skill directory and
37
+ * sorted; empty when the skill is up to date.
38
+ */
39
+ export declare function outdatedSkillFiles(projectDir: string, agentDir: string): string[];
package/index.js ADDED
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SKILL_NAME = exports.AGENT_DIRS = void 0;
7
+ exports.skillDir = skillDir;
8
+ exports.hasAgentDir = hasAgentDir;
9
+ exports.syncSkill = syncSkill;
10
+ exports.outdatedSkillFiles = outdatedSkillFiles;
11
+ const node_fs_1 = __importDefault(require("node:fs"));
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ /** The directories of the AI agents a project may have, each holding its skills in `skills/`. */
14
+ exports.AGENT_DIRS = [
15
+ '.claude',
16
+ '.junie',
17
+ '.kiro',
18
+ '.pi',
19
+ '.github',
20
+ '.opencode',
21
+ '.agents'
22
+ ];
23
+ /** The name of the skill directory in the `skills/` of an agent directory. */
24
+ exports.SKILL_NAME = 'appweaver';
25
+ /**
26
+ * The directory of the skill files (`SKILL.md`, `GUIDELINES.md` and `references/`): the `skill/` of the published
27
+ * package, or the `skill/` of the repository when running from the sources.
28
+ *
29
+ * @return {string} The absolute path of the skill directory.
30
+ */
31
+ function skillDir() {
32
+ const published = node_path_1.default.join(__dirname, 'skill');
33
+ return node_fs_1.default.existsSync(published)
34
+ ? published
35
+ : node_path_1.default.join(__dirname, '..', '..', 'skill');
36
+ }
37
+ /**
38
+ * Checks if a project has an agent directory.
39
+ *
40
+ * @param {string} projectDir - The root directory of the project.
41
+ * @param {string} agentDir - The agent directory, relative to the project (`.claude`).
42
+ * @return {boolean} `true` when the directory exists.
43
+ */
44
+ function hasAgentDir(projectDir, agentDir) {
45
+ return node_fs_1.default.existsSync(node_path_1.default.join(projectDir, agentDir));
46
+ }
47
+ /**
48
+ * Copies the skill files into the `skills/appweaver/` of the agent directories of a project, replacing the files of an
49
+ * older version. The project's own `AGENTS.md` or `CLAUDE.md` is never touched.
50
+ *
51
+ * @param {string} projectDir - The root directory of the project.
52
+ * @param {string[]} [agentDirs] - The agent directories to write to, relative to the project; by default the ones of
53
+ * `AGENT_DIRS` the project has.
54
+ * @return {string[]} The skill directories written, relative to the project.
55
+ */
56
+ function syncSkill(projectDir, agentDirs) {
57
+ const targets = agentDirs ?? exports.AGENT_DIRS.filter((dir) => hasAgentDir(projectDir, dir));
58
+ const source = skillDir();
59
+ return targets.map((agentDir) => {
60
+ const target = node_path_1.default.join(agentDir, 'skills', exports.SKILL_NAME);
61
+ const absolute = node_path_1.default.join(projectDir, target);
62
+ // A reference removed from the skill must not linger in the project
63
+ node_fs_1.default.rmSync(absolute, { recursive: true, force: true });
64
+ node_fs_1.default.cpSync(source, absolute, { recursive: true });
65
+ return target;
66
+ });
67
+ }
68
+ /**
69
+ * Compares the skill files of an agent directory of a project with the ones of the package: every file of the skill,
70
+ * `SKILL.md`, `GUIDELINES.md` and `references/`.
71
+ *
72
+ * @param {string} projectDir - The root directory of the project.
73
+ * @param {string} agentDir - The agent directory, relative to the project (`.claude`).
74
+ * @return {string[]} The files changed, missing, or left from an older version, relative to the skill directory and
75
+ * sorted; empty when the skill is up to date.
76
+ */
77
+ function outdatedSkillFiles(projectDir, agentDir) {
78
+ const source = skillDir();
79
+ const target = node_path_1.default.join(projectDir, agentDir, 'skills', exports.SKILL_NAME);
80
+ const files = new Set([...listFiles(source), ...listFiles(target)]);
81
+ return [...files]
82
+ .filter((file) => readFile(node_path_1.default.join(source, file)) !== readFile(node_path_1.default.join(target, file)))
83
+ .sort();
84
+ }
85
+ /** The files of a directory and its subdirectories, relative to it with `/` separators. */
86
+ function listFiles(dir) {
87
+ if (!node_fs_1.default.existsSync(dir)) {
88
+ return [];
89
+ }
90
+ return node_fs_1.default
91
+ .readdirSync(dir, { recursive: true, withFileTypes: true })
92
+ .filter((entry) => entry.isFile())
93
+ .map((entry) => node_path_1.default
94
+ .relative(dir, node_path_1.default.join(entry.parentPath, entry.name))
95
+ .split(node_path_1.default.sep)
96
+ .join('/'));
97
+ }
98
+ function readFile(file) {
99
+ try {
100
+ return node_fs_1.default.readFileSync(file, 'utf8');
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@appweaver/skill",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "3.1.0",
4
+ "description": "Appweaver - the backend framework for AI-first development (@skill)",
5
+ "author": "Luka Matosevic",
6
+ "license": "MIT",
7
+ "main": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "keywords": [
17
+ "appweaver",
18
+ "agent-skill",
19
+ "agent-skills",
20
+ "ai-agents",
21
+ "claude-code",
22
+ "codex",
23
+ "cursor",
24
+ "llm"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/lmatosevic/appweaver.git",
29
+ "directory": "packages/skill"
30
+ },
31
+ "maintainers": [
32
+ {
33
+ "name": "Luka Matosevic",
34
+ "email": "lukamatosevic5@gmail.com",
35
+ "web": "https://lukamatosevic.com"
36
+ }
37
+ ],
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "engines": {
42
+ "node": ">= 24.7"
43
+ }
6
44
  }
@@ -0,0 +1,383 @@
1
+ # Appweaver Guidelines
2
+
3
+ Appweaver is a TypeScript/Node.js library for building web applications. Built on Fastify (HTTP) and Prisma (ORM), it
4
+ provides factory methods for creating resource models, services, policies, and routes with sensible defaults.
5
+
6
+ ## Project structure
7
+
8
+ - `database/` - migrations, seeders, generated Prisma client
9
+ - `dist/` - transpiled JavaScript output
10
+ - `public/` - static files (if enabled)
11
+ - `src/features/` - application logic (vertical slice architecture)
12
+ - `src/resources/` - resources (models, services, policies, routes)
13
+ - `src/types/` - generated and manual types
14
+ - `src/main.ts` - application entrypoint
15
+ - `src/modules/<name>/module.ts` - local modules, enabled without config (optional)
16
+ - `test/e2e/` - end-to-end tests
17
+ - `test/unit/` - unit tests
18
+ - `.env` / `.env.{env}` - environment variable overrides (optional)
19
+ - `appweaver.json` - central configuration, with the overrides of each environment under `environments`
20
+ - `appweaver.{env}.json` - environment-specific overrides, loaded over the `environments` section (optional)
21
+ - `Dockerfile` - Docker image definition
22
+
23
+ **IMPORTANT:** `{env}` is controlled by `NODE_ENV` environment variable. The environment names are `test`, `local`,
24
+ `dev`, `staging`, `qa`, and `prod` (`development` resolves to `dev`, `production` or an unset `NODE_ENV` to `prod`).
25
+
26
+ ## Application entrypoint
27
+
28
+ ```ts
29
+ // src/main.ts
30
+ import { createApp } from '@appweaver/core';
31
+ import { logger } from '@appweaver/common';
32
+
33
+ createApp().catch((err) => logger.error(err));
34
+ ```
35
+
36
+ The framework is assembled from modules: `@appweaver/core`, `@appweaver/data` (Prisma, resources, factories),
37
+ `@appweaver/web` (the server, routes, auth, errors) and a driver package per library (`@appweaver/redis`,
38
+ `@appweaver/bullmq`, `@appweaver/cron`, `@appweaver/nodemailer`, `@appweaver/handlebars`, `@appweaver/sharp`), each
39
+ enabled by being a dependency of the project. Install the driver package, never its library (`@appweaver/redis`, not
40
+ `ioredis`), and import each name from the package exporting it (`createModel` from `@appweaver/data`, `createRoutes`
41
+ from `@appweaver/web`). Each `provider` key defaults to `auto` (the driver of an enabled module), `none` turns a
42
+ contract off, and `APP_MODULES_DISABLED=@appweaver/web` runs a worker or scheduled jobs without a server
43
+ (`HEALTH_CHECK_PORT` answers the health checks). See [modules.md](references/modules.md).
44
+
45
+ ## Creating resources
46
+
47
+ Resources are the core building blocks. There are four types: **model**, **service**, **routes**, and **policy**.
48
+ Exported resources are loaded automatically on application start.
49
+
50
+ Dependencies: **model** ← **service** ← **routes**, and **model** ← **policy** (optional)
51
+
52
+ Only a model is required. If a service exists, a model must exist. If routes exist, a service must exist. A policy
53
+ needs only the model.
54
+
55
+ **DOS:**
56
+
57
+ - Use default configuration values whenever possible
58
+ - Rely on library defaults for `omit`/`pick`, and `input`/`output` settings
59
+ - Use default `mimeType` and `namePattern` patterns in file configurations unless specifically requested
60
+ - Prefer storing configuration in JSON file (`appweaver.json`) over environment (`.env`) file, but keep secrets in
61
+ `.env` and reference them from the JSON file as `${VAR}` (i.e.
62
+ `"url": "postgresql://${DB_USER:-app}:${DB_PASSWORD}@..."`)
63
+ - Always create all four resource configs (model, service, routes, and policy) unless specified otherwise
64
+
65
+ **DON'TS:**
66
+
67
+ - Don't explicitly set default values in configuration unless specifically requested
68
+ - Don't override `omit`/`pick` for `read`, `create` and `update` settings unnecessarily
69
+ - Don't specify `input`/`output` configurations if defaults suffice
70
+ - Don't modify file's `mimeType` and `namePattern` patterns unless specifically instructed
71
+ - Don't customize index arrays without an explicit requirement
72
+
73
+ ### Model
74
+
75
+ ```ts
76
+ // src/resources/product/model.ts
77
+ import { createModel } from '@appweaver/data';
78
+
79
+ export default createModel({
80
+ name: 'Product',
81
+ scalars: {
82
+ title: { type: 'string', minLength: 1, maxLength: 200 },
83
+ price: { type: 'float', minimum: 0 },
84
+ status: {
85
+ type: 'enum',
86
+ default: 'Draft',
87
+ values: ['Draft', 'Active', 'Sold']
88
+ },
89
+ description: { type: 'string', required: false },
90
+ lastViewedAt: { type: 'dateTime', defaultGenerator: 'now()' },
91
+ enabled: { type: 'boolean', default: true }
92
+ },
93
+ relations: {
94
+ category: {
95
+ model: 'Category',
96
+ type: 'manyToOne',
97
+ mappedBy: 'products',
98
+ output: { type: 'always' }
99
+ }
100
+ },
101
+ files: {
102
+ photo: { mimeType: 'image/*', maxSize: '2 MB' }
103
+ },
104
+ create: { omit: ['status'] },
105
+ update: { pick: ['title', 'price', 'status', 'description'] },
106
+ index: ['title']
107
+ });
108
+ ```
109
+
110
+ Index entries are field names, nested in an array for a composite index (`[['status', 'createdAt']]`). Prefix a name
111
+ with `-` for a descending index or `+` for an ascending one (`['-createdAt']`); unprefixed uses the database default.
112
+ The side holding the foreign key of a one-to-many relation is a `manyToOne` relation, and its inverse side a
113
+ `oneToMany` one.
114
+
115
+ ### Service
116
+
117
+ ```ts
118
+ // src/resources/product/service.ts
119
+ import { createService } from '@appweaver/data';
120
+
121
+ export default createService({
122
+ modelName: 'Product',
123
+ afterCreate: (resource) => {
124
+ console.log('Product created:', resource.id);
125
+ },
126
+ textSearch: {
127
+ title: { contains: '{input}', mode: 'insensitive' }
128
+ }
129
+ });
130
+ ```
131
+
132
+ The generated types register every model by name, so `createService`, `createAuthService`, `createPolicy`, and
133
+ `injectService` infer the model types from the model name. Never pass the model types as generic arguments. Inject a
134
+ resource service anywhere by its model name:
135
+
136
+ ```ts
137
+ import { injectService } from '@appweaver/core';
138
+
139
+ const products = injectService('Product'); // ProductResourceService
140
+ const page = await products.query({
141
+ filter: { status: 'Active' },
142
+ size: 20,
143
+ sort: '-createdAt'
144
+ });
145
+ const first = await products.single({ title: 'Lamp' }); // the first match or null
146
+ ```
147
+
148
+ ### Routes
149
+
150
+ ```ts
151
+ // src/resources/product/routes.ts
152
+ import { createRoutes } from '@appweaver/web';
153
+
154
+ export default createRoutes({
155
+ modelName: 'Product',
156
+ actions: ['find', 'query', 'create', 'update', 'replace'], // no delete route
157
+ find: { cache: true, roles: ['Admin', 'User'], rateLimit: { max: 100 } },
158
+ query: { cache: { ttl: 5000 } },
159
+ create: { permissions: ['product:create'] }
160
+ });
161
+ ```
162
+
163
+ ### Policy
164
+
165
+ ```ts
166
+ // src/resources/product/policy.ts
167
+ import { createPolicy } from '@appweaver/data';
168
+
169
+ export default createPolicy({
170
+ modelName: 'Product',
171
+ checkAccess: (user, resource, action) =>
172
+ action !== 'delete' || resource.status === 'Draft',
173
+ readRestrictions: (user) => (user ? undefined : { enabled: true }), // anonymous users see enabled products only
174
+ files: {
175
+ photo: { accessType: 'public' }
176
+ }
177
+ });
178
+ ```
179
+
180
+ ### Auth model and service
181
+
182
+ Use `createAuthModel` and `createAuthService` for authenticatable users. They must be used together.
183
+
184
+ `createAuthModel` adds: `email`, `passwordHash`, `verifiedEmail`, `phone`, `verifiedPhone`, `enabled`, `logoutAt`
185
+ scalars; a virtual `password` field; a `roles` relation; a `twoFactorMethods` relation (while 2FA is enabled); and
186
+ optional `apiKeys` relation. The 2FA methods (`Email`, `Sms`, `Totp`) are managed by the `/auth/account/two-factor` routes,
187
+ and `authUser.twoFactorMethods` lists the confirmed ones, the first being the default (see the security reference).
188
+
189
+ `createAuthService` supports an optional `registrationData` callback to customize the registration payload, an optional
190
+ `registrationFiles` callback that stores files on the model's file fields right after the user is created (used to keep
191
+ the avatar an OAuth2 provider serves), and an optional `checkOAuth2User` callback to allow or reject OAuth2
192
+ registrations/logins (return nothing to proceed, or a string/`Error` to abort).
193
+
194
+ ```ts
195
+ // src/resources/user/model.ts
196
+ import { createAuthModel } from '@appweaver/data';
197
+
198
+ export default createAuthModel({
199
+ name: 'User',
200
+ scalars: { name: { type: 'string', maxLength: 100 } },
201
+ files: { avatar: { mimeType: 'image/(png|jpeg|gif)', maxSize: '2 MB' } }
202
+ });
203
+ ```
204
+
205
+ ```ts
206
+ // src/resources/user/service.ts
207
+ import { createAuthService } from '@appweaver/data';
208
+
209
+ export default createAuthService({
210
+ modelName: 'User',
211
+ registrationData: (_, email, password) => ({
212
+ email,
213
+ password,
214
+ roles: [1, 2]
215
+ }),
216
+ registrationFiles: (_, data) => ({ avatar: data?.avatarFile })
217
+ });
218
+ ```
219
+
220
+ ## Custom routes, models, and plugins
221
+
222
+ ### Custom route
223
+
224
+ ```ts
225
+ // src/features/custom-route.ts
226
+ import { registerRoute, Router } from '@appweaver/web';
227
+ import { Type } from 'typebox';
228
+
229
+ registerRoute(
230
+ async function (router: Router) {
231
+ router.get('/search-result', {
232
+ schema: {
233
+ summary: 'Search result',
234
+ response: { 200: Type.Ref('SearchResult') }
235
+ },
236
+ handler: async () => ({ message: 'Hello, world!' })
237
+ });
238
+ },
239
+ { public: true, cache: { ttl: 15000 } }
240
+ );
241
+ ```
242
+
243
+ ### Custom model
244
+
245
+ ```ts
246
+ // src/features/custom-model.ts
247
+ import { registerModel } from '@appweaver/web';
248
+ import { Type } from 'typebox';
249
+
250
+ registerModel(
251
+ Type.Object(
252
+ {
253
+ id: Type.Number(),
254
+ title: Type.String(),
255
+ score: Type.Number({ minimum: 0, maximum: 1 })
256
+ },
257
+ { $id: 'SearchResult' }
258
+ )
259
+ );
260
+ ```
261
+
262
+ ### Plugin
263
+
264
+ ```ts
265
+ // src/plugins/audit-log.ts
266
+ import { registerPlugin } from '@appweaver/web';
267
+
268
+ registerPlugin('audit-log', async (server) => {
269
+ server.addHook('onResponse', async (request, reply) => {
270
+ console.log(`${request.method} ${request.url} → ${reply.statusCode}`);
271
+ });
272
+ });
273
+ ```
274
+
275
+ ## Dependency injection
276
+
277
+ ```ts
278
+ import { Cache, Mailer } from '@appweaver/common';
279
+ import { define, inject, isDefined } from '@appweaver/core';
280
+
281
+ define(MyCacheService, Cache); // register class under abstract token
282
+ define('https://api.example.com', 'ApiBaseUrl'); // register plain value
283
+
284
+ const cache = inject(Cache); // resolve singleton
285
+ const url = inject<string>('ApiBaseUrl'); // resolve by string token
286
+ const mailer = inject(Mailer, false); // undefined when no mailer is selected
287
+ isDefined(Mailer); // check without creating the instance
288
+ ```
289
+
290
+ The modules define the providers from the `provider` keys; `main.ts` never loads them.
291
+
292
+ ## Seeders
293
+
294
+ Seeder files export async functions and run in alphabetical order. Prefix filenames with ordinal numbers.
295
+
296
+ ```ts
297
+ // database/seeders/001-create-admin-user.ts
298
+ import { hashPassword } from '@appweaver/data';
299
+ import { db } from '@db/client';
300
+
301
+ export async function createAdminUser(): Promise<void> {
302
+ await db.user.create({
303
+ data: {
304
+ firstName: 'Admin',
305
+ lastName: 'Admin',
306
+ email: 'admin@appweaver.co',
307
+ roles: {
308
+ connectOrCreate: [
309
+ {
310
+ where: { name: 'Admin' },
311
+ create: {
312
+ name: 'Admin',
313
+ permissions: {
314
+ connectOrCreate: [
315
+ { where: { name: 'manage' }, create: { name: 'manage' } },
316
+ { where: { name: 'view' }, create: { name: 'view' } }
317
+ ]
318
+ }
319
+ }
320
+ }
321
+ ]
322
+ }
323
+ }
324
+ });
325
+ }
326
+ ```
327
+
328
+ ## Common commands
329
+
330
+ | Command | Description |
331
+ | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
332
+ | `npm run generate` | Generate the types and Prisma schema of the models and `appweaver.schema.json` (only the latter without `data`) |
333
+ | `npm run build` | Build the application |
334
+ | `npm run start` | Start in production mode |
335
+ | `npm run dev` | Start in development (watch) mode |
336
+ | `npm run seed` | Seed the database |
337
+ | `npm run migrate` | Apply pending database migrations |
338
+ | `npm run test` | Run unit tests |
339
+ | `npm run e2e` | Run end-to-end tests |
340
+ | `npm run format` | Format code with Prettier |
341
+ | `npm run lint` | Lint code with ESLint |
342
+ | `weaver migration check` | Check whether the models need a new migration |
343
+ | `weaver migration new <name>` | Create a new database migration |
344
+ | `weaver upgrade` | Upgrade all @appweaver/\* packages |
345
+ | `weaver module add <name>` | Add a module (redis, docker, templates…) |
346
+ | `weaver module new <name>` | Create a local module in `src/modules/` |
347
+ | `weaver resource new <name>` | Create the model, service, routes and policy of a resource in `src/resources/<name>/` |
348
+ | `weaver config check` | Validate the config of every module |
349
+ | `weaver doctor` | Check the project (packages, `.env`, config, generated files, migrations, skill) and print what to fix first |
350
+ | `weaver openapi` | Generate OpenAPI specification |
351
+ | `weaver run <task> [args...]` | Run a `createTask` of `src/tasks/` by name or file, then exit (`weaver run` lists them) |
352
+
353
+ ## Testing
354
+
355
+ - Test files must use the **`.test.ts`** extension.
356
+ - Unit tests live in `test/unit/`, end-to-end tests in `test/e2e/`; name each file after the module it covers.
357
+ - Add or update tests whenever a feature is added or existing behaviour changes, and run `npm run test` before
358
+ considering the task done.
359
+ - A test calling a service directly skips the policies (the application's own call): a test file of the policies calls
360
+ `runTestsAsAnonymous()` of `@appweaver/testing` at its top level, and a test sets its user with `runAs(user, fn)`.
361
+ - Prisma refuses the dangerous database actions (`prisma migrate dev` and `reset`) of the `weaver migration` and
362
+ `weaver test` commands when an AI agent runs them and `DATABASE_AI_DANGEROUS_ACTIONS_ENABLED` is `false`. Never
363
+ change that config yourself to get past the refusal.
364
+
365
+ ## References
366
+
367
+ - Application CLI (weaver): [cli.md](references/cli.md)
368
+ - Application configuration: [configuration.md](references/configuration.md)
369
+ - Modules & providers: [modules.md](references/modules.md)
370
+ - Application resources: [resources.md](references/resources.md)
371
+ - Dependency injection: [dependency-injection.md](references/dependency-injection.md)
372
+ - Security details: [security.md](references/security.md)
373
+ - Storage & File management: [storage.md](references/storage.md)
374
+ - Database & Migrations: [database.md](references/database.md)
375
+ - Events & Hooks: [events.md](references/events.md)
376
+ - Cache management: [cache.md](references/cache.md)
377
+ - Queue jobs: [queue.md](references/queue.md)
378
+ - Scheduling jobs: [scheduler.md](references/scheduler.md)
379
+ - Sending emails: [mailer.md](references/mailer.md)
380
+ - Sending text messages (SMS): [sms.md](references/sms.md)
381
+ - Templates & translations: [templates.md](references/templates.md)
382
+ - Generating an HTTP client for using API: [client.md](references/client.md)
383
+ - Framework errors: [errors.md](references/errors.md)