# @rangka/core

Server-side runtime engine for the Rangka framework.

## How it works

This package boots a complete Fastify server from declarative model/page definitions. It handles module discovery, schema resolution, database sync, REST API generation, authentication, lifecycle hooks, background jobs, and events. All server-side behavior lives here.

## Architecture

```
src/
├── api/            — Fastify server, route generation, handlers, OpenAPI schema
├── audit/          — Audit trail recording
├── auth/           — JWT sessions, permissions, scopes, field-level access
├── boot/           — Boot sequence: discovery, schema loading, merging, registry init
├── db/             — DatabaseClient, auto-sync (DiffEngine), model-ops (Kysely CRUD)
├── events/         — EventBus (transaction-scoped pub/sub)
├── external-model/ — Adapter-based external data sources
├── fixtures/       — Seed data loading
├── helpers/        — Stamping, ownership checks, validation utilities
├── hooks/          — Hook registry, executor, middleware, context builder
├── jobs/           — Job registry, worker, scheduler, enqueue
├── model-api/      — Query builder, filter translation, scope enforcement, includes
├── plugins/        — Plugin lifecycle, adapter registry, loader
├── schema/         — SchemaRegistry, relationship resolution
├── services/       — ServiceRegistry, service factory
├── validation/     — Field-level validation engine
├── widgets/        — Server-side widget registry (for studio)
├── context.ts      — FrameworkContext builder
├── errors.ts       — AppError, BadRequestError, NotFoundError
└── index.ts        — Public exports
```

## Key internal systems

| System      | Entry point                   | Purpose                                        |
| ----------- | ----------------------------- | ---------------------------------------------- |
| Boot        | `boot/index.ts`               | Orchestrates full server startup               |
| Schema      | `schema/registry.ts`          | Holds resolved models and relationships        |
| Model API   | `model-api/index.ts`          | CRUD with scopes, permissions, filters         |
| Hooks       | `hooks/executor.ts`           | Lifecycle pipeline (validate → before → after) |
| Middleware  | `hooks/middleware.ts`         | Wraps hooks into Fastify request handlers      |
| Routes      | `api/route-generator.ts`      | Auto-generates REST endpoints per model        |
| Auth        | `auth/session.ts`             | JWT session management                         |
| Permissions | `auth/permission-registry.ts` | Role-based model/field access                  |
| Scopes      | `auth/scope-registry.ts`      | Row-level tenant isolation                     |
| Services    | `services/registry.ts`        | Named business logic with DI                   |
| Jobs        | `jobs/registry.ts`            | Background job processing                      |
| Events      | `events/bus.ts`               | Transaction-scoped pub/sub                     |

## Commands

```bash
pnpm --filter @rangka/core build   # Compile TypeScript
pnpm --filter @rangka/core test    # Unit tests
pnpm test:integration              # Integration tests (from repo root)
```

## Contributing

- All data access in hooks/services goes through `ctx.models` (the ModelAccess interface). Never write raw Kysely for basic CRUD.
- All hooks/services/jobs receive `FrameworkContext`. Use it. Don't build parallel context objects.
- The hook pipeline is fixed: validate → beforeSave → (write) → afterSave. Don't add new phases.
- Route handlers are auto-generated by `route-generator.ts`. Don't duplicate CRUD routes manually.
- Registries are singletons created at boot. Extend existing ones, don't create new ones for the same purpose.
- Helper utilities (`helpers/stamping.ts`, `helpers/validation.ts`, `helpers/assert-ownership.ts`) must be reused. Don't recreate stamping or ownership logic.
- This package imports from `@rangka/shared` only. Never import from `@rangka/client`.
