# Adaptivestone Framework - Complete Documentation

> This file is auto-generated from the Docusaurus documentation.
> Generated on: 2026-11-01T13:50:51.995Z
> Total documents: 22

---

## Table of Contents

1. 01-intro
2. 02-configs
3. 03-files-inheritance
4. 04-base
5. 05-models
6. 05-modelsOld
7. 06-Controllers / 01-intro
8. 06-Controllers / 02-routes
9. 06-Controllers / 03-middleware
10. 06-Controllers / 04-error-handling
11. 07-logging
12. 08-i18n
13. 09-testsing
14. 10-cli
15. 11-cache
16. 12-email
17. 12-resize
18. 13-deploy
19. 14-helpers
20. 15-recipes
21. 16-anti-patterns
22. 17-openapi

---



# Document 1: 01-intro

<!-- Source: 01-intro.md -->

# Intro

Welcome to the AdaptiveStone framework documentation. We hope that the documentation is clean and short. Please feel free to edit it via a Git merge request and contact us.

## History

You must be wondering - why another framework, as we currently have a lot of them? But each of them is different.

The Adaptive Stone framework was born around 2016 and has been growing since.

There were a few requirements that no one existing framework could provide us for SAAS at that time - working with multiple databases, scaling out of the box, and a modern approach.

That is why the Adaptive Stone framework was born.

## Features

- Automatically initialized controllers (no config needed)
- Mongoose models
- Winston logger (Sentry logger as a part of Winston logger)
- Node cluster enabled by default (possibility to use with no cluster (dev mode))
- Docker development environment (and production too)
- Integrated Biome (modern alternative to ESLint and Prettier) for code style
- Cache system
- Ability to overwrite any controller, model, and config that came with the framework
- Multi-language support out of the box
- ESM only (no CommonJS)
- TypeScript support (you are able to write everything in JavaScript, but in JS you will have types as a bonus)

:::info Requirements
The framework requires **MongoDB** and an **`AUTH_SALT`** secret — it fails fast at boot if either is missing (set the `MONGO_DSN` env var; `npm run cli createEnv` creates a `.env` with a fresh salt). The runtime requires **Node ≥ 24**.
:::

## Folder Structure

```js
framework/
├─ commands/  // Contains the command folder (CLI)
├─ config/ // Contains config files
├─ controllers/ // Contains controller files
│  ├─ {controller_group_folder}/ // Can contain a folder (will be added to the route)
├─ locales/ // i18n folder with translations
│  ├─ {locale_1}/ // Locale name (en, fr, etc.)
│  │  ├─ translation.json // Translation JSON file
│  ├─ {locale_2}/
│  │  ├─ translation.json
├─ migrations/ // Folder where migration files are stored
├─ models/ // Contains model files
├─ modules/ // Main folder with abstract stuff
├─ public/ // Public stuff (served statically)
├─ services/ // Some services (email, http, etc.)
├─ tests/ // Folder contains basic tests
├─ Cli.ts // Main CLI class
├─ index.ts // Main entry point (creates and starts the Server)
├─ cluster.ts  // Entry point for production (cluster module)
├─ folderConfig.ts // Folder configuration
├─ server.ts // Server class
```

## Framework Structure

![Framework](/img/AdaptiveStroneFramework.jpg)

## Getting Started

Get started by **creating a new project**.

The simplest way to create a new project is to clone the **template** and customize it:

```shell
git clone git@github.com:adaptivestone/framework-example-project.git adaptivestone-example-rename-me
```

## Start Your Project

You should have **[Docker](https://www.docker.com/products/docker-desktop)** and **[Docker Compose](https://docs.docker.com/compose/install/)** installed.

Run the development server:

```shell
cd adaptivestone-example-rename-me
docker compose up
```

Your site starts at `http://localhost:3300`.

Open `src/controllers/Person.ts` and edit some lines: the site **reloads automatically** and applies your changes.

## TypeScript Support

The framework itself is written in TypeScript (erasable syntax), but the project is flexible to use either TypeScript or JavaScript.

You are able to use the modern Node.js runtime to run TypeScript files without any compilation.

You are also able to mix TypeScript and JavaScript files in one project. Just remember that types will only work if the imported file is a TypeScript file and it is imported into a TypeScript file.

## Guides

- [Recipes](15-recipes.md) — a task-oriented cookbook: add a controller, validate a body, paginate, write middleware, override a built-in, test a controller.
- [Anti-patterns](16-anti-patterns.md) — common mistakes and what to do instead.


---


# Document 2: 02-configs

<!-- Source: 02-configs.md -->

# Configs

Every modern application runs on multiple environments and should have the ability to configure itself without changing the code.

## Config Files

Config files are located in ‘src/config/\{filename\}.(js|ts)’. Each config file is mostly unique, and you should refer to the module documentation (or the framework config section).

:::note

Config files are part of the [framework inheritance process](03-files-inheritance.md).

:::

## Environment Variables

Out of the box, the framework supports environment variables with [process.loadEnvFile](https://nodejs.org/api/process.html#processloadenvfilepath). This is part of Node.js since v20.12.0.

The framework will grab and parse the .env file in the root of the project directory to fill environment variables.

The sample project ships with a basic .env.example file. On a fresh clone, `npm run cli createEnv` copies it to `.env` and fills in a new `AUTH_SALT` (see [CLI › Create .env](10-cli.md#create-env)).

:::tip

Do not use environment variables in the code. Use them only inside config files. This will allow you to track variables and split configs and the codebase.

:::

:::tip

Do not push the .env file to the version control system, as it can contain passwords and keys. The file should be unique per environment.
:::

:::tip

Try not to overload the .env file with configuration and keep only private data in it. To manage non-private data, check the [NODE_ENV](#node_env) section.
:::

## NODE_ENV

Depending on the NODE_ENV environment variable, the framework will load additional config files. Data from these files will be merged into the main config with an overwrite.

This is useful when you want to have something that depends on the environment but do not want to overload the .env file.

Also, it's a good practice to keep the basic config in files rather than in the .env file.

**Example:**

```js title="/src/config/sample.ts"
export default {
  variable1: 1,
  variable2: 2,
};
```

```js title="/src/config/sample.production.ts"
export default {
  variable2: 3,
  variable3: 4,
};
```

On a NON-production environment:

```js
const sampleConfig = this.app.getConfig("sample");
//     variable1: 1,
//     variable2: 2
```

On a PRODUCTION environment:

```js
const sampleConfig = this.app.getConfig("sample");
//     variable1: 1,
//     variable2: 3, <-- DIFFERENT
//     variable3: 4  <-- NEW
```

You can use the same approach for different environments (dev, stage, testing, etc.).

## API

```ts
getConfig(configName: string): Record<string, unknown>;
updateConfig(configName: string, config: Record<string, unknown>): Record<string, unknown>;
```

Returns the config based on the config name. It also caches it in memory.

```js
const sampleConfig = this.app.getConfig("sample");
```

Updates the config based on the config name. Returns the updated config.

```js
const sampleConfig = this.app.updateConfig("sample", {
  variableToUpdate: 3,
  anotherVariable: 4,
});
```

## Typed config

The base `getConfig(name)` signature is `Record<string, unknown>`, but the
framework's [type generation](10-cli.md) (`node src/cli.ts generatetypes`) emits
a `genTypes.d.ts` that types each call against your **actual** config file — so
`this.app.getConfig("http").port` is precise, with no cast.

The type is derived from the config's runtime **shape**, not its values, so a
secret value is never written into the generated file. A key read straight from
the environment with **no default** is a special case: at generation time
`process.env.X` may be unset, so the framework reads it from the config
**source** and types it honestly as `string | undefined`.

```ts title="/src/config/hubspot.ts"
export default {
  apiKey: process.env.HUBSPOT_API_KEY, // typed: string | undefined
  region: process.env.HUBSPOT_REGION ?? "eu", // has a default → typed: string
  baseUrl: "https://api.hubspot.com", // literal → typed: string
};
```

```ts
const { apiKey } = this.app.getConfig("hubspot");
// apiKey is `string | undefined` — guard it; no `as` cast needed
if (!apiKey) {
  throw new Error("HUBSPOT_API_KEY is not set");
}
```

The same holds when your config **overrides a framework config** by spreading it. The env reads stay in the framework file, and the generated type still includes them:

```ts title="/src/config/auth.ts"
import originalAuth from "@adaptivestone/framework/config/auth.js";

export default {
  ...originalAuth, // saltSecret: process.env.AUTH_SALT → typed: string | undefined
  isAuthWithVerificationFlow: false,
};
```

No `?? ''` fallback is needed to keep such a key in the type when the variable is unset at generation time (for example, in CI). A key you set to a value in your own file keeps that value's type.

:::tip

If a value is guaranteed present (you assert it at boot), add a non-null
assertion in the config so the generated type is `string`:

```ts
apiKey: process.env.HUBSPOT_API_KEY!, // typed: string
```

:::

:::note

Recovery follows only inline `process.env.X` reads in a config's own
default-exported object. A key whose env read is spread in from another config
(`{ ...baseConfig }`) or hidden behind an indirection isn't followed across that
boundary. Regenerate after changing a config's shape; `generatetypes --check`
fails CI if the committed types are stale.

:::

### Generated array and object shapes

Codegen widens a homogeneous array to a reusable array type. Its type therefore
describes the kind of entries the config contains without freezing the number
of entries that happened to be loaded during generation:

```ts title="/src/config/assets.ts"
export default {
  origins: ["https://one.example", "https://two.example"],
  dimensions: [
    [300, 300],
    [1080, 1080],
  ],
  endpoints: [
    { hostname: "one.example", secure: true },
    { hostname: "two.example", secure: false },
  ],
};
```

The generated shapes are `string[]`, `number[][]`, and
`{ hostname: string; secure: boolean }[]`, respectively. A production override
can therefore contain a different number of entries without creating a false
fixed-length tuple error.

Arrays whose entries have different generated types remain tuples. For example,
`["retries", 3]` becomes `[string, number]`, preserving the useful positional
types. An empty array becomes `unknown[]`: a runtime empty value provides no
evidence from which codegen could infer its element type.

Generated object properties remain exact. The framework intentionally does not
add a `[key: string]` index signature, because that would allow misspelled keys
and falsely claim that every possible string exists. When iterating a finite
generated object, narrow `Object.keys()` back to its real keys:

```ts
const { endpointsByRegion } = this.app.getConfig("assets");
const keys = Object.keys(endpointsByRegion) as Array<
  keyof typeof endpointsByRegion
>;

for (const key of keys) {
  const endpoint = endpointsByRegion[key];
}
```

If a config value is genuinely an open string dictionary rather than a finite
object, declare a local `Record<string, Value>` contract at that dynamic access
boundary. Codegen sees only the keys present in the loaded runtime value and
cannot safely infer that arbitrary future keys are supported.


---


# Document 3: 03-files-inheritance

<!-- Source: 03-files-inheritance.md -->

# File Inheritance

The framework provides a flexible way to overwrite some functionalities from the core. You can create a file with the same name in the same folder, and the framework will use this file instead of the built-in one.

Let’s go with an example. We have a User model built directly with the framework with some user-related stuff. We want to provide a fully different implementation of this model.

To do that, we will create a user model file at the project level in the model folder.

```js
project/
├─ node_modules/
│  ├─ @adaptivestone/
│  │  ├─ framework/
│  │  │  ├─ models/
│  │  │  │  ├─ User.js // Built-in model (published as compiled .js). Mark it as "User_original"
├─ src/
│  ├─ models/ // Contains model files
│  │  ├─ User.ts // File that will be used. Mark it as "User_project"

```

```js
const User = this.app.getModel("User"); // Will return the "User_project" model
```

This also happens at **all** levels of the code. If some code inside the framework asks for the “User” model, it will get the “User_project” model.

The same approach works for models, controllers, and configs.

## How To

### Extend a module with new functionality instead of completely overwriting it

That's easy. Just require the original file and extend it.
Please note: TypeScript types are fully optional. You are able to use plain JavaScript too.

```ts
import OriginalUserModel from "@adaptivestone/framework/models/User.js";
import type {
  GetModelTypeLiteFromSchema,
  ExtractProperty,
} from "@adaptivestone/framework/modules/BaseModel.js";

class User extends OriginalUserModel {
  static get modelStatics() {
    type UserModelLite = GetModelTypeLiteFromSchema<
      typeof User.modelSchema,
      ExtractProperty<typeof User, "schemaOptions">
    >;

    return {
      ...OriginalUserModel.modelStatics, // Grab the original model methods
      getPublic: function getPublic(this: InstanceType<UserModelLite>) {
        return {
          userName: this.name,
        };
      },
    };
  }
}
```

### Disable functions completely

To disable something (like a default controller), the best way is to overwrite it with an empty implementation.

```js
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";

class Auth extends AbstractController {}

export default Auth;
```


---


# Document 4: 04-base

<!-- Source: 04-base.md -->

# Base Class

Each class extends the Base class to have some basic functions, mostly related to logging and the inheritance process.

The Base class implements on-demand logging instance loading. That means the logger will be united only when you first request it. This is an important part of loading speed optimization.

## API

```js
class A extends Base {
  async someFunction() {
    // Access to the logger instance (please follow the logger documentation for more details).
    this.logger;

    // Get files with inheritance.
    const files = await this.getFilesPathWithInheritance(
      `${import.meta.dirname}/../../migrations`,
      this.app.foldersConfig.migrations
    );
  }

  /**
   * Returns the logger group. Just to have all logs grouped logically.
   */
  static get loggerGroup() {
    return "Base_please_overwrite_";
  }

  /**
   * In case of logging, sometimes we might need to replace the name.
   */
  getConstructorName() {
    return this.constructor.name;
  }
}
```

```js
getFilesPathWithInheritance(internalFolder, externalFolder);
```

Will scan two folders and provide a path with inheritance. If the same file is present in both paths, the priority will be given to the external file.


---


# Document 5: 05-models

<!-- Source: 05-models.md -->

# Models

The framework is based on the [Mongoose](https://mongoosejs.com/) library and provides direct access to it.

The model handles database connections.

:::note

Model files are part of the [framework inheritance process](03-files-inheritance.md).

:::

The model uses a class with static methods and properties, providing auto-typing for each model. TypeScript helpers are also available to extract types from the model class.

## Lifecycle

The framework can do the following:

1. Load model files
2. Initialize model files

There are internal options for this (see the Commands section), which are mostly used in commands where you can skip model initialization or load the model without initializing it. This is useful in a few use cases, primarily for type generation.

Under normal conditions, the framework scans the `model` folder and loads all models using the inheritance process.

This is primarily to avoid model 'circular dependencies.'

### Duplicate framework copies

Every model extends `BaseModel` from `@adaptivestone/framework`. If **two different copies** of the framework end up installed (a duplicate/undeduped install), a model can extend `BaseModel` from one copy while the loader runs from the other. `instanceof BaseModel` compares prototype identity, so it is `false` across that copy boundary — and boot used to silently misroute such a model into the legacy (`AbstractModel`) branch, surfacing only later as a confusing downstream failure.

Boot now recognizes the model by its static shape (a `BaseModel` subclass without the `instanceof`) and **fails fast**, naming the offending model:

```text
Model 'Article' extends BaseModel from a DIFFERENT copy of @adaptivestone/framework than the one loading models, so `instanceof BaseModel` is false and it cannot be initialized. This means @adaptivestone/framework is installed more than once (a duplicate/undeduped install). Fix the duplication so a single copy is shared: run `npm ls @adaptivestone/framework` to find the extra copy, then dedupe (align versions, delete node_modules and reinstall, and check your lockfile).
```

The model loader prefixes this with the model name and file (`Failed to initialize model '<Name>' (<file>): …`). The fix is to collapse the duplicate so a single copy is shared:

```bash
npm ls @adaptivestone/framework
```

then dedupe — align versions, delete `node_modules` and reinstall, and check your lockfile. Genuinely legacy (`AbstractModel`-based) models still route to the legacy branch unchanged.

:::tip Module authors

If you publish a package that defines framework models (or otherwise imports `@adaptivestone/framework`), declare the framework as a **peer dependency**, not a regular dependency — that way the host app supplies the single shared copy instead of your package pulling in a second one. `npm link` during local development is the most common trigger for a duplicate copy, since the linked package resolves the framework from its own `node_modules`.

:::

## Base Model

The base model is the core of your models. It handles their structure and initialization.
We have provided a TypeScript example, but you can ignore the types if you only want to use JavaScript.
Using types is fully optional.

```ts
import { BaseModel } from "@adaptivestone/framework/modules/BaseModel.js";

// in case you need to access appInstance - appInstance.getConfig('s3');
import { appInstance } from "@adaptivestone/framework/helpers/appInstance.js";

// These are TypeScript helpers.
import type {
  GetModelTypeFromClass, // `GetModelTypeFromClass` returns model types from the class.
  GetModelTypeLiteFromSchema, // Schema-derived authoring type that breaks class cycles.
} from "@adaptivestone/framework/modules/BaseModel.js";

import mongoose, {
  type Aggregate,
  type Query,
  type Schema,
} from "mongoose";

// Reduced authoring types for static methods, instance methods, virtuals,
// and hooks while the class is still being defined.
type SomeModelLite = GetModelTypeLiteFromSchema<
  typeof SomeModel.modelSchema,
  typeof SomeModel.schemaOptions
>;
type SomeDocument = InstanceType<SomeModelLite>;

class SomeModel extends BaseModel {
  static initHooks(schema: Schema): void {
    // A place to initialize plugins, indexes, and so on.
    // This happens after the class is loaded into Mongoose but before Mongoose initializes it.
    // schema.plugin(PLUGIN_NAME);
    schema.index({ name: "text" }); // or indexes.

    // For hooks, there are two types of `this`: model and queries.
    // https://mongoosejs.com/docs/middleware.html#types-of-middleware
    schema.pre(
      'save',
      async function (this: SomeDocument) {
        ...
      }
    );
    schema.pre('findOneAndDelete', async function (
      this: Query<unknown, SomeDocument>
    ) {
      const docToDelete = await this.model.findOne(this.getFilter());
      ...
    });
    schema.pre('aggregate', function (
      this: Aggregate<unknown>
    ) {
      this.pipeline().unshift({ $match: { archived: { $ne: true } } });
    });
  }

  // The Mongoose schema goes here.
  // This is a complete Mongoose schema.
  // Please refer to the Mongoose documentation: https://mongoosejs.com/docs/guide.html
  static get modelSchema() {
    return {
      someString: { type: String, required: true },
      firstName: String,
      lastName: String,
      email: String,
      orders: [{
        type: mongoose.Schema.Types.ObjectId, // Use Schema.Types.ObjectId for a stored reference.
        ref: "Order", // Models are resolved after the framework has loaded them.
      }],
    } as const; // This helps generate better types (TypeScript only).
  }

  // The Mongoose schema options go here.
  // Please refer to the Mongoose documentation: https://mongoosejs.com/docs/guide.html#options
  static get schemaOptions() {
    return {
      read: "primary",
    } as const; // This helps to generate better types. (TypeScript only)
  }

  /**
   *  Object with static methods.
   * this.app.getModel('SomeModel').findByEmail('email');
   * this.app.getModel('SomeModel').getInfoStatic();
   *
   */
  static get modelStatics() {
    return {
      findByEmail: async function findByEmail(
        this: SomeModelLite, // A type helper to map to the correct `this` context.
        email: string
      ) {
        const instance = await this.find({ email });
        return instance;
      },
      getInfoStatic: async function getInfoStatic(
        model: SomeDocument
      ) {
        await model.populate("orders");
        return {
          _id: model.id,
          email: model.email,
        };
      },
      getInfoStaticWithOrders: async function getInfoStatic(
        model: SomeDocument
      ) {
        const populated = await model.populate<{
          orders: Array<{ id: string; total: number }>;
        }>("orders");
        return {
          _id: populated.id,
          email: populated.email,
          orders: populated.orders,
        };
      },
    };
  }

  /**
   * We should also have instance methods for the model to interact with.
   * const SomeModel = appInstance.getModel('SomeModel');
   * const someModel = await SomeModel.findOne({email:"cfff"});
   * const data = await someModel.getInfo(); // call instance method
   */
  static get modelInstanceMethods() {
    return {
      getInfo: async function getInfo(this: SomeDocument) {
        return {
          _id: this._id,
          email: this.email,
        };
      },
            // anotherMethod,
    };
  }

  /**
   * We should also have virtual methods for the model to interact with.
   * const SomeModel = appInstance.getModel('SomeModel');
   * const someModel = await SomeModel.findOne({email:"cfff"});
   * const fullName = await someModel.fullName // virtual field
   * someModel.fullName = 'Jean-Luc Picard';
   */
  static get modelVirtuals() {
    return {
      fullName: {
        // virtual field
        options: {
          type: Object, // schema
        },
        get(this: SomeDocument) {
          // Getter
          return `${this.firstName} ${this.lastName}`;
        },
        async set(this: SomeDocument, v: string) {
          // Setter
          const firstName = v.substring(0, v.indexOf(" "));
          const lastName = v.substring(v.indexOf(" ") + 1);
          this.set({ firstName, lastName });
        },
      },
    }; // make sure that you not put it as a const
  }

}

export default SomeModel;

// It's good practice to return the type from the model.
export type TSomeModel = GetModelTypeFromClass<typeof SomeModel>;
```

## Authoring types and complete model handles

There is only one runtime schema: `SomeModel.modelSchema`. The two helpers show
that schema at different points in TypeScript's class evaluation:

| Type | Use it for | What it contains |
| --- | --- | --- |
| `GetModelTypeLiteFromSchema<typeof Model.modelSchema, typeof Model.schemaOptions>` | `this:` annotations inside the class while its members are still being inferred | Schema fields and native Mongoose model/document operations |
| `GetModelTypeFromClass<typeof Model>` | Generated types, exports, controllers, services, commands, and tests after the class is complete | Schema fields plus the class's statics, instance methods, and virtuals |

The reduced type cannot include a custom static, method, or virtual that
TypeScript is currently in the middle of inferring. Trying to use the complete
class-derived type inside that same member creates a circular type. This is a
TypeScript evaluation boundary, not a second schema and not a reduced runtime
model.

Keep the reduced alias beside the class-authoring context. Export the complete
class-derived handle:

```ts
type SomeModelLite = GetModelTypeLiteFromSchema<
  typeof SomeModel.modelSchema,
  typeof SomeModel.schemaOptions
>;
type SomeDocument = InstanceType<SomeModelLite>;

export type TSomeModel = GetModelTypeFromClass<typeof SomeModel>;
```

For two complete model classes that refer to each other, put one deliberate
annotation or deferred boundary at the cycle. Renaming the reduced helper or
wrapping the same circular inputs in another conditional type cannot make the
unfinished class available earlier.

## Type corrections in 5.4.1

:::info Requires framework 5.4.1 or newer

The corrections in this section are included in framework 5.4.1. Upgrade from
5.4.0 or earlier to use them.

:::

The schema remains the source of truth. The fixes cover these cases:

- **Nested IDs:** plain nested paths keep no generated `_id`, including inside
  arrays and other subdocuments. Explicit `_id` paths retain their declared
  type. Both inner and wrapper `_id: false` spellings are respected for nested
  documents and arrays. A disabled hydrated subdocument ID reads as `undefined`;
  its raw/lean counterpart has no generated ID field.
- **Schema options:** custom `typeKey` and top-level `_id: false` are carried
  through inference, including nested corrections and lean reads. Pass literal
  `schemaOptions` to `GetModelTypeLiteFromSchema` when they affect the result.
  Timestamp names and disabled timestamp fields follow those options too.
- **Wrapped field overrides:** `TsTypeOverride<TRaw, THydrated>` works inside
  both bare arrays and `{ type: [...] }` arrays. Loaded subdocuments use the
  hydrated override; their `toObject()` results retain the raw override.
- **Virtuals:** a getter's return type determines the exposed value. A
  setter-only virtual accepting `V` is writable and has type `V | undefined`
  when read; assigning it does not imply a readable value is stored. Setters
  remain writable when declared `as const`. A populate virtual without a
  getter or setter is `unknown` and needs narrowing.
- **The `id` virtual:** `schemaOptions: { id: false }` no longer promises an
  `id: string`, and an actual schema path named `id` retains its own type.

### Remaining Mongoose typing limits

A custom virtual named `id` can still intersect with Mongoose's default
`id: string`. A non-string result can therefore collapse to `never`; use a
schema path for a stored value or choose a different virtual name.

Mongoose can accept `null` array elements even where its inferred element type
omits `null`. Lean results also do not acquire hydration defaults. Treat these
as limits of the inferred types when handling such data; successful type
checking is not a replacement for runtime validation or null checks.

## Schema options that affect types

Pass `typeof Model.schemaOptions` as the second argument whenever schema options
affect a document or query result. Keep the options literal with `as const`.

Timestamp options are reflected exactly: either timestamp can be disabled or
renamed, and an omitted key in an object-form timestamp configuration keeps its
default name.

```ts
class AuditModel extends BaseModel {
  static get modelSchema() {
    return { event: { type: String, required: true } } as const;
  }

  static get schemaOptions() {
    return {
      timestamps: { createdAt: "created_on", updatedAt: false },
    } as const;
  }
}

type AuditModelLite = GetModelTypeLiteFromSchema<
  typeof AuditModel.modelSchema,
  typeof AuditModel.schemaOptions
>;
type AuditDocument = InstanceType<AuditModelLite>;

declare const audit: AuditDocument;
audit.created_on; // Date
// audit.createdAt; // Type error: renamed
// audit.updatedAt; // Type error: disabled
```

Mongoose can also make queries lean by default at schema level. With
`lean: true` (or an object-form lean configuration), ordinary reads return plain
objects. Opt out per query when document methods are required:

```ts
class LeanRecord extends BaseModel {
  static get modelSchema() {
    return { title: { type: String, required: true } } as const;
  }

  static get schemaOptions() {
    return { lean: true } as const;
  }
}

type LeanRecordModel = GetModelTypeFromClass<typeof LeanRecord>;
declare const LeanRecordHandle: LeanRecordModel;

const plain = await LeanRecordHandle.findOne();
// plain?.save(); // Type error: the result is a plain object

const document = await LeanRecordHandle.findOne({}, null, { lean: false });
await document?.save(); // Hydrated document
```

If `schemaOptions` is not passed to the schema-derived helper, TypeScript cannot
recover those options from `modelSchema` alone.

:::warning

Models are instantiated once per process, and their instances are then cached. Do not expect constructor or `init` hook calls on every model load.

:::

:::tip

Please do not use the plural form for model names.

**Bad** - Coin**s**

**Good** - Coin

:::

:::tip Annotating `this` on instance methods

An instance method may declare an explicit `this:` to type its body — handy when
the body assumes a narrower shape than the raw document (a populated ref, a
non-null [plugin-reshaped field](#typing-plugin-reshaped-fields), sibling
methods):

```ts
getInfo: async function (this: SomeDocument) {
  return { _id: this._id, email: this.email };
},
```

That annotation types the **body only**. You still call the method directly on
the document — `doc.getInfo()` — on any model handle; the framework drops the
authored `this` from the caller-facing type, since a method accessed on its own
document always has the right `this` at runtime. No `(schema.methods.x as …)
.call(doc, …)` cast is needed.

:::

:::tip Annotating `this` in middleware

Use the context for the middleware category, not one model type everywhere:

```ts
// Document middleware
schema.pre("save", function (this: SomeDocument) {
  this.email;
});

// Query middleware
schema.pre("findOneAndUpdate", function (
  this: Query<unknown, SomeDocument>
) {
  this.getFilter();
  this.getUpdate();
});

// Aggregate middleware
schema.pre("aggregate", function (this: Aggregate<unknown>) {
  this.pipeline();
});
```

The same annotations work when hooks are registered in a loop. A query's
`this` is a Mongoose `Query`; it is not the model and not a hydrated document.

:::

## Typing plugin-reshaped fields

Some Mongoose plugins reshape a field after the schema literal is declared. An
intl plugin may store a locale map behind a `String` path, an encryption plugin
may store a cipher object, and a custom getter may expose a different hydrated
value. The framework can only infer the declared `type:` unless you describe the
plugin's transformation.

Mark the field with `TsTypeOverride<TRaw, THydrated = TRaw>`:

- `TRaw` is the stored shape used by casting/create inputs and lean results;
- `THydrated` is the value exposed by loaded Mongoose documents and hydrated
  subdocuments;
- omitting `THydrated` preserves the original one-type behavior.

Both marker properties are phantom TypeScript fields and are never set at
runtime. The plugin remains responsible for the transformation.

:::info Version requirement

Distinct raw and hydrated overrides require framework **5.2.3 or newer**. The
one-argument `TsTypeOverride<T>` form works in earlier v5 releases and remains
source-compatible.

:::

### One value type on both surfaces

Use one type argument when the plugin exposes the same reshaped value on raw and
hydrated documents:

```ts title="/src/models/Event.ts"
import { BaseModel } from "@adaptivestone/framework/modules/BaseModel.js";
import type { TsTypeOverride } from "@adaptivestone/framework/modules/BaseModel.js";

type EncryptedValue = { ciphertext: string; keyId: string };

function encryptedString<C extends object>(field: C) {
  return field as C & TsTypeOverride<EncryptedValue>;
}

export default class Event extends BaseModel {
  static get modelSchema() {
    return {
      secret: encryptedString({ type: String, encrypted: true }),
      schedule: [{ secret: encryptedString({ type: String, encrypted: true }) }],
      plainField: { type: String }, // unmarked → still `string`
    } as const;
  }
}
```

The static type now follows the runtime value everywhere — no casts:

```ts
const Event = this.app.getModel("Event");
const event = await Event.findOne();
event?.secret?.ciphertext; // `secret` is EncryptedValue
event?.schedule?.[0]?.secret?.keyId; // any depth (nested + subdoc arrays)
event?.plainField; // unmarked field is still `string`
```

### Different raw and hydrated values

A virtual getter can expose a different value from the one stored in MongoDB.
Describe both surfaces once in an application-side schema factory. Include every
state the getter can return—for example, an intl getter may normally return the
selected string but expose the complete locale map after a document method
changes its mode:

```ts title="/src/models/Event.ts"
import { BaseModel } from "@adaptivestone/framework/modules/BaseModel.js";
import type { TsTypeOverride } from "@adaptivestone/framework/modules/BaseModel.js";

type Language = "en" | "fr";
type IntlText = Partial<Record<Language, string>>;
type IntlHydratedValue = string | IntlText;

function intlString<C extends object>(field: C) {
  return field as C & TsTypeOverride<IntlText, IntlHydratedValue>;
}

export default class Event extends BaseModel {
  static get modelSchema() {
    return {
      title: intlString({ type: String, required: true, intl: true }),
      schedule: [
        { title: intlString({ type: String, required: true, intl: true }) },
      ],
    } as const;
  }
}
```

The raw shape is accepted when creating the document. The returned document is
hydrated, while `.lean()` returns the raw locale map:

```ts
const Event = this.app.getModel("Event");

const event = await Event.create({
  title: { en: "Title", fr: "Titre" },
  schedule: [{ title: { en: "Session", fr: "Séance" } }],
});

if (typeof event.title === "string") {
  event.title.toUpperCase(); // selected-language getter state
} else {
  event.title.en; // full-languages getter state
}

const raw = await Event.findById(event._id).lean();
raw?.title.en; // IntlText

const item = event.schedule.create({
  title: { en: "Next", fr: "Suivante" },
});
event.schedule.push(item);
// `item.title` is IntlHydratedValue; its create input was IntlText.
```

Prefer the plugin's nested raw value (`title: { en, fr }`) when its setter
supports it. `TsTypeOverride` describes a field's values; it deliberately does
not synthesize plugin-specific dotted root keys such as `"title.en"` for every
model operation.

:::note

The override is **opt-in** and a strict **no-op** for any field without the
marker — existing models are unaffected. It recurses into nested objects and
subdocument arrays, so a reshaped field can appear at any depth. The same marker
works for any runtime-reshaping plugin (encrypted fields, custom getters, …), not
just intl plugins. The framework does not interpret plugin-specific options such
as `intl: true`; the small application-side factory is the explicit type/runtime
boundary.

:::

## Typing populated references

A reference field (`{ type: Schema.Types.ObjectId, ref: "User" }`) is typed as an
`ObjectId` — that is what is stored, and what you get back when the field is
**not** populated. After `.populate(...)` the runtime value is the referenced
document, but the inferred type stays `ObjectId` (Mongoose cannot know at the
schema level which queries populate it). There are two cast-free ways to type the
populated value, depending on how often you populate the field.

**Per call — `.populate<T>()`.** When you populate occasionally, pass the
populated shape as the type argument at the call site. The returned document is
typed with that field replaced:

```ts
const Boat = this.app.getModel("Boat");
const boat = await Boat.findOne();
const populated = await boat!.populate<{ owner: { email: string } }>("owner");
populated.owner.email; // typed — no cast
```

**Always — mark the field.** When a field is almost always read populated, mark it
with `TsTypeOverride` as the **union** of both states (`ObjectId` when not
populated, the document when it is). Reads then narrow without a cast:

```ts title="/src/models/Boat.ts"
import { BaseModel } from "@adaptivestone/framework/modules/BaseModel.js";
import type { TsTypeOverride } from "@adaptivestone/framework/modules/BaseModel.js";
import { Schema, type Types } from "mongoose";

type PopulatedOwner = { email: string; name: string };

function ref<C extends object, T>(field: C) {
  return field as C & TsTypeOverride<Types.ObjectId | T>;
}

export default class Boat extends BaseModel {
  static get modelSchema() {
    return {
      owner: ref<{ type: typeof Schema.Types.ObjectId; ref: "User" }, PopulatedOwner>({
        type: Schema.Types.ObjectId,
        ref: "User",
      }),
    } as const;
  }
}
```

```ts
const boat = await this.app.getModel("Boat").findOne();
// `owner` is `ObjectId | PopulatedOwner | undefined` — narrow before use:
if (boat?.owner && "email" in boat.owner) {
  boat.owner.email; // typed as PopulatedOwner
}
```

:::note

Refs that are not marked stay plain `ObjectId`, and `.populate<T>()` always works
regardless. Prefer the marker only for fields you consistently populate — the
union forces a narrowing check, which is the honest cost of a field that is
sometimes an id and sometimes a document.

:::

## Recovering a model from a document

Use Mongoose's typed `$model<T>()` method when document code needs its owning
model. Avoid casting `document.constructor`: Mongoose exposes that property as a
general constructor, so it does not preserve the framework model's statics.

```ts
declare const document: SomeDocument;

const SomeModelHandle = document.$model<TSomeModel>();
await SomeModelHandle.findByEmail(document.email ?? "");
```

On an existing document, prefer the no-argument `$model<T>()` overload. The
named overload (`$model<T>("SomeModel")`) passes through a broader Mongoose
constraint that can reject schema-specific model types. For a model selected by
a runtime string, use the application's generated model registry or define a
small local capability type for the operations that branch needs.

## Write inputs and query-local result types

A hydrated document type describes a document returned by Mongoose. It is not a
general create/insert DTO: hydrated subdocuments may contain generated `_id`
fields and document methods that are not present in a plain write payload.

Prefer inference for one-off writes:

```ts
declare const SomeModelHandle: TSomeModel;

await SomeModelHandle.create({
  someString: "required value",
  email: "reader@example.com",
  orders: [],
});
```

### Hydrated subdocuments and array writes

Raw write values and hydrated document properties intentionally have different
types. A plain value passed to `create()` has no generated fields yet. After
Mongoose hydrates it, a subdocument has its generated `_id` and an array of
subdocuments is a real `DocumentArray` with Mongoose's change tracking and
methods.

```ts
const Workflow = this.app.getModel("Workflow");

const workflow = await Workflow.create({
  entries: [{ label: "Initial" }], // no `_id` or defaulted fields required
});

workflow.entries[0]._id; // ObjectId: generated ids are required when read

workflow.entries.push({ label: "Review" }); // Mongoose casts the plain value

const approved = workflow.entries.create({ label: "Approved" });
workflow.entries.push(approved);
workflow.entries.id(approved._id); // hydrated DocumentArray method
```

The same distinction applies to defaulted subdocument fields: callers may omit
them from `Model.create()`, `DocumentArray.push()`, `DocumentArray.create()`, and
`DocumentArray.splice()` input, while the hydrated result exposes the value
Mongoose supplies. An inline `_id: false` removes the generated id instead; it
is not exposed as a usable field on the hydrated subdocument and is absent from
raw/lean results.

### Nested paths are not subdocuments

Only the `{ type: { … } }` spelling builds a subdocument, and only a subdocument
gets a generated `_id`. A plain nested object is a *path grouping*: Mongoose
stores `name.first` and `name.last`, and there is no `name._id` at any point.
The types follow that distinction on every surface, so the runtime shape
assigns without a cast or an `Omit<…>` bridge:

```ts
name: {
  first: { type: String }, // plain nested path — never an `_id`
  last: { type: String },
},
badge: {
  type: { label: { type: String } }, // subdocument — generated `_id`
},
```

```ts
user.name = { first: "Ada" }; // nothing to supply beyond the real fields
user.badge?._id; // ObjectId — a real subdocument
```

Use the `{ type: … }` form when you want a subdocument's own identity and
document methods; keep the plain form when you only want to group related fields
under one prefix.

Replacing a hydrated array with a native JavaScript array by direct property
assignment is intentionally rejected. A native array does not have
`DocumentArray.create()`, `id()`, casting, or change tracking, so accepting it as
the property's read type would make those APIs unsafe. Mutate the existing array
or use Mongoose's setter:

```ts
const replacement = [{ label: "Rebuilt" }];

workflow.entries.splice(
  0,
  workflow.entries.length,
  ...replacement,
);

// Alternatively, replace the whole path through Mongoose's casting setter.
workflow.set("entries", replacement);

// Type error: a native array is not a hydrated DocumentArray.
// workflow.entries = replacement;
```

For filtered hydrated values, keep the `DocumentArray` instance and replace its
contents:

```ts
const remaining = workflow.entries.filter((entry) => entry.label !== "Review");
workflow.entries.splice(0, workflow.entries.length, ...remaining);
```

A lean query returns raw values, so its array fields are ordinary JavaScript
arrays rather than `DocumentArray`s. This raw/hydrated split follows
[Mongoose's TypeScript subdocument model](https://mongoosejs.com/docs/typescript/subdocuments.html)
and does not require a second runtime schema or a separately maintained document
interface.

Primitive schema arrays similarly hydrate as Mongoose arrays rather than native
arrays. Mutate them in place or use `set()` for a whole-path replacement.

When an input crosses a service or command boundary, declare a local input type
containing the writable fields instead of reusing `SomeDocument`:

```ts
type CreateSomeModelInput = {
  someString: string;
  email?: string;
  orders?: mongoose.Types.ObjectId[];
};

const rows: CreateSomeModelInput[] = getRows();
await SomeModelHandle.insertMany(rows);
```

Population and aggregation are also query-local runtime choices. Use
`.populate<T>()` for the populated result and supply an explicit aggregation
result type:

```ts
const totals = await SomeModelHandle.aggregate<{
  _id: string;
  count: number;
}>([
  { $match: { email: { $ne: null } } },
  { $group: { _id: "$email", count: { $sum: 1 } } },
]);
```

Keep these contracts beside the operation that creates the shape. The framework
cannot infer an aggregation projection or a runtime-selected population state
from the static schema alone.

## Looking up models

Run type generation before type-checking. The generated `AppModelTypes` map
contains every resolved application model, including application overrides of
framework models. `getModel()` therefore accepts application models as well as
the built-in models—it is not limited to the framework's model names.

```ts
const User = this.app.getModel("User");
const user = await User.findOne({ email: "user@email.com" });

// A union of valid generated names produces the corresponding model union.
const modelName: "Article" | "Comment" = chooseModelName();
const Content = this.app.getModel(modelName);

// @ts-expect-error — no model with this generated name
this.app.getModel("Artcle");
```

Use the two lookup methods according to where the name comes from:

| Name source | Method | Return type | Missing model |
|---|---|---|---|
| Generated literal or union | `getModel(name)` | Exact model or model union | Rejected by TypeScript |
| Runtime `string` | `getModelOrThrow(name)` | Broad Mongoose model, never `false` | Throws an `Error` |

For example, a command may receive a model name only at runtime:

```ts
const modelName = process.env.MODEL_NAME;
if (!modelName) throw new Error("MODEL_NAME is required");

const Model = this.app.getModelOrThrow(modelName);
await Model.collection.dropIndexes();
```

`getModelOrThrow()` also has access to the generated map. Passing a known
literal or a valid-name union therefore keeps the same precise return type as
`getModel()`; only an unrestricted `string` widens to the common model type.

An unknown name, or a lookup before `Server.init()` completes, is logged and
then throws. If a model name comes directly from an HTTP request, validate it
against an allowed-name set first so the application can return an appropriate
client error rather than exposing an internal lookup failure.

## Configuration

The main configuration variable is the `MONGO_DSN` environment variable, which the model uses to connect to the database.

## Built-in Models

The framework comes with a few built-in models.

### User

It is part of the authorization system and handles user storage, password hashing, and provides basic functions for token generation and user retrieval.

If you want to create your own user implementation, you should override or disable this one.

The authentication controller depends on this model.

#### API

```js
const UserModel = this.app.getModel("User");
const user = await UserModel.getUserByEmailAndPassword("email", "password");
// Stores a new 30-day session (its hash only) and returns { token, valid }.
// Since 5.5.1, if the password changed after `user` was loaded, it rejects with
// the same 400 `BadRequestError` as a wrong password: a custom login needs no catch.
const userToken = await user.generateToken();
const userPublic = await user.getPublic();
// `hashPassword` is a standalone helper, not a model static:
// import { hashPassword } from "@adaptivestone/framework/helpers/crypto.js";
const hashedPassword = await hashPassword("password");
const sameUser = await UserModel.getUserByToken(userToken.token);
const sameUserAgain = await UserModel.getUserByEmail(user.email);
// The token generators live in `userHelpers`, not on the model:
// import { userHelpers } from "@adaptivestone/framework/models/User.js";
const recoveryToken = await userHelpers.generateUserPasswordRecoveryToken(user);
const sameUserAgain2 = await UserModel.getUserByPasswordRecoveryToken(
  recoveryToken
);
// Both token lookups consume the token and save. Pass `{ save: false }` to
// only remove it from the returned document and persist it with your own
// changes in one `save()` (what the built-in reset and verify routes do).
const isSuccess = await user.sendPasswordRecoveryEmail(i18n);
const verificationToken = await userHelpers.generateUserVerificationToken(user);
const sameUserAgain3 = await UserModel.getUserByVerificationToken(
  verificationToken
);
const isSuccess2 = await user.sendVerificationEmail(i18n);
```

#### Customizing the User model

To replace the framework's `User`, drop your own `User.ts` into your project's
`models/` folder. The [inheritance process](03-files-inheritance.md) makes it win
over the framework's, and `getModel("User")` / `req.appInfo.user` are typed
against **your** model automatically (run `generatetypes` after adding it).

There are two ways to customize it.

**Add fields** — extend the framework's `User` and spread its schema:

```ts title="/src/models/User.ts"
import FrameworkUser from "@adaptivestone/framework/models/User.js";

export default class User extends FrameworkUser {
  static get modelSchema() {
    return {
      ...FrameworkUser.modelSchema,
      company: { type: String },
    } as const;
  }
}
```

The inherited auth statics and instance methods (`getUserByEmailAndPassword`,
`generateToken`, `getPublic`, …) keep working on your model with no casts.

**Reshape fields** — when you need to change a field's _shape_ (for example an
i18n `name`, or a singular `role` instead of `roles[]`), TypeScript can't express
a type _replacement_ through `extends` (the static-getter override is checked
covariantly, so it fails with `TS2417`). Compose instead: extend `BaseModel` and
reuse the framework's auth logic by spreading it in.

```ts title="/src/models/User.ts"
import { BaseModel } from "@adaptivestone/framework/modules/BaseModel.js";
import FrameworkUser from "@adaptivestone/framework/models/User.js";
import type { Schema } from "mongoose";

export default class User extends BaseModel {
  static get modelSchema() {
    return {
      name: { native: { type: String }, machine: { type: String } },
      email: { type: String },
      password: String,
      sessionTokens: [{ token: String, valid: Date }],
      role: { type: String },
      // …the rest of your schema
    } as const;
  }

  static get modelStatics() {
    return { ...FrameworkUser.modelStatics } as const;
  }

  static get modelInstanceMethods() {
    return { ...FrameworkUser.modelInstanceMethods } as const;
  }

  static initHooks(schema: Schema) {
    FrameworkUser.initHooks(schema); // keeps the password-hashing pre-save hook
  }
}
```

The shipped auth helpers are typed against small structural contracts
(`UserAuthDoc` / `UserAuthInstance` / `UserAuthModel`), so they stay callable on
your reshaped model without casts.

:::note

The auth statics (`getUserByEmailAndPassword`, `getUserByToken`, …) only read a
few fields — `email`, `password`, and the token arrays. Any model that keeps
those reuses them as-is. `getPublic` returns the framework's public shape, so
override it if your model reshapes the fields it reads (such as `name`).

:::

### Migration

The migration model is a helper for the migration subsystem. It stores the names of migrated files to ensure that each migration is only executed once.

Please refer to the `CLI/migrations` section for more details.

You should probably not use this model directly.

### Sequence

The Sequence model allows you to generate sequences by name. This is a cross-server-safe method for generating sequences in a distributed environment.

```javascript
const SequenceModel = this.app.getModel("Sequence");
// Will be 1.
const someTypeSequence = await SequenceModel.getSequence("someType");
// Will be 2.
const someTypeSequence2 = await SequenceModel.getSequence("someType");
// Will be 1, as the type is different.
const someAnotherTypeSequence = await SequenceModel.getSequence(
  "someAnotherType"
);
```

### Lock

The Lock model provides the ability to lock resources in a distributed environment.

This can be used for external requests, system actions, etc.

Imagine you have a high volume of traffic requesting data from an external system. You also have a cache for this data, but you must initially query the internal API to retrieve it. To prevent overwhelming the API, you want to ensure that you only request the data once and that other simultaneous requests wait for the result instead of making redundant calls. This is where the Lock model can help.

```javascript

const LockModel = this.app.getModel("Lock");

  /**
   * Acquires a lock based on the lock name.
   * @param {string} name
   * @param {number} [ttlSeconds=30]
   * @returns {Promise<boolean>}
   */
  async acquireLock(name, ttlSeconds = 30)

  /**
   * Releases a lock based on the lock name.
   * @param {string} name
   * @returns {Promise<boolean>}
   */
  async releaseLock(name)

  /**
   * Waits for a lock based on the lock name.
   * @param {string} name
   * @returns {Promise}
   */
  async waitForUnlock(name)

  /**
   * Gets the lock's remaining time based on the lock name.
   * @param {string} name
   * @returns {Promise<{ttl: number}>}
   */
  async getLockData(name)


  /**
   * Gets the locks' remaining time based on the lock names.
   * @param {string[]} names
   * @returns {Promise<{name: string, ttl: number}[]>}
   */
  static async getLocksData(names)

```

Example of usage:

```javascript

async someHTTPRequestWithExpensiveExternalAPI(req, res) {
  // We have some external requests, which can be simultaneous requests from different users.
  const LockModel = this.app.getModel("Lock");
  // Let's say it's AI processing of a video, for example.
  const { videoId } = req.appInfo.request;

  // Check if we already have it.
  const VideoAIModel = this.app.getModel("VideoAIModel");
  const videoAI = await VideoAIModel.findOne({ videoId });
  if (videoAI) {
    return res.json(videoAI.getPublic());
  }

  const lockName = `video-ai-processing-${videoId}`;

  // We don't have that video, so let's send it for processing using a lock.
  const isLockAcquired = await LockModel.acquireLock(lockName);
  if (isLockAcquired) {
    const result = await videoAIService.processVideo(videoId);
    const videoModel = await VideoAIModel.create({ videoId, result });
    // Release the lock.
    await LockModel.releaseLock(lockName);
    // Return the result.
    return res.json(videoModel.getPublic());
  }

  // We don't have a lock, so let's wait for one.
  await LockModel.waitForUnlock(lockName);
  // It looks like the external process is finished, so let's check for the result.
  const videoAI2 = await VideoAIModel.findOne({ videoId });
  if (videoAI2) {
    return res.json(videoAI.getPublic());
  }

  // If there's no result, we'll return an error.
  return res.status(500).json({ error: "Something went wrong" });
}
```

### KeyValue

A minimal persistent key/value store backed by MongoDB. Think of it as a tiny, shared "settings drawer" for your app: a place to keep small pieces of state that should survive restarts and be readable by every process — a lightweight cache, runtime configuration, feature flags, the cursor of a background job, and so on.

The model is intentionally schema-only — it adds no custom methods. The key is the document `_id` (a string), and the value is a `Mixed` field, so it can hold anything Mongoose can serialise (string, number, boolean, array, or nested object). You interact with it through the standard Mongoose API that every model already exposes.

```ts
static get modelSchema() {
  return {
    _id: { type: String, required: true },
    value: { type: Schema.Types.Mixed, required: true },
  } as const;
}
```

#### Usage

```js
const KeyValue = this.app.getModel("KeyValue");

// Set (create or overwrite). `upsert: true` makes it idempotent.
await KeyValue.findByIdAndUpdate(
  "config:theme",
  { value: "dark" },
  { upsert: true },
);

// Get. Returns the document or `null` when the key is missing.
const doc = await KeyValue.findById("config:theme");
const theme = doc?.value ?? "light"; // fall back to a default

// Any serialisable value works.
await KeyValue.findByIdAndUpdate(
  "config:features",
  { value: { newDashboard: true, limits: [10, 50, 100] } },
  { upsert: true },
);

// Read many keys at once.
const docs = await KeyValue.find({ _id: { $in: ["config:theme", "config:features"] } });
const map = new Map(docs.map((d) => [d._id, d.value]));

// Delete.
await KeyValue.deleteOne({ _id: "config:theme" });
```

:::tip

Use a `namespace:key` convention for the `_id` (for example `config:theme`, `cache:user-42`, `flag:beta-signup`). It keeps keys readable and makes prefix queries with a regular expression easy:

```js
const allConfig = await KeyValue.find({ _id: /^config:/ });
```

:::

#### Caching pattern

Because every process reads the same collection, `KeyValue` is a convenient cross-server cache for values that are expensive to compute but cheap to store.

```js
async function getExchangeRates(app) {
  const KeyValue = app.getModel("KeyValue");
  const cached = await KeyValue.findById("cache:exchange-rates");
  if (cached) {
    return cached.value;
  }

  const rates = await fetchExpensiveRatesFromExternalApi();
  await KeyValue.findByIdAndUpdate(
    "cache:exchange-rates",
    { value: rates },
    { upsert: true },
  );
  return rates;
}
```

Pair it with the [`Lock`](#lock) model when several requests might try to populate the same cache key at once, so the expensive work runs only once.

:::note

`KeyValue` is **persistent storage**, not an expiring cache — entries live until you delete them. There is no built-in time-to-live. If you need automatic expiration, add an `expireAt` date field and a TTL index in `initHooks`, the same way the `Lock` model does:

```ts
static initHooks(schema: Schema) {
  schema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });
}
```

For request-scoped or in-memory caching, see the [Cache](11-cache.md) section instead.

:::

#### Concurrency

`value` is a `Mixed` field, so it is replaced as a whole — concurrent writers are last-write-wins. Do not read a value, mutate it in your code, and write it back if multiple processes update the same key; you may lose updates. For counters or fields that must change atomically, use MongoDB update operators directly (`$inc`, `$set` on a sub-path) or reach for the [`Sequence`](#sequence) model.


---


# Document 6: 05-modelsOld

<!-- Source: 05-modelsOld.md -->

# Models (OLD)

:::warning

This documentation is for old model definitions. Please do not use this type of models at all. Use current model versions.
:::

Framework based on [mongoose](https://mongoosejs.com/) library and provide direct access to mongoose.

It uses [ES6 class variant](https://mongoosejs.com/docs/guide.html#es6-classes) of mongoose to init. Also you can access framework

Model take care about database connection

:::note

Models files part of [framework inheritance process ](03-files-inheritance.md).

:::

## Access mongoose instance

Inside the class mongoose is available as

```js
this.mongooseModel;
```

## Basic model

```js
import AbstractModel from "@adaptivestone/framework/modules/AbstractModel.js";

class SomeModel extends AbstractModel {
  constructor(app) {
    super(app);
    // you can put some init stuff
  }

  initHooks() {
    super.initHooks();
    // place to init plugins, indexes, etc.
    // As it happens after loaded class into mongoos, but before mongoose inited class
    // this.mongooseSchema.plugin(PLUGIN_NAME);
  }

  // here mongoose scheme go
  // this is a full mongoose schema
  // Please refer to mongoose documentation https://mongoosejs.com/docs/guide.html
  get modelSchema() {
    return {
      someString: { type: String, required: true },
      firstName: String,
      lastName: String,
      email: String,
    };
  }

  // here mongoose scheme options go
  // this is a full mongoose schema
  // Please refer to mongoose documentation https://mongoosejs.com/docs/guide.html#options
  get modelSchemaOptions() {
    return {
      read: "primary",
    };
  }

  // Static method will be part of the mongoose class
  // this.app.getModel('SomeModel').someStaticMethod()
  static async someStaticMethod() {
    const somedata = await this
      .findByIdAndUpdate
      //.....
      ();
    const { app } = this.getSuper();
    return somedata;
  }

  // any methods will be part on instance method
  // await this.app.getModel('SomeModel').findById(124).someInstanceMethod()
  async someInstanceMethod() {
    // you can access app into the instance method
    const { app } = this.getSuper();

    // inside of instance method you can access model data
    this.someString;
  }

  // any getters will became a mongoose virtual
  // const SomeModels = this.app.getModel("SomeModel").
  // const someModelInstance = await SomeModel().create({ email: 'test@gmail.com' });;
  // `domain` is now a property on SomeModels documents.
  // someModelInstance.domain; // 'gmail.com'
  get domain() {
    return this.email.slice(this.email.indexOf("@") + 1);
  }

  // setters also be an virtual
  // const SomeModels = this.app.getModel("SomeModel").
  // const someModelInstance = new SomeModel();
  // Vanilla JavaScript assignment triggers the setter
  // someModelInstance.fullName = 'Jean-Luc Picard';
  set fullName(v) {
    // `v` is the value being set, so use the value to set
    // `firstName` and `lastName`.
    const firstName = v.substring(0, v.indexOf(" "));
    const lastName = v.substring(v.indexOf(" ") + 1);
    this.set({ firstName, lastName });
  }
}

export default SomeModel;
```

:::tip

If you have some relations ("ref") on a mongoose model that you should care to load schema. As mongoose can only build relationships with schemas in memory. Google place to do that - inside constructor. Be aware on loop linking models

```js
constructor(app){
	super(app);
	this.app.getModel(“ReferenceModelName”);
}
```

:::

:::warning

Models united onse per process and then united instances cached. Do NOT expect constructor or init hook calls on every model loading

:::

:::tip

Please do not name the model in plural form.

**Bad** - Coin**s**

**Good** - Coin

:::

## API

```js
getModel(modelName: string): MongooseModel<any>;
```

Example:

```js
const UserModel = this.app.getModel("User");
const userInstance = await UserModel.findOne({ email: "user@email.com" });
```

## Configuration

Main configuration variable "MONGO_DSN" environment variable. Based on it model will made connection to the database

## Built-in models

Framework came with few built-in models.

### User

It's a part of the authorization system. It takes care of storing users, hash passwords and provides some basic functions for token generation and getting users.

If you want to have your own user implementation you should overwrite it or disable.

Auth controller depends on this model

#### API

```js
const UserModel = this.app.getModel("User");
const user = await UserModel.getUserByEmailAndPassword("email","password");
const userToken = await user.generateToken(); // generate and store token in the database
const userPublic = await user.getPublic();
const hashedPassword = await UserModel.hashPassword("password");
const sameUser = await UserModel.getUserByToken(userToken);
const sameUserAgain = await UserModel.getUserByEmail(user.email);
const recoveryToken = await UserModel.generateUserPasswordRecoveryToken(user);
const sameUSerAgain2 = await UserModel.getUserByPasswordRecoveryToken(recoveryToken);
const isSuccess = await user.sendPasswordRecoveryEmail(i18n);
const verificationToken = await UserModel.generateUserVerificationToken(user);
const sameUserAgain3 = await UserModel.getUserByVerificationToken(verificationToken);
const isSuccess2 = await user.sendVerificationEmail(i18n);
```

### Migration

Migration model it's helper for migration subsystems. It stores migrated files to make sure that migrated executed once

Please refer to CLI/migrations for more details

You probably should not use this model directly

### Sequence

Sequence allows you to generate sequences by name. This is cross server safe method to generate sequences in distributed environment

```javascript
const SequenceModel = this.app.getModel("Sequence");
// will be 1
const someTypeSequence = await SequenceModel.getSequence("someType");
// will be 2
const someTypeSequence2 = await SequenceModel.getSequence("someType");
// will be 1 as type is another
const someAnotherTypeSequence = await SequenceModel.getSequence(
  "someAnotherType"
);
```

### Lock

Lock model is designed to provide ability to lock some resources in distributed environment.

This can be external requests, some actions in the system, etc.

Imagine that you have a log of traffic that asks external system for some data. You have cache of this data as weel, but initially you shaul asks internal api to get this data. And you want to make sure that you asking this api for that data only one time and other same time requests will wait for the result instead of asking api. This is where Lock model can help you.

```javascript

const LockModel = this.app.getModel("Lock");

  /**
   * acquire lock based on lock name
   * @param {string} name
   * @param {number} [ttlSeconds=30]
   * @returns {Promise<boolean>}
   */
  async acquireLock(name, ttlSeconds = 30)

  /**
   * release lock based on lock name
   * @param {string} name
   * @returns {Promise<boolean>}
   */
  async releaseLock(name)

  /**
   * wait lock based on lock name
   * @param {string} name
   * @returns {Promise}
   */
  async waitForUnlock(name)

  /**
   * get lock remaining time based on lock name
   * @param {string} name
   * @returns {Promise<{ttl: number}>}
   */
  async getLockData(name)


  /**
   * get lock remaining time based on lock name
   * @param {string[]} names
   * @returns {Promise<{name: string, ttl: number}[]>}
   */
  static async getLocksData(names)

```

Example of usage:

```javascript

async someHTTPRequestWithExpensiveExternalAPI(req,res){
  // we have some external request (this can be same time request from different users)
  const LockModel = this.app.getModel("Lock");
  // lets say its a AI processing of video (for example)
  const {videoId} = req.appInfo.request;

  // check if we already have it
  const VideoAIModel = this.app.getModel("VideoAIModel");
  const videoAI = await VideoAIModel.findOne({videoId});
  if(videoAI){
    return res.json(videoAI.getPublic());
  }

  const lockName = `video-ai-processing-${videoId}`;

  // we have no that video, lets send it otp rocessing with lock
  const isLockAcquired = await LockModel.acquireLock(lockName);
  if(isLockAcquired){
    const result = await videoAIService.processVideo(videoId);
    const videoModel = await VideoAIModel.create({videoId, result});
    // release lock
    await LockModel.releaseLock(lockName);
    // return result
    return res.json(videoModel.getPublic());
  }

  // we have no lock, lets wait for it
  await LockModel.waitForUnlock(lockName);
  // lookslikeexternal process is done, lets check if we have result
  const videoAI2 = await VideoAIModel.findOne({videoId});
  if(videoAI2){
    return res.json(videoAI.getPublic());
  }

  // we have no result, lets return error
  return res.status(500).json({error: "something went wrong"});
}

```


---


# Document 7: 06-Controllers > 01-intro

<!-- Source: 06-Controllers/01-intro.md -->

# Controllers

Controllers are a crucial component of the framework. The framework uses [Express.js](https://expressjs.com/) for the HTTP lifecycle (listening, body parsing, response API, the third-party middleware ecosystem) and a tree-based `RouteRegistry` for path matching, parameter extraction, method dispatch, and middleware ordering. Controllers contribute subtrees to the global registry — auto-loaded from the controllers folder, mounted via a single Express middleware.

:::note

Controller files are part of the [framework inheritance process](03-files-inheritance.md).

:::

The framework provides built-in error handling, automatic controller loading (including from subfolders), and request validation and casting.

:::note

Clustering is opt-in. Use the exported `runCluster()` helper when a standalone
deployment should use multiple CPU cores; when systemd, PM2, Docker, or an
orchestrator already manages replicas, run one framework process per replica.
Workers do not share memory, so cross-worker sessions, WebSocket fan-out, and
similar state require external coordination. See [Deployment](../13-deploy.md).
:::

## Controller Structure

```js
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";

class ControllerName extends AbstractController {
  get routes() {
    // Return routes info.
    // NECESSARY part.
  }

  getHttpPath() {
    // URL prefix for this controller. Default: `/{constructor-name-lowercase}`.
    // Override in a subclass to customize (e.g., `Home` → `/`).
  }

  static get middleware() {
    return new Map();
    // Path-/method-scoped middlewares for routes in THIS controller.
  }
}
export default ControllerName;
```

:::tip

Only the `routes` getter is required; other parts of the controller can be omitted if not needed.
:::

:::warning

Controllers should extend the "AbstractController" module.
:::

## Name Convention and Loading

The framework loads every file in `src/controllers/` except `*.test.js` and
`*.test.ts`. The default mount path comes from the controller's folder prefix
plus its **lowercased class name**. The filename does not determine the URL:
`src/controllers/admin/UserSettings.ts` exporting `class UserSettings`
mounts at `/admin/usersettings`.

Filename still matters for framework-internal controller overrides, so name the
file after the class. Never export the same controller class from two files:
the loader initializes both files and mounts the controller twice. Override
`getHttpPath()` when the default class-name path is not the URL you want.

### Organizational route groups

A controller subfolder normally contributes a URL segment. Wrap a folder name
in parentheses when it should organize source files without changing routes:

```text
src/controllers/(group)/Reports.ts
  → /reports

src/controllers/(group)/admin/Settings.ts
  → /admin/settings
```

Only fully parenthesized path segments are omitted. Ordinary folders still
contribute their lowercased names, and multi-word controller class names are
still lowercased without implicit kebab-casing. Generated `*.routes.gen.ts`
files remain beside their controllers inside the group folder.

Route groups are also ignored when matching a project controller against a
framework-internal controller override. For example, moving an `Auth.ts`
override into `(group)/Auth.ts` still replaces the framework `Auth`
controller; the group changes source organization, not override identity.

Route groups do not create namespaces. If two grouped controllers resolve to
the same HTTP method and path, startup fails with the normal duplicate-route
error; rename or explicitly remount one of them.

### Explicit registration

In addition to file-based auto-loading, you can register a controller programmatically via `app.controllerManager.registerController(ControllerClass, prefix?)`. This is useful for:

- **Test fixtures** — register a controller only for a specific test (see the [Testing](../09-testsing.md) chapter).
- **Late registration** — controllers added after `Server.startServer()` boots, via the `callbackBefore404` hook so routes mount before the 404 handler.
- **Conditional controllers** — only register based on config, feature flags, or runtime detection.

```js
import MyController from "./controllers/MyController.js";

await server.startServer(async () => {
  // Runs after framework controllers init, before the 404 handler.
  // Routes mount on `/my/mycontroller/*` (prefix + lowercase class name).
  server.app.controllerManager?.registerController(MyController, "my");
});
```

Auto-loading internally uses the same `registerController` entry point — both paths produce identical instances.

For the example above:

```js
class ControllerName extends AbstractController {
```

The route will be `http://localhost:3300/controllername` because the class is
named `ControllerName`; renaming only its file would not change this URL.

Then, any method from the router will be accessible via the URL.

If you want to define a custom path, provide your own implementation of
`getHttpPath()`:

```js
  getHttpPath() {
    return "/super-duper-mega-special-route";
  }
```

By default, `getHttpPath()` combines the folder prefix with the lowercased
class name. It does not kebab-case multi-word names: `UserSettings` becomes
`/usersettings`, so use an override when `/user-settings` is required.

### Project boot hook (`bootHttp`)

For app-wide HTTP wiring that doesn't belong to any single controller — webhooks, OAuth callbacks, or boot-time setup — pass a **`bootHttp`** function to the `Server` constructor. The framework calls it with the live `app` during `startServer`, after controllers are registered but before the adapter mounts, so anything it adds is in place from the first request. Since 5.4.2 the server starts accepting connections only once everything is mounted, and `startServer()` resolves after the port is bound.

Define it inline — `app` is inferred, no annotation needed:

```ts title="src/index.ts"
import Server from "@adaptivestone/framework/server.js";

const server = new Server({
  folders: {
    /* … */
  },
  bootHttp: async (app) => {
    // `httpServer` is always set by the time bootHttp runs, but it's typed
    // nullable (CLI and worker processes never have one). Narrow it by
    // throwing, not with `?.`: an optional chain on a null would skip your
    // wiring silently and the app would serve without it.
    if (!app.httpServer) {
      throw new Error("bootHttp ran without a live httpServer");
    }

    // An ad-hoc route that doesn't fit the controller convention:
    app.httpServer.routeRegistry.registerRoute("POST", "/webhooks/stripe", {
      handler: stripeWebhookHandler,
    });

    // Or app-wide Express middleware (runs before the router):
    // app.httpServer.express.use(myGlobalMiddleware);
  },
});
await server.startServer();
```

There's no required file or folder for it — it's just a function. If it grows, extract it to its own module and type it with `BootHttpHook`:

```ts title="src/bootHttp.ts"
import type { BootHttpHook } from "@adaptivestone/framework/server.js";

const bootHttp: BootHttpHook = async (app) => {
  /* … */
};

export default bootHttp;
```

It's wired **explicitly**, not auto-discovered from a folder: the framework finds everything else through configured folders, and those are all spoken for — `config/` merges its files as config, `controllers/` auto-loads its files as controllers — so there's no conflict-free folder to scan. `bootHttp` is **HTTP-specific** by design: it needs `app.httpServer`, which only exists once the HTTP server boots (CLI and worker processes never run it). Unlike the `callbackBefore404` hook (which you pass to `startServer` and which runs _after_ the adapter mounts), `bootHttp` runs _before_ the mount.

The framework builds its own `Server` for tests, so pass the same hook to [`configureTestServer`](../09-testsing.md#production-http-wiring-boothttp) in your test setup — otherwise your suites run against a server that never got this wiring.

## Request Flow

![RequestFlow](/img/requestFlow.jpg)

## View

:::warning

Built-in view rendering was **removed in version 5**. The framework no longer ships a `views/` folder or a default template engine — it is API-first (returns JSON).

:::

If you need server-rendered HTML, the underlying Express 5 instance is available on `app.httpServer.express` (once the HTTP server has booted), so you can register a template engine yourself (see the [Express template-engine guide](https://expressjs.com/en/guide/using-template-engines.html)). For most applications, return JSON and render on the client.

## JSON

JSON is the most common data format for modern web applications, but its flexibility can sometimes lead to confusion.

We provide [basic documentation](https://andrey-systerr.notion.site/API-JSON-41f2032055ae4bddae5d033dc28eb1d3) on how we recommend working with JSON, and the framework is designed to follow these guidelines.

## Configuration

The configuration file is located at `config/http.js`.

Please take a moment to review it.

The most notable options are:

```js
port; // Port that the server will use. By default, process.env.HTTP_PORT or port 3300.
hostname; // IP to bind to. By default, process.env.HTTP_HOST or '0.0.0.0' (any). Could be dangerous.
corsDomains; // CORS-allowed domains.
corsExposedHeaders; // Response headers browser code may read. By default ['Retry-After'].
```


---


# Document 8: 06-Controllers > 02-routes

<!-- Source: 06-Controllers/02-routes.md -->

# Routes

Routes are relative to the controller route. You SHOULD NOT use the full route here.

Route objects have multiple levels.

## Route First Level (Method Level)

On the first level, only the ‘method’ (post, put, delete, etc.) exists. Only requests with these methods will go deeper into the real routes.

```js
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";

class ControllerName extends AbstractController {
  get routes() {
    return {
      post: {
        // post routes
      },
      get: {
        // get routes
      },
      put: {
        // put routes
      },
      // etc.
    };
  }
}
export default ControllerName;
```

## Route Second Level (Path Level)

Inside the methods (second level), we have a path. The framework's tree-based router supports a small, opinionated set of patterns:

```js
"/fullpath"                          // literal path
"/fullpath/:paramOne/:paramTwo"      // named params → req.params.paramOne, paramTwo
"/api/{*rest}"                       // catch-all splat → req.params.rest = "/v1/users/42"
```

| Syntax | Matches | Captures |
|---|---|---|
| `/literal` | exact segment | nothing |
| `:name` | exactly one segment | `req.params.name` |
| `{*name}` | zero or more segments to end of path | `req.params.name` (joined with `/`) |

**Specificity** (when patterns overlap): static segments win, then `:param`, then `{*splat}`. So `/users/me` registered alongside `/users/:id` matches the literal first. Precedence is per method: with `GET /users/me` and `DELETE /users/:id`, `DELETE /users/me` reaches `/users/:id` (`id = 'me'`). A `405` is answered only when no matching route has the method, and its `Allow` header lists the methods of all of them.

**URL decoding** is per-segment (Spring `PathPatternParser` model). `%2F` inside a `:param` value stays as `/`; the matcher does not split on it. For `{*splat}` captures, segments are decoded individually then re-joined — encoded-slash distinction is lost (documented trade-off; use raw-body mode for the rare encoded-slash case).

**Defaults**: case-insensitive, lenient trailing slash. Both flip in v6.

:::note

The order of routes matters when patterns overlap at the same specificity tier (e.g., two `:param` siblings). The first matched route is executed.
:::

Example:

```js
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";

class ControllerName extends AbstractController {
  get routes() {
    return {
      post: {
        "/someUrl": {
          handler: this.postSomeUrl,
          request: yup.object().shape({
            count: yup.number().max(100).required(),
          }),
        },
      },
    };
  }
}
export default ControllerName;
```

## Route Third Level (Route Object Level)

On the third level, we have a "route object," a special object that will describe our route.

```js
{
  handler: this.postSomeUrl, // required
  request: yup.object().shape({ // optional
    count: yup.number().max(100).required(),
  }),
  query: yup.object().shape({ // optional
    page: yup.number().required(),
  }),
  params: yup.object().shape({ // optional
    id: yup.string().required(),
  }),
  middleware: [RateLimiter], // optional
  description: "Create a sample" // optional — a plain string; becomes the OpenAPI operation summary
}

```

Here:

```js
Handler; // Some async function (most likely in this controller file) that will do all the work.
Request; // A special interface that will do validation of body parameters for you.
Query; // A special interface that will do validation of query parameters for you.
Params; // A special interface that will do validation of path parameters (:id) for you.
Middleware; // An array of middlewares specially for the current route.
Description; // A description of this route — becomes the OpenAPI operation summary.
```

The route `description` together with the `request:` / `query:` / `params:` schemas and the middleware chain are what the framework reads to generate an [OpenAPI 3.1 document](../17-openapi.md).

## Request

Request does validation and casting of an upcoming `req.body`.

As we want to use already well-defined solutions, we believe that [yup](https://github.com/jquense/yup) is a great example of how a schema should be validated.

But you still have the ability to provide your own validation based on an interface.

:::warning
Request works on a body level.
:::

Request contains all fields from `req.body` and passes them into validation.

:::warning
Please note that GET methods have no BODY.
:::

Parameters after validation are available as `req.appInfo.request`.

:::warning
Do not use `req.body` directly. Always use parameters via `req.appInfo.request`.

:::

## Query

Query does validation and casting of an upcoming `req.query`.

The Yup schema is described similarly to the request.

:::warning
Query works on a query level.
:::

Query contains all fields from `req.query` and passes them into validation.

Parameters after validation are available as `req.appInfo.query`.

:::warning
Do not use `req.query` directly. Always use parameters via `req.appInfo.query`.

:::

## Params

Path params (`:id`, `{*rest}`) arrive as raw strings from the matcher. Declare a `params:` schema to validate and coerce them the same way `request:` handles the body:

```js
get: {
  "/person/:id": {
    handler: this.getPerson,
    params: yup.object().shape({
      id: yup.string().matches(/^[0-9a-fA-F]{24}$/, "must be a valid id"),
    }),
  },
}
```

A failure is a **400** with the framework's usual error shape, returned before your handler runs:

```json
{ "message": "Validation failed", "errors": { "id": ["must be a valid id"] } }
```

The validated, coerced values are available as `req.appInfo.params`. Because coercion comes from the validator, a numeric or date param arrives already converted:

```js
"/invoice/:year": {
  handler: this.getInvoice,
  params: yup.object().shape({ year: yup.number().min(2000) }),
}

// in the handler:
req.appInfo.params.year; // 2026    (number)
req.params.year;         // "2026"  (string — raw, untouched)
```

:::warning
Use `req.appInfo.params` for validated values. Raw `req.params` is deliberately left alone so the Express contract (always strings) still holds — which also means it is **not** validated. Passing a raw param straight to Mongoose is the classic way to turn a client typo into a server error.
:::

:::note
`params:` is route-level only — unlike `request:` and `query:`, middleware do not contribute param schemas. It does feed the [OpenAPI document](../17-openapi.md): a declared `params:` schema types the path parameters that would otherwise be documented as plain `string`s. Path params are always emitted as `required: true` — they are part of the URL by construction, whatever the schema says about optionality.

If a route declares no `params:` schema and an unvalidated param reaches Mongoose anyway, the framework still catches the resulting `CastError` and answers **400** rather than 500 — see [Error handling → the Mongoose cast safety net](04-error-handling.md#built-in-the-mongoose-cast-safety-net). That is a floor, not a substitute: a `params:` schema rejects bad input earlier, with wording and coercion you control.
:::

## Validation

The framework dispatches validation through [Standard Schema](https://standardschema.dev/) — a vendor-neutral interface. Any conforming validator works as a route's `request:` or `query:` schema with no glue code:

| Validator | Standard Schema support |
|---|---|
| [Yup](https://github.com/jquense/yup) | ≥1.7 |
| [Zod](https://zod.dev/) | ≥3.24 |
| [Valibot](https://valibot.dev/) | all current versions |
| [ArkType](https://arktype.io/) | all current versions |

Yup is shown in the examples below since the framework historically taught it, but the same shapes are accepted from any Standard Schema-conforming library.

:::note
`request:` validates the request **body**, `query:` the **query string**, and `params:` the **path params** (`:id`) — see [Params](#params) below. All three accept any Standard Schema validator and all three report failures the same way.
:::

:::note
The framework no longer bundles a validator. `yup` is an **optional peer dependency** — install it only if you use yup schemas (or the deprecated `YupFile`). For dependency-free validation of simple shapes, use [`defineSchema`](#zero-dependency-schemas-defineschema) below.
:::

### Yup example

```js
request: yup.object().shape({
  count: yup.number().max(100).required("error text"),
});
query: yup.object().shape({
  page: yup.number(),
});
```

A more complete example:

```js
request: yup.object().shape({
  name: yup.string().required("validation.name"), // You can use i18n keys here.
  email: yup.string().email().required("Email required field"), // Or just text.
  message: yup
    .string()
    .required("Message required field")
    .min(30, "minimum 30 chars"), // Additional validators for different types exist.
  pin: yup.number().integer().min(1000).max(9999).required("pin.pinProvided"),
  status: yup
    .string()
    .required("Status required field")
    .oneOf(["WAITING", "CANCELED"]), // One of.
  transaction: yup
    .object() // Deep-level object.
    .shape({
      to: yup.string().required(),
      amount: yup.number().required(),
      coinName: yup.string().oneOf(["btc", "etc"]).default("etc"), // Default.
    })
    .required(),
});
```

For Yup schemas, the framework automatically strips unknown fields (security-relevant when handlers spread `req.appInfo.request` into model creates). You don't need `.noUnknown()` — the framework calls `cast(data, { stripUnknown: true })` for you.

### Zod example

```js
import { z } from "zod";

request: z.object({
  count: z.number().max(100),
  message: z.string().min(30, "minimum 30 chars"),
});
query: z.object({
  page: z.number().optional(),
});
```

Zod (and Valibot, ArkType) strip unknown fields by default — no extra configuration needed. To allow unknown fields explicitly, use the library's pass-through API (Zod's `.passthrough()`, Valibot's `looseObject`, ArkType's `'+': 'ignore'`).

### Zero-dependency schemas (`defineSchema`)

When you want a small schema without pulling in a validator library, use `defineSchema` — a one-function adapter that wraps a plain validate callback into a Standard Schema object:

```ts
import { defineSchema } from "@adaptivestone/framework/services/validate/defineSchema.js";

request: defineSchema<{ email: string }>(
  (value) => {
    const v = (value ?? {}) as Record<string, unknown>;
    if (typeof v.email !== "string" || !v.email.includes("@")) {
      return { issues: [{ message: "validation.email", path: ["email"] }] };
    }
    // Return only known keys — unknown input is stripped by construction.
    return { value: { email: v.email } };
  },
  {
    // Optional: lets OpenAPI document this imperative validator.
    jsonSchema: {
      type: "object",
      properties: { email: { type: "string", format: "email" } },
      required: ["email"],
    },
  },
);
```

- The `Output` generic (`{ email: string }`) is what the codegen reads for the typed handler signature (`req.appInfo.request`) — see below. You declare it; the runtime checks live in the callback.
- Return `{ value }` on success (only the keys you copy survive — this is your strip-unknown), or `{ issues }` on failure. Each issue's `message` is an i18n key (or literal text); the framework auto-translates it like any other validator.
- The optional `jsonSchema` value (or function returning one) describes the wire shape to OpenAPI. It does not change runtime validation. Omit it when the shape should remain undocumented.
- This is the mechanism the built-in `Auth` controller uses, so the framework itself ships validator-free.

`defineSchema` is intentionally minimal — there are no `string()`/`object()` combinators. If you find yourself hand-writing many or deeply nested schemas, reach for a real validator library (Zod, etc.) instead.

### Typed handler signatures (codegen)

Running `npm run gen` (alias for `npm run cli generatetypes`) emits a `<File>.routes.gen.ts` next to every controller. The gen file exports one type alias per handler method (PascalCase suffixed with `Request`) — handlers import the alias instead of hand-writing `FrameworkRequest & { appInfo: { request: { ... } } }`:

```ts
// src/controllers/Auth.ts
import type { PostLoginRequest } from "./Auth.routes.gen.ts";
import { object, string } from "yup";

class Auth extends AbstractController {
  get routes() {
    return {
      post: {
        "/login": {
          handler: this.postLogin,
          request: object().shape({
            email: string().email().required(),
            password: string().required(),
          }),
        },
      },
    };
  }

  async postLogin(req: PostLoginRequest, res: Response) {
    // req.appInfo.request.email is typed as string (from the schema)
    // req.appInfo.user is typed as InstanceType<TUser> | undefined
    //   (from GetUserByToken middleware's `static get provides()`)
    // req.appInfo.i18n.t(...) is typed (from BaseAppInfo)
  }
}
```

The gen file uses `InstanceType<typeof Controller>['routes'][...]['request']` type navigation, so schemas stay inline in the `routes` getter — no extracted named consts required. It also intersects in `provides` shapes from the middleware tuple at this route, so `req.appInfo.user` (and any other middleware-contributed fields) are typed automatically.

**What the generated type carries** (per route):

| Source | Emitted into |
|---|---|
| Route path `:name` segments (e.g., `/users/:id`) | `req.params: { id: string }` |
| Route path `{*name}` splats (e.g., `/files/{*path}`) | `req.params: { path: string }` — splats join captured segments with `/` (one string, not an array) |
| Route `request:` schema | `req.appInfo.request: StandardSchemaV1.InferOutput<...>` |
| Route `query:` schema | `req.appInfo.query: StandardSchemaV1.InferOutput<...>` |
| Route `params:` schema | `req.appInfo.params: StandardSchemaV1.InferOutput<...>` — the raw `req.params` row above stays `string`-valued |
| Middleware-chain `static get provides()` returns | Merged into `req.appInfo` |

The middleware chain in the gen file is read from the same `RouteRegistry.flatten()` the runtime uses — so the types you see at compile time match the middlewares that actually run at request time. No parallel matcher to drift.

#### Keep `routes` declarative (codegen reads the source, never your constructor)

`npm run gen` analyzes each controller **statically, from its source AST** — it never imports, constructs, or runs your controller. That keeps type generation free of side effects (config reads, S3/OAuth client construction, timers, DB connections) and fast.

The trade-off: the `routes` (and `static get middleware()` / `getHttpPath()`) getter must return a **plain object literal** that the parser can read directly. It may reference handler methods (`handler: this.postLogin`) and inline schemas, but it must not be computed — no reading constructor state, no loops, conditionals, computed keys, or `super` calls in the returned shape.

```ts
// ✅ fine — the constructor sets up clients, but `routes` returns a literal
class Files extends AbstractController {
  constructor(app, prefix) {
    super(app, prefix);
    this.s3 = new S3Client(app.getConfig('s3')); // used inside handlers, not in routes
  }
  get routes() {
    return { post: { '/upload': { handler: this.upload } } };
  }
}

// ❌ not analyzable — `routes` is computed from constructor state
class Crud extends AbstractController {
  constructor(app, prefix) {
    super(app, prefix);
    this.models = ['User', 'Order'];
  }
  get routes() {
    // a computed return — the AST can't read these route shapes
    return Object.fromEntries(this.models.map((m) => [`/${m}`, { handler: this.list }]));
  }
}
```

If a `routes` getter isn't a static literal, codegen can't analyze it and **`npm run gen` fails** (declarative-only — there is no constructor fallback). Move the dynamic part into handlers or a module-level constant so the returned shape stays literal.

#### Setup

Install the parser code generation uses. `oxc-parser` is an **optional peer dependency** — it reads your controller sources and is never loaded at runtime, so it stays out of production installs:

```sh
npm i -D oxc-parser
```

Add to `package.json`:

```json
"gen": "node src/cli.ts generatetypes",
"check:types": "npm run gen && tsc --noEmit"
```

Add to `.gitignore`:

```
**/*.routes.gen.ts
```

The gen files are regenerated on every type-check, so they stay fresh; CI doesn't need any extra step.

#### Naming convention

Handler method `postLogin` → type `PostLoginRequest`. Method `verifyUser` → `VerifyUserRequest`. The convention is method name in PascalCase + `Request` suffix. Renames flow naturally with editor refactor tools.

If the same handler method serves multiple routes (e.g., a backward-compatible POST and GET sharing one method), the type is a union of the per-route shapes — narrow with `req.method` inside the handler.

#### Routes without schemas

Bare-method-ref routes like `'/logout': this.postLogout` (no `request:` field) get a type that omits the schema-output override; `req.appInfo.request` falls through to the default `Record<string, unknown>` from `BaseAppInfo`.

#### Middleware-provided types

To make a middleware contribute typed fields to `req.appInfo`, add a `static get provides()` getter:

```ts
class GetUserByToken extends AbstractMiddleware {
  static get provides() {
    return {} as { user?: InstanceType<TUser> };
  }

  async middleware(req, res, next) {
    // ... runtime logic ...
  }
}
```

The returned object is always `{}` — only the cast type matters. Codegen reads this; the runtime ignores it. Handlers downstream of this middleware (per the route's middleware chain) get `req.appInfo.user` typed.

The same pattern works for **project-side middlewares** that augment `req.appInfo`. Example — a `UserWithRole` middleware that resolves CASL permissions onto the request:

```ts
import type { MongoAbility } from "@casl/ability";
import AbstractMiddleware from "@adaptivestone/framework/services/http/middleware/AbstractMiddleware.js";

class UserWithRole extends AbstractMiddleware {
  static get provides() {
    return {} as { permissions: MongoAbility };
  }

  async middleware(req, res, next) {
    req.appInfo.permissions = await buildPermissions(req.appInfo.user);
    next();
  }
}
```

Any route with `UserWithRole` in its middleware chain now has `req.appInfo.permissions` typed as `MongoAbility` automatically.

For app-wide globals (e.g., `requestId`, `sentryTransaction`) that aren't tied to a specific middleware, augment `AppInfoExtensions`:

```ts
declare module "@adaptivestone/framework/services/http/types" {
  interface AppInfoExtensions {
    requestId: string;
  }
}
```

#### Extending the framework's User model

If your project's `User` model adds methods or fields beyond the framework's base (`getSuppliers()`, custom relations, etc.), `req.appInfo.user` from `GetUserByToken.provides` will still be typed as the framework's `TUser` — calls to project-specific methods won't compile.

Augment the framework's `User` module to add your project's fields:

```ts
// somewhere in your project, loaded before handlers compile
declare module "@adaptivestone/framework/models/User" {
  interface IUserMethods {
    getSuppliers(): Promise<string[]>;
  }
}
```

Now `req.appInfo.user.getSuppliers()` type-checks across all handlers.

#### Manual fallback (without codegen)

If you'd rather not run codegen, you can pull a typed shape from any Standard Schema validator with `StandardSchemaV1.InferOutput`:

```ts
import type { StandardSchemaV1 } from "@adaptivestone/framework/services/validate/types";
import { object, string } from "yup";

const loginSchema = object({
  email: string().email().required(),
  password: string().required(),
});

type LoginRequest = StandardSchemaV1.InferOutput<typeof loginSchema>;

async postLogin(
  req: FrameworkRequest & { appInfo: { request: LoginRequest } },
  res: Response,
) {
  // req.appInfo.request.email is typed
}
```

This works for Zod, Valibot, ArkType too. Trade-off: middleware-contributed fields (`req.appInfo.user` and friends) need to be intersected by hand on every handler, and renames don't propagate.

### File Validation

Files are uploaded via `multipart/form-data`. The parser preserves the raw form shape, which means **every multipart field arrives as an array** — a single value is a one-element array, several values are a longer array. Validate against the framework-exported `File` type, using your validator's own array support to declare cardinality:

```ts
import { File } from "@adaptivestone/framework/types.js";
import { z } from "zod";

request: z.object({
  // one file: validate the one-element array, unwrap to a File for the handler
  avatar: z.array(z.instanceof(File)).length(1).transform(([f]) => f),
  // many files (`<input type="file" multiple>`): keep the array
  avatars: z.array(z.instanceof(File)).nonempty(),
});
```

`req.appInfo.request.avatar` is a `File`; `req.appInfo.request.avatars` is `File[]`.

:::caution Cardinality is declared, not inferred from length
A single value and a one-element array look identical on the wire (`["A"]`), so you must **declare** which fields are scalar — never auto-unwrap by array length. A `multiple` field that receives one file still arrives as `["A"]`; because `avatars` is declared `z.array(...)` (no transform), it correctly stays a one-element `File[]`. Only fields you explicitly transform to a scalar (`.length(1).transform(...)`) are unwrapped — and a scalar field that receives two values fails `.length(1)`, which is the right outcome.
:::

`File` is exported as both a value (so `instanceof` works) and a type. It aliases the parser's file class today and re-points at the web-standard `File` after the transport-neutral parser swap — so your validation code stays stable across that change. The same `File` works with every validator: `z.instanceof(File)`, `v.instance(File)`, `type.instanceOf(File)`, or yup's `mixed().test("file", "not a file", (v) => v instanceof File)`.

#### How route types are generated for multipart

Route-type generation is **parser-agnostic** — the multipart always-array shape never reaches it. Codegen emits `req.appInfo.request: StandardSchemaV1.InferOutput<...["request"]>`, which reads the request schema's **output** type. Because the schema above transforms the one-element array down to a `File`, the generated handler type is the unwrapped shape (`{ avatar: File; avatars: File[] }`) — and it matches the runtime value. The schema is the single source of truth for both runtime and types.

:::info Planned — route-level single-element extraction
A **route-level option** is planned so a route can declare which multipart fields are scalar, and the router unwraps their single-element arrays *before* validation. The schema then stays the clean logical shape (`avatar: z.instanceof(File)`), codegen reads that output type directly, and there's no per-field `.array().length(1).transform(...)` to write. This keeps the array-handling in the parser layer (where the array-ness originates) instead of the schema. Until it ships, use the validator's array handling shown above.
:::

:::warning Deprecated: `YupFile`
The yup-specific `YupFile` helper (`@adaptivestone/framework/helpers/yup.js`) is **deprecated and will be removed in v6** — migrate to the `File` export above. It still works for now (and requires `yup` in your own dependencies, since the framework no longer bundles it):

```js
import { YupFile } from "@adaptivestone/framework/helpers/yup.js";

request: yup.object().shape({
  someFileName: new YupFile().required("error text"),
});
```
:::

:::warning
Please be aware that a file can only be uploaded by ‘multipart/form-data’, and because of this, you can’t use nested objects.
:::

### Different schemas per Content-Type

A single route can accept more than one `Content-Type` with a different body shape for each — for example, create a resource from JSON or upload it as `multipart/form-data`. Instead of one `request` schema, pass a **content-type map** (the shape mirrors OpenAPI's `requestBody.content`):

```ts
import { File } from "@adaptivestone/framework/types.js";
import { z } from "zod";

"/avatar": {
  handler: this.setAvatar,
  request: {
    "application/json": z.object({ url: z.string().url() }),
    "multipart/form-data": z.object({
      file: z.array(z.instanceof(File)).length(1).transform(([f]) => f),
    }),
  },
},
```

The body is parsed (the parser is already Content-Type-aware), then validated with the schema matching the request's `Content-Type`. An unmatched type returns **415 Unsupported Media Type**, listing the accepted ones.

`req.appInfo.request` becomes a **discriminated union** keyed by an injected `contentType` field, so the handler narrows cleanly — and codegen emits the union for you:

```ts
async setAvatar(req: SetAvatarRequest, res: Response) {
  if (req.appInfo.request.contentType === "multipart/form-data") {
    req.appInfo.request.file; // File
  } else {
    req.appInfo.request.url; // string
  }
}
```

:::note
Matching is on the media type only and is **case-insensitive** — parameters like `; charset=...` and `; boundary=...` are ignored. The injected `contentType` is the lower-cased media type, and it overwrites any body field of the same name, so don't declare a schema field named `contentType`. A `Content-Type` the body parser itself can't handle (e.g. malformed `multipart/form-data`) is rejected with a `400` by the parser *before* the `415` check. Middleware-declared request schemas (`relatedRequestParameters`) still apply on top, regardless of Content-Type.
:::

### Combining route and middleware validation outputs

:::info Corrected in framework 5.4.1

The middleware-output typing and non-object handling described here require
framework 5.4.1 or newer. Upgrade from 5.4.0 or earlier before relying on these
corrections.

:::

For `req.appInfo.request`, the framework combines the route's `request` output
with outputs from middleware `relatedRequestParameters` schemas. For
`req.appInfo.query`, it combines the route's `query` output with middleware
`relatedQueryParameters` outputs.

Each validator receives the original body or query input. Validators do not
receive the preceding validator's transformed result. The framework merges
completed outputs in a fixed order: route first, then middleware in route-chain
order. Async completion order does not change which output wins.

When several schemas contribute to the same slot, their outputs must be plain
objects. The merge is shallow: a later own property replaces the earlier value,
including an entire nested object. For example, these two outputs:

```ts
// Route output
const routeOutput = { limit: "10", filters: { category: "books", active: true } };

// Later middleware output
const middlewareOutput = { limit: 10, filters: { active: false } };

// Result exposed to the handler
const mergedOutput = { limit: 10, filters: { active: false } };
```

Generated request types follow this order. A later required property replaces
the earlier property's type. If the later property is optional, the earlier
value remains possible when that property is absent, so the generated type
retains both possibilities. An explicitly present `undefined` still overwrites
the earlier value at runtime.

With exactly one schema contributing to a slot, its output is preserved,
including arrays, scalar values and `null`. For example, a single
`z.array(z.string())` request schema produces a `string[]` handler value. Adding
a middleware request schema means there are now multiple outputs; every output
must then be a plain object. Put array data inside an object property when
several schemas need to contribute fields.

A content-type map also requires a plain-object result so the framework can add
its `contentType` discriminator. The discriminator is added to a new object
after merging, without mutating the validator's returned object. Non-object
outputs in a multi-schema combination or a content-type map are configuration
errors handled by the normal 500 error path, not field-validation 400 errors.

Run codegen after changing middleware `relatedRequestParameters` or
`relatedQueryParameters`, as well as after changing route schemas.

### Custom validators

To plug in a validator that doesn't already implement Standard Schema (e.g., raw [Joi](https://joi.dev/), or a hand-rolled function), implement the `~standard` slot directly. About 10 lines of glue:

```ts
import type { StandardSchemaV1 } from "@adaptivestone/framework/services/validate/types";

interface ProductInput { sku: string; price: number }

const productSchema: StandardSchemaV1<unknown, ProductInput> = {
  "~standard": {
    version: 1,
    vendor: "mycustom",
    validate(value) {
      const data = value as Partial<ProductInput>;
      if (typeof data.sku !== "string") {
        return { issues: [{ message: "sku is required", path: ["sku"] }] };
      }
      if (typeof data.price !== "number") {
        return { issues: [{ message: "price is required", path: ["price"] }] };
      }
      return { value: { sku: data.sku, price: data.price } };
    },
  },
};

// Use it on a route:
request: productSchema;
```

You also get `InferOutput<typeof productSchema>` for free. Standard Schema's spec lives at https://standardschema.dev/.

### Registering vendor drivers

For library-specific behavior (custom strip semantics, native JSON Schema export for OpenAPI, etc.), register a `ValidatorDriver`:

```ts
import { ValidateService, type ValidatorDriver } from "@adaptivestone/framework/services/validate/ValidateService";

const myJoiDriver: ValidatorDriver = {
  canHandle: (body) => body?.isJoi === true,
  async validate(body, data) {
    const { value, error } = body.validate(data, { stripUnknown: true });
    if (error) throw new ValidationError(joiToFrameworkPayload(error));
    return value;
  },
  toJsonSchema: (body) => myJoiToJsonSchema(body), // optional — supplies the OpenAPI body schema
};

ValidateService.register(myJoiDriver);
```

Drivers are matched in registration order; user-registered drivers take priority over the built-ins. Register them before `startServer()` (module scope, as above): routes resolve their driver once at boot, and a schema no driver matches fails the boot with a migration message instead of answering a 500 later.

### ValidationError

When validation fails, the framework throws a `ValidationError`. The instance's `.message` is the path-keyed payload object, sent as the `errors` of the response:

```json
{
  "message": "Validation failed",
  "errors": {
    "fieldName": ["error description"],
    "anotherField": ["another field error"]
  }
}
```

Each value is always an array of messages. A field that fails multiple validators surfaces all of them: `{password: ["min8", "startUpper"]}`.

The body is `message` plus `errors` — no `data`. `message` is translatable through the `http.validationFailed` key. Every framework error response follows the same contract, `{ error?, message, errors? }`, so a client can always read field errors from `body.errors` (see [Error handling](04-error-handling.md#error-codes-and-translated-messages)). If you are replacing a hand-rolled in-handler guard with a `request:`/`query:`/`params:` schema and your project envelope is `{ data, message?, errors? }`, clients and tests that read `data` (for example asserting `body.data === null`) must stop expecting it.

Validation errors cover input that fails the declared schema **before** the handler runs. For errors thrown **inside** the handler — typed HTTP errors like `NotFoundError`, third-party errors you map yourself, escaped Mongoose validation — see [Error handling](04-error-handling.md).

For structured access (logging, observability), use `.issues`:

```ts
import { ValidationError } from "@adaptivestone/framework/services/validate/ValidationError";

try {
  /* ... */
} catch (e) {
  if (e instanceof ValidationError) {
    for (const issue of e.issues) {
      console.error(`[${issue.path?.join(".") ?? "root"}] ${issue.message}`);
    }
  }
}
```

### i18n

In any fields that can generate an error (required, etc.), you can use i18n keys to translate. The framework will handle the translation for you.

Please refer to the [i18n documentation](../08-i18n.md).

## Handler

Handler - some async function (most likely in this controller file) that will do all the work. It is better to write the function in the same file.

:::warning
The handler can only be an **async** function.
:::

`req.appInfo.app`

```js
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";

class ControllerName extends AbstractController {
  get routes() {
    return {
      post: {
        '/': {
          handler: this.postSample,
          request: yup.object().shape({
            count: yup.number().max(100).required(),
          })
        }
      }
    }
  }
  // Send a request with data {count: "5000"}.
  // Will produce an error with status 400 and {message: 'Validation failed', errors: {count:['Text error']}}.

  postSample(req, res) {
    // On success validation, we pass here.
    // {count: "5000"}
    console.log(req.appInfo.request)
    // {count: 5000} -> casted to a number

    const SomeModel = this.app.getModel('SomeModel');
    const SomeModelAlternativeWay = req.appInfo.app.getModel('SomeModel');

    const { count } = req.appInfo.request;

    const someModel = await SomeModel.findOne({count});

    return res.status(200).json({modelId: someModel.id});
  }

}
export default ControllerName;
```

### Middleware

Middleware - an array of middlewares specially for the current route.

:::warning

Route middlewares take precedence over middlewares in controllers.

:::

```javascript
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";

class ControllerName extends AbstractController {
  get routes() {
    return {
      get: {
        '/routeName': {
          handler: ...,
          middleware: [MiddlewareName, MiddlewareName, etc]
        }
      },
    };
  }
}
export default ControllerName;
```

Similarly to controller middlewares, you can use middlewares with parameters.

:::note

The rules for the design of middlewares with parameters are described in the subsection "Middleware".

:::

Sample:

```javascript
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";
import RoleMiddleware from "@adaptivestone/framework/services/http/middleware/Role.js";

class ControllerName extends AbstractController {
  get routes() {
    return {
      get: {
        '/routeName': {
          handler: ...,
          middleware: [[RoleMiddleware, { roles: ['client'] }]]
        }
      },
    };
  }
}
export default ControllerName;
```

## Debugging your routes

### Boot-time route tree

After all controllers are registered, the framework prints the full route tree at the `verbose` log level — useful for spotting cross-controller middleware accumulation, splat scopes, or unexpected route shapes. Set `LOGGER_CONSOLE_LEVEL=verbose` (or your transport's equivalent) to see it.

```
Registered routes:
/  (mw: GetUserByToken)
├── GET     /
├── auth  (mw: RateLimiter; pmw: GetUserByToken)
│   ├── login
│   │   └── POST    /auth/login  [request]
│   └── logout
│       └── POST    /auth/logout
└── v1  (mw: ApiLimiter; pmw: GetUserByToken)
    └── container
        ├── GET     /v1/container  [query]
        └── POST    /v1/container  [query]

5 route(s) across 6 node(s) in the tree.
```

Each method line is `METHOD` (padded) followed by the route's full path — handler names aren't printed. `[request]` / `[query]` markers indicate routes with body / query schemas. For middleware: `(mw: …)` lists what's newly attached at that node or route, `pmw: …` lists the inherited chain that already runs above it (deduped, in run order), and `{…}` after a middleware name means it was registered with parameters.

### Warnings on misconfiguration

The framework logs a `warn`-level message and skips the offending entry when it sees these problems in your `routes` getter or middleware `Map`:

| Warning | Triggered when |
|---|---|
| `unknown verb 'X' in routes getter` | A key in `get routes()` isn't one of `get/post/put/patch/delete/head/options` |
| `route X Y has no handler function` | A route's value is an object but its `handler` field is missing or not callable |
| `middleware Map key is not a string` | A key in `static get middleware()`'s `Map` is not a string |
| `middleware Map key 'X' has unknown method prefix 'Y'` | A `Map` key looks like `METHOD/path` but `METHOD` is not a known HTTP verb — the whole key is treated as a path, which is usually a typo |

These warnings catch the common typos that used to silently produce 404s at request time.


---


# Document 9: 06-Controllers > 03-middleware

<!-- Source: 06-Controllers/03-middleware.md -->

# Middleware

You can read more about middlewares at [https://expressjs.com/en/guide/using-middleware.html](https://expressjs.com/en/guide/using-middleware.html).

In general, it’s a function that accepts a request, a response, and a `next` callback. This function can analyze requests and add more details to them (like parsing JSON, getting query params, or checking a user token). Middleware can pass requests to the next level (the next middleware or handler) or can respond directly and finish the request.

This is really powerful and allows developers to reuse simple logic and build routes on these simple building blocks.

Default:

```js
  static get middleware() {
    return new Map([['/{*splat}', [GetUserByToken, Auth]]]);
  }
```

## Middleware Order

Middleware will be executed in the order provided. Based on that, you can chain middleware where the input of the second middleware depends on the output of the first middleware.

## Global Middlewares

The framework internally uses a few middlewares. These middlewares are not adjustable (for now) and are executed on each request, in this order (security response headers are applied first, before any of these):

[RequestLogger](#requestlogger)

[PrepareAppInfo](#prepareappinfo)

[IpDetector](#ipdetector)

[I18n](#i18n)

[Cors](#cors)

[RequestParser](#requestparser)

## Including Middlewares into Controllers

Controller-level middleware is adjusted based on the “middleware” getter.

```js
  static get middleware() {
    return new Map([['METHOD/path', ["Middleware","Array"]]]);
    // return middlewares for THIS route only
  }
```

Where 'METHOD/path' is a method with a path. Supported methods are `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, and the pseudo-verb `ALL` (matches all methods). If the middleware key starts with `/`, then `ALL` methods are used.

The path follows the same patterns as routes — literals, `:name` params, and `{*name}` splats. See [Routes › path syntax](02-routes.md#route-second-level-path-level) for the full reference.

The middleware array is an array of middlewares (with params).

Sample:

```javascript
  static get middleware() {
    return new Map([['GET/{*splat}', [GetUserByToken]]]);
  }
```

```javascript
  static get middleware() {
    return new Map([
      ['POST/someUrl', [
        GetUserByToken,
        [RoleMiddleware, { roles: ['admin'] }]
      ]]
    ]);
  }
```

:::warning
The middleware here are not raw Express middlewares. Please see below.
:::

## Including Middlewares into a Route Object

Middlewares can also be added into a route object (subchapter “Routes”).

## Middleware Parameters

Some middleware accept initial parameters passed into them.

```javascript
  static get middleware() {
    return new Map([
      ['POST/someUrl', [
        GetUserByToken, // middleware with no parameters
        [RoleMiddleware, { roles: ['admin'] }] // middleware with parameters
      ]]
    ]);
  }
```

To pass parameters, wrap the middleware in an array. The first element will be the middleware itself, and the second one will be the middleware parameters. The second one will be passed as is into the middleware constructor.

## Built-in Middleware

The framework has a few middlewares that you can use.

:::info Translatable since 5.4

Every user-facing message the built-in middleware return (the auth 401, both role rejections, the rate-limit 429 and the two request-parser failures) is emitted as an i18n key with its English text as the in-code default. They read as English out of the box; define the key in your own locale files to reword or translate one. The key table lives in [i18n › Middleware keys](../08-i18n.md#middleware-keys).

Status codes and machine-readable fields are not affected — the auth 401 still carries `error: "AUTH001"` whatever `message` says. Since 5.5 these responses are thrown errors, so you can also reshape them with an error handler: see [Error handling › Errors from middleware](./04-error-handling.md#errors-from-middleware).

:::

### Auth

```js
import Auth from "@adaptivestone/framework/services/http/middleware/Auth.js";
```

Allows passing only if the user is provided. Please use any middleware that provides a user instance beforehand (like `GetUserByToken`).

#### Parameters

No parameters.

### Cors

```js
import Cors from "@adaptivestone/framework/services/http/middleware/Cors.js";
```

Adds CORS headers if the origin matches the config. Every response also gets `Vary: Origin`, added to any existing `Vary` value, so shared caches keep responses for allowed and other origins apart.

#### Parameters

`origins` - an array of strings or regex to check the origin. Required parameter.

`exposedHeaders` - an array of response header names that browser code on an allowed origin may read. Optional.

```javascript
  static get middleware() {
    return new Map([
      ['GET/someUrl', [
        [Cors, { origins: ['http://localhost',/./], exposedHeaders: ['Retry-After'] }]
      ]]
    ]);
  }
```

#### Exposed headers

Browsers let cross-origin JavaScript read only a few basic response headers (`Content-Type`, `Content-Length`, `Cache-Control`, `Content-Language`, `Expires`, `Last-Modified`, `Pragma`). Any other header is hidden: `response.headers.get('Retry-After')` returns `null` even though the header was sent. `exposedHeaders` sends `Access-Control-Expose-Headers` on responses to allowed origins (not on preflight requests), so the listed headers become readable.

The global CORS middleware reads the list from `http.corsExposedHeaders`, next to `corsDomains`. It defaults to `['Retry-After']`, so a web app can show how long to wait after a [rate limiter](#ratelimiter) 429. An array in your `config/http.ts` replaces the default instead of extending it, so keep `Retry-After` when you add your own headers:

```ts
// config/http.ts
export default {
  corsDomains: ["https://app.example.com"],
  corsExposedHeaders: ["Retry-After", "X-Request-Id"],
};
```

### GetUserByToken

```js
import GetUserByToken from "@adaptivestone/framework/services/http/middleware/GetUserByToken.js";
```

Grabs a token and tries to parse the user from it. It will find the user in the database by the token. If the user exists, it will add the `req.appInfo.user` variable.

#### Parameters

No parameters.

### I18n

```js
import I18n from "@adaptivestone/framework/services/http/middleware/I18n.js";
```

An internationalization module based on [i18next](https://www.npmjs.com/package/i18next). It provides `req.appInfo.i18n` that can be used for translation.

The middleware provides a few detectors:

- X-Lang header
- Query
- User

`i18next` and `i18next-fs-backend` are **optional peer dependencies** — install them (`npm i i18next i18next-fs-backend`) only if you translate. Without them the middleware still runs, `req.appInfo.i18n.t()` still answers, and every message is served in English.

Please check the [i18n documentation](../08-i18n.md) for more details.

#### Parameters

No parameters.

### IpDetector

```js
import IpDetector from "@adaptivestone/framework/services/http/middleware/IpDetector.js";
```

This middleware will detect the client's IP. It works well with different proxies (AWS ELB, Nginx, etc.) and detects the real client IP.

:::note
If the request IP is from a `trustedProxy` (trusted source) only, then the module will try to parse the IP from the provided `X-Forwarded-For` header and grab the client IP from there. Otherwise, the request IP will be used.
:::
This is a core middleware, and some other middlewares (like `RateLimiter`) depend on it.

#### Parameters

All parameters go into the config file. There are two parameters there: `headers` and `trustedProxy`.

`headers` is an array of headers to parse the IP address from. By default, it is 'X-Forwarded-For'.

`trustedProxy` is an IP, CIDR, or range of IPv4 and IPv6 that is trusted to parse headers from.

```javascript
  headers: ['X-Forwarded-For'],
  trustedProxy: [ // list of trusted proxies.
    '169.254.0.0/16', // ipv4 cidr
    'fe80::/10', // ipv6 cidr
    '127.0.0.1', // ip itself
    '1.1.1.1-1.1.1.3', // ip range
  ],
```

IP data is available at:

```javascript
req.appInfo.ip;
```

:::warning
Select `trustedProxy` really carefully, as anyone can add any headers to your request.
:::

Nginx sample to add a header:

```bash
server {
    location xxxx/ {
      proxy_set_header  X-Forwarded-For $remote_addr;
    }
  }

```

### Pagination

```js
import Pagination from "@adaptivestone/framework/services/http/middleware/Pagination.js";
```

The pagination middleware provides a helper that grabs URL search parameters (`page`, `limit`) and calculates the necessary `appInfo` properties (`skip`, `limit`, and `page`).
Routes using it also expose optional numeric `page` and `limit` query
parameters in generated OpenAPI documents automatically.

#### Parameters

`limit` = 10 - default limit if not provided.

`maxLimit` = 100 - max limit for documents.

```javascript
  static get middleware() {
    return new Map([
      ['POST/someUrl', [
        [Pagination, { limit: 10,maxLimit: 50}]
      ]]
    ]);
  }
```

```javascript
  static get middleware() {
    return new Map([
      ['POST/someUrl', [Pagination]
    ]);
  }
```

```javascript
// http://localhost:3300/someUrl?limit=10&page=2
const { limit, skip, page } = req.appInfo.pagination;
```

A `page` or `limit` that is not a number is rejected with `400`. A missing, zero or negative `limit` uses the default, and a larger one is reduced to `maxLimit`. A missing, zero, negative or absurdly large `page` (one that would make `skip` unsafe) becomes `1`.

### PrepareAppInfo

```js
import PrepareAppInfo from "@adaptivestone/framework/services/http/middleware/PrepareAppInfo.js";
```

`PrepareAppInfo` is a special small middleware that generates `req.appInfo = { app }`. This is to make sure that all subsequent middleware can use `appInfo` without checking if it exists.
It is for internal use.

#### Parameters

No parameters.

### RateLimiter

A rate limiter middleware. Limits the amount of requests.

```js
import RateLimiter from "@adaptivestone/framework/services/http/middleware/RateLimiter.js";
```

For rate limiting, we are using the [node-rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) module. Please refer to the module documentation for more details.

The basic idea of a rate limiter is that we have some weight for the call and some key that has ‘credits’. Each call consumes ‘credits’, and when it reaches 0, the request is blocked.

Some samples - login protection. We can generate rate limiters based on the user's email and limit each email to only 5 calls per minute. Or we can construct a more complex login that includes user IPs, etc.

#### Parameters

By default, the rate key is generated based on the Route, IP, and userID. But you can adjust it via the config (globally) or via middleware parameters.

:::info Upgrading to 5.4.1

When `consumeKeyComponents.route` is enabled, the route component uses the registered route template and HTTP method. Different parameter values, case variants, encoded spellings and trailing slashes share a budget; implicit HEAD shares GET's budget. A limiter mounted before routing uses one route bucket per method.

Upgrading resets existing rate-limit counters. Complete the rollout across workers promptly so older workers cannot maintain separate buckets for equivalent URLs.

:::

```javascript
  static get middleware() {
    return new Map([
      [
        'POST/login',
        [
          GetUserByToken,
          [
            RateLimiter,
            {
              consumeKeyComponents: { ip: false },
              limiterOptions: { points: 5 },
            },
          ],
        ],
      ],
    ]);
  }
```

You can include request body fields in the key. The limiter runs before validation, so it reads the raw `req.body`, not `req.appInfo.request`. Each value is Unicode-normalized (NFKC), trimmed and lowercased, so `Foo@x.com`, ` foo@x.com` and `FOO@x.com` share one budget; blank values and objects/arrays are ignored. Field names and values are hashed into the key, so e-mails never appear in stored keys or logs.

:::info Upgrading to 5.5.0

Request-keyed limiters re-key on upgrade, which resets their counters. If you added a middleware that lowercases or trims body fields before `RateLimiter`, you can remove it.

:::

```javascript
  static get middleware() {
    return new Map([
      ['POST/login', [
        GetUserByToken,
        [RateLimiter,{consumeKeyComponents: { ip: false, request:['email','phone'] }}]
      ]]
    ]);
}
```

The key must treat as equal every spelling your user lookup treats as equal. If your lookup normalizes further (for example, ignores dots or `+tags` in Gmail addresses), extend `RateLimiter` and override `generateConsumeKey` to build the key from the same canonical form.

#### Typed named policies from config

Keep reusable operational limits in the application's typed configuration
instead of repeating numbers across controllers:

```ts title="src/config/rateLimiter.ts"
import defaults from '@adaptivestone/framework/config/rateLimiter.js';

export default {
  ...defaults,
  policy: {
    personCreate: {
      limiterOptions: { points: 3, duration: 60 * 60 },
    },
  },
};
```

Read the final merged config once when the controller module loads and pass the
selected options object directly to the existing middleware tuple:

```ts
import { getAppInstance } from '@adaptivestone/framework/helpers/appInstance.js';
import AbstractController, {
  type TMiddleware,
} from '@adaptivestone/framework/modules/AbstractController.js';
import RateLimiter from '@adaptivestone/framework/services/http/middleware/RateLimiter.js';

const { policy } = getAppInstance().getConfig('rateLimiter');

class Person extends AbstractController {
  static get middleware(): Map<string, TMiddleware> {
    return new Map([
      ['/{*splat}', []],
      ['POST/', [[RateLimiter, policy.personCreate]]],
    ]);
  }
}
```

Run `npm run gen` after adding the config. Generated config types preserve the
policy names, so `policy.personCreate` is autocompleted and a misspelling fails
TypeScript; `RateLimiter` receives the actual options object and performs no
string lookup.

For route-level policies, a simple initialized `const` config read before the
literal route return is also statically analyzable:

```ts
get routes() {
  const { policy } = this.app.getConfig('rateLimiter');
  return {
    post: {
      '/': {
        handler: this.create,
        middleware: [[RateLimiter, policy.personCreate] as const],
      },
    },
  };
}
```

The returned route tree must remain literal. Loops, conditionals, mutable setup,
computed route keys, and dynamically constructed middleware are still skipped
by route-type generation with a warning. The `as const` keeps the route-level
middleware pair typed as a tuple; the AST extractor safely unwraps this
TypeScript-only annotation. Route-type generation never executes the getter —
the `const` prelude is checked by statement shape only, so an initializer that
happens to have side effects is accepted, and those effects run at runtime only.

Declare the policy catalogue in the base config, then override policy values in
environment-specific config files. Controller modules capture the effective
boot-time value; a later `app.updateConfig()` does not mutate limiter instances
that already exist. Config merging uses `deepmerge`, so array fields are
concatenated rather than replaced—most policies should override scalar
`limiterOptions` such as `points` and `duration`.

You can find the default parameters in ‘config/rateLimiter.js’. These parameters are used if other parameters are not provided.

The rate limiter has multiple backends, selected via the `driver` option (`'mongo'`, `'memory'`, or `'redis'`). The default is `'mongo'`. The `'redis'` backend lazy-loads `@redis/client`, which is an **optional peer dependency** — install it (`npm i @redis/client`) when you choose that driver; the `'memory'` and `'mongo'` backends never load it.

### RequestLogger

```js
import RequestLogger from "@adaptivestone/framework/services/http/middleware/RequestLogger.js";
```

A small middleware that logs request info (route, method, status, and time).

Logs example:

```js
[middlewareRequestLogger]  2023-01-24T07:00:35.680Z  info : Request is  [GET] /project/123
[middlewareRequestLogger]  2023-01-24T07:00:35.747Z  info : Finished Request is  [GET] /project/123.  Status: 200. Duration 67 ms
```

#### Parameters

No parameters.

### RequestParser

```js
import RequestParser from "@adaptivestone/framework/services/http/middleware/RequestParser.js";
```

This is the main middleware to parse requests (`application/json`, `multipart/form-data`, `application/octet-stream`, `application/x-www-form-urlencoded`).
It is based on the [formidable](https://www.npmjs.com/package/formidable) package.
After parsing, the data is available in `req.body`.

A body over the size or count limits (`requestParser` in `config/http.ts`) gets a `413` response. For a non-multipart body over `maxFieldsSize` — declared or streamed — the connection is closed after the `413` instead of reading the rest of the body.

#### Parameters

No parameters.

### Role

Checks the user role (`user.roles` property). If the user does not have the role, it stops the request and returns an error. It uses OR logic (any of the specified roles will allow the user to pass).

```js
import Role from "@adaptivestone/framework/services/http/middleware/Role.js";
```

#### Parameters

`roles` - an array of roles to check. It uses OR logic (any role will pass).

```javascript
  static get middleware() {
    return new Map([
      ['POST/someUrl', [
        [RoleMiddleware, { roles: ['admin','moderator'] }]
      ]]
    ]);
  }
```

### StaticFiles

:::warning

Deprecated and removed in version 5. It is better to use an HTTP server (Nginx, etc.) to handle static files.
:::

```bash
# nginx sample
server {

	root /var/www/application/src/public;

	server_name _;
	client_max_body_size 64M;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ @backend;
	}

	location @backend {
		proxy_pass http://localhost:3300;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection 'upgrade';
		proxy_set_header Host $host;
		proxy_cache_bypass $http_upgrade;
	}
}

```

## Creating Your Own Middlewares (or Integrating External Ones)

You can create your own middleware. To do that, you should extend `AbstractMiddleware` and provide at least two of your own functions: `description` and `middleware`. Please check the code below.

```js
import AbstractMiddleware from "@adaptivestone/framework/services/http/middleware/AbstractMiddleware.js";

class CustomMiddleware extends AbstractMiddleware {
  static get description() {
    return "Middleware description";
  }

  // optional
  static get authSchemes() {
    // How requests send the credentials this middleware reads — read by the
    // OpenAPI generator into `components.securitySchemes` (see the OpenAPI chapter).
    return [
      {
        name: "Authorization", // name of the parameter
        type: "apiKey", // apiKey, http, oauth2, openIdConnect
        in: "header", // header, query, cookie
        description: this?.description,
      },
    ];
  }

  // optional — declared `static` so the framework reads the schema WITHOUT
  // instantiating the middleware (no constructor side effects at route setup /
  // codegen)
  static get relatedQueryParameters() {
    // A Standard Schema-conformant schema (Zod, Valibot, ArkType, yup ≥1.7, or
    // `defineSchema`) for middleware-related `req.query` parameters. Validated
    // and exposed on `req.appInfo.query`, relative to the route the middleware
    // is declared on.
    return yup.object().shape({
      limit: yup.number(), // For example
    });
  }

  // optional
  static get relatedRequestParameters() {
    // Same, for middleware-related `req.body` parameters — exposed on
    // `req.appInfo.request`.
    return yup.object().shape({
      name: yup.string().required(), // For example
    });
  }

  async middleware(req, res, next) {
    // check something
    if (!req.body.yyyyy) {
      //  return and stop processing
      return res.status(400).json({});
    }
    if (this.params.iiii) {
      // we can also check all the params that we passed during init
    }
    // go to the next one
    return next();
  }
}

export default CustomMiddleware;
```

`static get authSchemes()` declares the security scheme(s) the middleware reads credentials from. The OpenAPI generator reads it off the class (no instantiation) to populate `components.securitySchemes` and documents auth on every route in the middleware's chain as optional. A middleware that rejects requests without a user also sets `static get requiresAuth()` to `true`, which makes auth required for the whole chain — see [OpenAPI › Documenting auth](../17-openapi.md#documenting-auth-security-schemes) for the field reference and an `http`/`bearer` example.

:::warning Deprecated: instance schema getters
The non-static form — `get relatedQueryParameters()` / `get relatedRequestParameters()` (and `get relatedReqParameters()`) — is **deprecated and will be removed in v6**. It forces the framework to instantiate the middleware (running its constructor) just to read the schema, so use `static get` instead. The instance form still works through v5: when it's detected, the framework instantiates the middleware as a fallback and emits a one-per-class `DeprecationWarning` (`ASF_DEP_MW_INSTANCE_SCHEMA`).
:::

### Rejecting a request

Instead of writing the response yourself, you can throw an [HTTP error](./04-error-handling.md#throwing-http-errors-from-your-code). It is answered through the error-handler registry, like an error from a route handler, so it gets the same response shape, translation and logging, and apps can reshape it:

```js
import { HttpError } from "@adaptivestone/framework/services/http/httpErrors.js";

class RequireSubscription extends AbstractMiddleware {
  static get description() {
    return "Allows only users with an active subscription";
  }

  async middleware(req, res, next) {
    if (!req.appInfo.user?.subscriptionActive) {
      throw new HttpError(402, {
        code: "SUB001",
        i18nKey: "middleware.subscription.required",
        message: "An active subscription is required",
      });
      // → 402 {"error": "SUB001", "message": "<translation, or the English message>"}
    }
    return next();
  }
}
```

This works since 5.5; before, any error thrown in a middleware became a 500.

### Translatable messages

When your middleware answers the request itself, do not hardcode the sentence. `AbstractMiddleware` gives every subclass a protected `translate(req, key, defaultValue)` — the same helper the built-in middleware use:

```js
import AbstractMiddleware from "@adaptivestone/framework/services/http/middleware/AbstractMiddleware.js";

class RequireSubscription extends AbstractMiddleware {
  static get description() {
    return "Allows only users with an active subscription";
  }

  async middleware(req, res, next) {
    if (!req.appInfo.user?.subscriptionActive) {
      return res.status(402).json({
        error: "SUB001", // machine-readable, never translated
        message: this.translate(
          req,
          "middleware.subscription.required",
          "An active subscription is required",
        ),
      });
    }
    return next();
  }
}
```

The default is the source of truth: it is what the client gets when the request carries no i18n at all, when i18n is disabled, and when the key is absent from the app's locale files. Define `middleware.subscription.required` in your locale file for a language and that wording wins whenever it is detected.

Keep the machine-readable part (`error`, the status code) out of the translated string — clients branch on those, not on the prose. See [i18n › Translating framework messages](../08-i18n.md#translating-framework-messages).

### Typed contributions to `req.appInfo`

If your middleware sets fields on `req.appInfo`, declare them via `static get provides()` so codegen can type them on every downstream handler — no per-handler intersections required.

```ts
import type { MongoAbility } from "@casl/ability";
import AbstractMiddleware from "@adaptivestone/framework/services/http/middleware/AbstractMiddleware.js";

class UserWithRole extends AbstractMiddleware {
  static get provides() {
    // Phantom — the runtime returns this `{}` but only the cast matters.
    return {} as { permissions: MongoAbility };
  }

  async middleware(req, res, next) {
    req.appInfo.permissions = await buildPermissions(req.appInfo.user);
    next();
  }
}
```

Any route with `UserWithRole` in its chain now has `req.appInfo.permissions` typed automatically. The cast type is the contract; the runtime value is ignored.

See the [routes chapter codegen section](./02-routes.md#middleware-provided-types) for the full picture of how generated request types compose middleware-provided fields, schemas, and path params.


---


# Document 10: 06-Controllers > 04-error-handling

<!-- Source: 06-Controllers/04-error-handling.md -->

# Error handling

What happens when a route handler or a middleware throws? The framework resolves the error through an ordered **error-handler registry**:

1. **Your registered handlers** — checked first, in registration order.
2. **Built-ins** — the `HttpError` mapper, the Mongoose validation safety net, then the Mongoose cast safety net.
3. **Fallback** — nothing matched: the error is logged at `error` level and the client gets `500 {"message": "Something went wrong. Please try again later."}`. Every framework 500 uses this one text, translatable through the `http.serverError` key.

The first entry whose error class matches (`instanceof`) and whose handler returns a response wins. That gives you two tools: **throw** typed HTTP errors from your own code, and **register** handlers for error types you don't own.

## Throwing HTTP errors from your code

Deep inside business logic you often know the right HTTP answer — the document doesn't exist, the user isn't allowed — but you don't have `res` there, and threading it through every function is noise. Throw instead:

```js
import { NotFoundError, ForbiddenError } from "@adaptivestone/framework/services/http/httpErrors.js";

class Posts extends AbstractController {
  get routes() {
    return {
      get: { "/:id": { handler: this.getOne } },
    };
  }

  async getOne(req, res) {
    const post = await this.app.getModel("Post").findById(req.params.id);
    if (!post) {
      throw new NotFoundError("Post not found");
      // → 404 {"message": "Post not found"}
    }
    if (String(post.ownerId) !== req.appInfo.user.id) {
      throw new ForbiddenError("Not your post");
      // → 403 {"message": "Not your post"}
    }
    return res.status(200).json({ data: post.getPublic() });
  }
}
```

It works from any depth — a service function three calls down can throw the same way.

Available classes (all from `services/http/httpErrors.js`):

| Class | Status | Default message |
| --- | --- | --- |
| `BadRequestError` | 400 | `Bad request` |
| `UnauthorizedError` | 401 | `Unauthorized` |
| `ForbiddenError` | 403 | `Forbidden` |
| `NotFoundError` | 404 | `Not found` |
| `ConflictError` | 409 | `Conflict` |
| `HttpError` | any | — (base class) |

Every constructor accepts a message string, or a details object in place of it (see [Error codes and translated messages](#error-codes-and-translated-messages)). Every framework error response follows one contract, so clients can rely on it:

```ts
{ error?: string; message: string; errors?: { [field: string]: string[] } }
```

`error` is a machine-readable code, `message` the human text, and `errors` the field errors: always an array per field, exactly as [request validation](02-routes.md#validation) answers. Field errors go in `errors`:

```js
throw new HttpError(422, {
  message: "Unprocessable",
  errors: { csv: "row 17 malformed" },
});
// → 422 {"message": "Unprocessable", "errors": {"csv": ["row 17 malformed"]}}
```

`errors` takes a string or an array per field, or validation issues (`[{ message, path, params }]`). A message that is an i18n key (for example `accounts.errors.csvRow`) is translated the same way validation messages are; free text is sent as-is. An empty `errors` object is left out.

### A fully custom response body

When a response genuinely needs a different shape, say so explicitly with `body`. It **is** the response: sent as-is, with no `error`, `message` or `errors` added. `message` is still required and only goes to the log:

```js
throw new ConflictError({
  message: "Task already exists",
  body: { existingId: task.id },
});
// → 409 {"existingId": "..."}
```

`body` opts this response out of the contract, so clients get no guaranteed `message` or `errors` from it. It cannot be combined with `code`, `i18nKey` or `errors`: TypeScript rejects the combination, and at runtime `body` wins and a one-time `ASF_HTTP_ERROR_BODY_MIXED` warning names the ignored fields. Prefer the contract whenever it fits.

:::warning Deprecated: `body` as a separate argument
The older form `new HttpError(422, "Unprocessable", body)` (and `new NotFoundError(message, body)`) still works but is **deprecated and will be removed in v6**. It logs a one-time `DeprecationWarning` per error class (`ASF_DEP_HTTP_ERROR_BODY`). Use the details object instead: `{ message, errors }` for field errors, or `{ message, body }` for a custom body. A plain message string such as `new NotFoundError("Post not found")` is not deprecated.
:::

### Error codes and translated messages

Instead of the message, pass a details object. `code` is a machine-readable code the client can branch on; `i18nKey` names the translation of the message and is never sent to the client:

```js
throw new ConflictError({
  code: "ALREADY_CONFIRMED",
  i18nKey: "accounts.errors.alreadyConfirmed",
  message: "This account is already confirmed.",
});
// → 409 {"error": "ALREADY_CONFIRMED", "message": "<translation, or the English message>"}
```

- `message` is required: it is the English fallback when the request's language has no `i18nKey` translation (or i18n is off), and the text that appears in logs.
- `code`, `i18nKey` and `errors` are optional and independent. Without `code` there is no `error` field; without `i18nKey` the message is never translated.
- The English `message` is used as-is, never interpreted as i18next syntax, so it can safely include request data.
- The details are readable on the error too: `err.code`, `err.i18nKey`, and `err.issues` for the field errors.

### Response headers

Add `headers` to the details object when the answer needs them, for example how long to wait before retrying:

```js
throw new HttpError(503, {
  code: "MAINTENANCE",
  message: "Back in a few minutes.",
  headers: { "Retry-After": "120" },
});
// → 503 Retry-After: 120 {"error": "MAINTENANCE", "message": "Back in a few minutes."}
```

`headers` works with a custom `body` too.

To keep throw sites short, wrap your own convention in a subclass:

```js
import { BadRequestError } from "@adaptivestone/framework/services/http/httpErrors.js";

const EN = { LOGIN_CODE_EXPIRED: "This code has expired. Request a new one." };

export class AccountsError extends BadRequestError {
  constructor(code) {
    super({ code, i18nKey: `accounts.errors.${code}`, message: EN[code] });
  }
}

throw new AccountsError("LOGIN_CODE_EXPIRED");
```

For a status you use often, subclass once and throw everywhere:

```js
import { HttpError } from "@adaptivestone/framework/services/http/httpErrors.js";

export class PaymentRequiredError extends HttpError {
  constructor(message = "Subscription expired") {
    super(402, message);
  }
}
```

Thrown `HttpError`s are logged at `verbose` level — they're deliberate control flow, not defects, so they don't pollute your error logs.

## Mapping errors you don't own

Libraries throw their own error types — the Mongo driver, payment SDKs, queue clients. Register a handler for the class, typically from the [`bootHttp` hook](01-intro.md#project-boot-hook-boothttp) (the `Server` constructor option that runs with the live app):

```js
import { MongoServerError } from "mongodb";

const server = new Server({
  ...folderConfig,
  bootHttp: async (app) => {
    if (!app.httpServer) {
      throw new Error("bootHttp ran without a live httpServer");
    }
    app.httpServer.registerErrorHandler(MongoServerError, (err) =>
      err.code === 11000
        ? { status: 409, body: { message: "Already exists" } }
        : null, // null = "not mine after all" → try the next entry
    );
  },
});
```

:::tip Register them in tests too
The framework builds its own server for tests and does not read your `Server`
options, so handlers registered here are absent under test — the 409 above comes
back as a 500. Pass the same `bootHttp` to
[`configureTestServer`](../09-testsing.md#production-http-wiring-boothttp) in
your test setup.
:::

The handler contract:

- **Signature**: `(err, req) => { status, body, headers? } | null` — async is fine, the result is awaited.
- `err` is typed as an instance of the class you registered — `err.code` autocompletes, no casts.
- `req` is the same request the route handler had — `req.appInfo.request`, `req.appInfo.i18n`, etc.
- Return `{ status, body }` to produce the response, with optional `headers` (the framework sends it — handlers never touch `res`, so double-send protection and logging stay in one place).
- Return `null`/`undefined` to pass the error to the next entry.
- `registerErrorHandler` returns an **unregister function** — handy in tests.
- Third argument `{ logLevel }` controls how the handled error is logged (default `warn`):

```js
app.httpServer.registerErrorHandler(
  StripeCardError,
  (err) => ({ status: 402, body: { message: err.declineReason } }),
  { logLevel: "verbose" },
);
```

If a handler itself throws, the framework logs it (with the stack) and falls back to the 500 — a broken error handler can never crash the request pipeline.

Handler-side types, if you want to extract the function:

```ts
import type { ErrorHandlerFn, ErrorHandlerResult } from "@adaptivestone/framework/services/http/builtinErrorHandlers.js";
```

### Reading the request in a handler

`req` is the full framework request, so a handler can build responses from everything the route knew — path params, validated body and query, locale, client IP. A fuller example: a task-creation route hits a unique index, and the handler turns the raw driver error into an answer that names what collided and where:

```js
// Route: POST /project/:projectId/tasks?notify=email
//        request: object({ title: string().required() })
//        query:   object({ notify: string() })
// Model: title has a unique index per project → E11000 on duplicates.

app.httpServer?.registerErrorHandler(MongoServerError, (err, req) => {
  if (err.code !== 11000) {
    return null; // other driver errors → next entry (→ 500 fallback)
  }

  // Which unique field collided — E11000 carries it in `keyValue`.
  const [field] = Object.keys(err.keyValue ?? {});

  return {
    status: 409,
    body: {
      // Translated for the request's locale; `defaultValue` is what the
      // client gets when your locale files do not define the key.
      message:
        req.appInfo.i18n?.t("errors.taskExists", {
          defaultValue: "Task already exists",
        }) ?? "Task already exists",
      field,                                    // "title"
      projectId: req.params.projectId,          // raw path param (string)
      attempted: req.appInfo.request?.title,    // validated body value
      notify: req.appInfo.query?.notify ?? null, // validated query value
    },
  };
});
```

What's available on `req`:

| Source | What it is | Caveat |
| --- | --- | --- |
| `req.params` | Path params (`:projectId`) | Raw **strings**, never validated — declare a route [`params:` schema](02-routes.md#params) and read `req.appInfo.params` instead |
| `req.appInfo.params` | Validated, coerced path params | Only set when the route declares a `params:` schema |
| `req.appInfo.request` | Validated, cast request body | Only set when the route declares a `request:` schema — guard with `?.` in handlers registered for many routes |
| `req.appInfo.query` | Validated, cast query string | Same — needs a `query:` schema |
| `req.appInfo.i18n` | `t()` + detected `language` | Present on framework routes; typed optional |
| `req.appInfo.ip` | Client IP (proxy-aware) | From the global IP detector |
| `req.appInfo.user` | Authenticated user document | Only on routes running the auth middleware (`GetUserByToken`) |
| `req.method`, `req.path`, `req.headers`, … | Anything Express exposes | — |

One design boundary to keep in mind: the handler decides the **response**; the framework does the sending and the logging. If you find a handler reaching for `res` or a logger, that logic probably belongs in the route handler's own `try/catch` instead.

## Errors from middleware

Since 5.5, an error thrown in a middleware goes through the same registry as an error from a route handler. Before, any middleware error became a 500. The built-in middleware throw coded errors:

| Middleware | Error | Status | `error` |
| --- | --- | --- | --- |
| `Auth` | `UnauthorizedError` | 401 | `AUTH001` |
| `Role`, no user | `UnauthorizedError` | 401 | `AUTH001` |
| `Role`, no matching role | `ForbiddenError` | 403 | `NO_ACCESS` |
| `RateLimiter` | `HttpError` (with `Retry-After`) | 429 | `TOO_MANY_REQUESTS` |

So one handler can reshape the framework's answers along with your own. For example, every 401, including the one from `Auth`:

```js
app.httpServer.registerErrorHandler(UnauthorizedError, (err, req) => ({
  status: 401,
  body: { error: err.code ?? "UNAUTHORIZED", message: err.message, loginUrl: "/login" },
}));
```

Your own middleware can reject the same way; see [Middleware › Rejecting a request](./03-middleware.md#rejecting-a-request).

## Matching order

Entries are matched by `instanceof` in **registration order — not by class specificity**. Your handlers always run before the built-ins, so you can intercept or override anything, including the built-ins themselves.

:::warning
An early handler for a base class shadows later handlers for its subclasses. If you register a handler for `HttpError` and later one for `NotFoundError`, the `HttpError` one wins for every `NotFoundError` thrown — it was registered first and `NotFoundError instanceof HttpError` is true. Register the specific classes first, or branch inside one handler.
:::

## Built-in: the Mongoose validation safety net

The recommended practice is to mirror model constraints in your route schema — a `maxLength: 50` in the model should have a `.max(50)` in the route's `request:` schema, so bad input fails fast with a clean, translated 400 (see [Validation](02-routes.md#validation)).

But when a constraint slips through, `doc.save()` throws a Mongoose `ValidationError`, and a built-in registry entry catches it:

- If **every** failing model path is a field the client actually sent (a key of the validated `request:`/`query:` input), the client gets `400 {"message": "Validation failed", "errors": {"name": ["..."]}}` — the same shape as route validation errors — and the framework logs a `warn`: your route schema is missing a constraint worth mirroring.
- If **any** failing path is internal or renamed (the client sent `name`, the model field is `userName`), it stays an honest **500**. Model field names are never leaked to the client, and a server-side data bug is never blamed on the client.

Each message is **rebuilt from the validation kind and the schema constraint** — `maxlength` → `"Must be at most 255 characters"`, a `Number` cast failure → `"Must be a number"`, `enum` → `"Must be one of: …"` — and **never includes the value the client submitted**. Mongoose's own default messages interpolate that value (a phone number, a password pasted into the wrong field), which would otherwise leak it into the response and the log. For the same reason a *custom* message set on the model (`maxLength: [50, 'Name too long']`) is **not** passed through — it's rebuilt generically, since a custom string can't be told apart from a templated default that embedded the value. The `warn` log line for a handled error is sanitized the same way; a failure that stays a 500 logs the original error in full. These fallback messages are plain English and not translated; put user-facing, i18n wording on the route schema.

Note this covers Mongoose *validation* errors only. A duplicate-key violation (`E11000`) is a `MongoServerError` from the driver, not a `ValidationError` — map it yourself as shown above if you want a 409. A standalone **cast** failure is a `CastError`, a sibling of `ValidationError` rather than a subclass, so it has its own built-in — described next.

:::tip
The safety net is a fallback, not the contract. Route schemas are the API's source of truth: they produce field-accurate, i18n-translated errors under the names the client knows. The safety net exists so a missed constraint degrades to a useful 400 instead of a mystery 500.
:::

## Built-in: the Mongoose cast safety net

The classic version of this is a path param handed straight to a model:

```js
async getPerson(req, res) {
  // `req.params.id` is a raw, unvalidated string
  const person = await this.app.getModel("Person").findById(req.params.id);
  return res.json({ data: person });
}
```

`GET /person/abc` cannot be cast to an ObjectId, so Mongoose throws a `CastError`. A `CastError` is **not** a `ValidationError` — they are siblings — so the validation safety net above structurally cannot see it. A built-in entry handles it separately:

- If the rejected value is one the **client actually supplied** — matched by value against the path params and the validated `request:`/`query:` input — the client gets `400 {"message": "Validation failed", "errors": {"id": ["Must be a valid id"]}}`, keyed by the public input name, logged at `warn`.
- If the value was **computed server-side**, nothing matches and it stays an honest **500** at `error` level. A bug in your own code is never blamed on the caller.

The message is rebuilt from the cast *kind* (`Must be a valid id`, `Must be a number`, `Must be a valid date`), so neither the rejected value nor the internal model path (`_id`) reaches the response — and the `warn` log line is sanitized the same way.

:::tip
This is a floor, not a design. Declaring a [`params:` schema](02-routes.md#params) rejects the same request earlier, with your own wording, i18n, and coercion — and it documents the constraint in your [OpenAPI output](../17-openapi.md). Reach for the floor only where you haven't got round to a schema yet.
:::

## What still becomes a 500

- Any error no registry entry claims (including `null` returns all the way down).
- A registry handler that throws while handling.
- Mongoose validation failures on internal/renamed fields (see above).
- Mongoose cast failures on server-computed values (see above).

All of these are logged at `error` level with the original error, so the details are in your logs — the client only ever sees the generic message.


---


# Document 11: 07-logging

<!-- Source: 07-logging.md -->

# Logging

The framework uses the [Winston](https://github.com/winstonjs/winston) logger as the main subsystem for logging.

You can adjust different transports (console and Sentry are available by default) and add your own transport with your own parameters.

The framework provides a basic initialization of Winston so you can easily use it out of the box, but you still have the ability to adjust it as you want.

## Logging Levels

[RFC5424](https://datatracker.ietf.org/doc/html/rfc5424) defines logger levels. Higher levels will include messages from lower levels. In other words, if you set the ‘warn’ level, the logger will report ‘error’ as well, but will not report the ‘debug’ level.

You can read more about levels in the [Winston levels documentation](https://github.com/winstonjs/winston#logging-levels).

But in short, these are the default levels:

```js
{
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  verbose: 4,
  debug: 5,
  silly: 6
}
```

## API

Each class has access to the logger instance via:

```js
this.logger;
```

```js
this.logger.error("error message");
this.logger.warn("warn message");
this.logger.info("info message");
this.logger.http("http message");
this.logger.verbose("verbose message");
this.logger.debug("debug message");
this.logger.silly("silly message");
```

:::tip
Please note that `this.logger` is an instance of `winston.logger`, and you can use any methods from it.
:::

## Default Transports

By default, the framework provides two transports: **console** and **Sentry**

## Configuration

We try to keep the configuration simple and powerful - you are able to enable/disable loggers and add your own with all available options passed to the transport.

Configuration files are located in ‘config/log.ts’.

```js
export default {
  transports: [
    {
      transport: "sentry", // transport name (specail name or npm package name)
      transportOptions: {
        // options that will be passed to the transport instance
        level: process.env.LOGGER_SENTRY_LEVEL || "info",
      },
      enable: process.env.LOGGER_SENTRY_ENABLE || false, // whether the transport is enabled or not
    },
    {
      // ....
    },
    /// more transports
  ],
};
```

The config contains a “transports” array. Each transport can be included in the logger.

The transport **name** is an npm package name that the framework will require. You can use any transport from NPM.

The **transportOptions** field contains the transport options - you can pass any options here for the transport. Please refer to the transport documentation.

And finally, the **enable** field will enable/disable modules for the logger. You can check [“NODE_ENV” in the config documentation](02-configs.md#node_env) to learn more about how you can use it depending on your environment.

## Redacting sensitive fields

The values of log fields named in the `redact` list of `config/log.ts` are replaced with `[REDACTED]` before any transport sees them: console, Sentry and your own transports. Names match in any letter case and at any depth, including inside arrays. The default list is:

```js
redact: ["authorization", "cookie", "password", "secret", "token"],
```

```js
logger.info("Login code sent", { email, token: "abc123", user: { Password: "p" } });
// → email is logged; token and user.Password are logged as "[REDACTED]"
```

- **Only fields are redacted, never the message text.** Write `logger.info("Code sent", { code })`, not ``logger.info(`Code sent: ${code}`)``.
- **Your list replaces the default one.** To add names, keep the defaults: `redact: ["authorization", "cookie", "password", "secret", "token", "code"]`. An empty list (`redact: []`) turns redaction off.
- **Your objects are not changed.** The logger redacts a copy, so the object you pass to `logger.info` keeps its values.
- **Plain objects and arrays are inspected.** Error objects, dates and class instances are logged as they are.

This replaces filtering log lines yourself. Filtering in Sentry's `beforeSend` still applies to errors Sentry captures on its own, outside the logger.

## Sentry transport 

For Sentry, we assume it is already configured in the project and we will reuse the existing setup. If Sentry is not present in the system, the framework will display a message indicating that this feature is only available when Sentry is configured.

## Add Your Own Transport

Adding your own transport is a simple process.

```js
npm i ${WINSTON_TRANSPORT_PACKAGE}
```

Then add it to the ‘config/log.ts’ config file.

```js
export default {
  transports: [
    {
      // .....
      // some already existing transports
    },
    {
      // ....
    },
    {
      transport: "WINSTON_TRANSPORT_PACKAGE",
      transportOptions: {
        // options that will be passed to the transport instance
        // .... your transport options
      },
      enable: true,
    },
  ],
};
```

:::tip

Feel free to use environment variables in your transport config as well. That simplifies working with multiple environments.

:::

## Console Output for Logger

Console loggers act in a customized way to provide more verbose info. The default console output is constructed as:

`(${process.pid}) ${info.label}  ${info.timestamp}  ${info.level} : ${info.message}`

Where:
“process.pid” - the PID of the Node process. Useful in a cluster environment.
“info.label” - the label of the place. More info below.
“info.timestamp” - the date of the event.
“info.level” - the log level (“error”, ”warn”, etc.).
“info.message” - the message that was passed to the logger (e.g., `this.logger.info(“this is a message”)`).

### info.label

Inside the base class, we have a method [“loggerGroup”](04-base.md#api) that is used as the first part of the info message generation. This is useful for grouping messages like “controllers”, ”models”, etc.

The framework uses the following groups: “command”, “connector”, “controller”, “model”, and “CLI\_”.

:::tip
Feel free to introduce your own groups.
:::

The second part is generated by the base class function “getConstructorName”, which by default grabs the constructor name and adds it to the info string. You can overwrite this method for your classes.

Example:

```
(15950)  [modelCoin]  2021-10-18T11:17:54.746Z  verbose : Model have no hooks
```

Here:

```
(15950) - process PID
[modelCoin] -  info message ("model" - group, "Coin" - model name)
2021-10-18T11:17:54.746Z - time
verbose - level
Model have no hooks - message
```

### Environment Variables

#### Sentry Transport

The framework's Sentry transport reuses the Sentry SDK your app already initialized — it does **not** read a DSN itself. Configure the DSN in your own `Sentry.init({ dsn: ... })` at startup (the project template uses the `LOGGER_SENTRY_DSN` env var there by convention). The framework reads only:

**LOGGER_SENTRY_LEVEL** - the log level that should go into Sentry. Default: 'info'.

**LOGGER_SENTRY_ENABLE** - enable or disable the Sentry logger. Default: 'false'.

#### Console Transport

**LOGGER_CONSOLE_LEVEL** - the log level. Default: 'silly' (includes all).

**LOGGER_CONSOLE_ENABLE** - enable or disable the console logger. Default: 'true'.


---


# Document 12: 08-i18n

<!-- Source: 08-i18n.md -->

# i18n

No modern app can avoid multi-language support. The framework supports internationalization out of the box.

Two things are worth separating before you start:

- **Your copy** — messages your controllers, validation schemas and email templates produce. You choose the keys and you ship the translations.
- **Framework messages** — the sentences the built-in middleware and the built-in auth controller return. Each one already carries its English text in code, so it reads correctly with no translation setup at all; you can [override any of them](#translating-framework-messages) key by key.

Translation itself is powered by the [i18next](https://www.i18next.com/) library, which is an [optional peer dependency](#i18next-is-optional) — install it only if you actually translate.

:::info Changed in 5.4

Before 5.4, a framework message whose key was missing from your locale files was answered with the raw key (`auth.messageSome`), and `i18next` was a mandatory dependency. Now every framework message travels with an English default, so a missing key reads as English, and `i18next` is optional. A key that **is** present in your locales still wins, so existing translations are unaffected.

:::

### Middlewares

The framework provides an I18n middleware that runs on each HTTP request.

## Detectors

As we are talking about languages, we need some way for the codebase to understand what language the user should use.

This feature is called detectors.

Order of detection:

- X-Lang header
- Query
- User

### X-Lang Header Detector

This detector will parse the “X-Lang” header on the request to detect the user's language. The frontend should add the user's language here (“en”, ”fr”, etc.), and if the backend supports it, the app will use the given user language.

:::tip
“xLang” is the preferred way to work with languages in the framework.
:::

Example for the frontend with Fetch:

```js
fetch("https://example.com/getSomething", {
  headers: {
    "X-Lang": "en", // Added language
  },
});
```
### Query Detector

The query is a simple detector. Just add the 'lookupQuerystring' parameter to your query string. 'lookupQuerystring' by default is **lng**, but you can change it as you want inside the config file.

```js
const res = await fetch("https://someUrl.com?lng=en");
```

### User Detector

The user detector tries to find an authorized user (provided by middleware) and grab the ‘locale’ field from this user.

### Adding Your Own Detector

At this time, you are not able to add your own detector. Please contact us if you need that option, and we will be happy to help you.

## Configuration

Please look at the ‘config/i18n.ts’ file for all configuration options. There are a limited number of options available.

```ts title="src/config/i18n.ts"
export default {
  enabled: true, // false → no i18next at all; every message is served in English
  preload: ["en", "ru"],
  supportedLngs: ["en", "ru"], // should be at least one supported
  fallbackLng: "en",
  saveMissing: false, // see "Finding what is left to translate" below
  debug: false,
  lookupQuerystring: "lng", // string to detect language on query
};
```

A language a detector reports that is not in `supportedLngs` is skipped and the next detector is tried, so `X-Lang: de` does not hide a supported `?lng=ru`. `fallbackLng` is used when no detector reports a supported language. A repeated query parameter (`?lng=en&lng=ru`) is ignored.

## Language Files

All files are JSON, and live in ‘\{localeCode\}/translation.json’ inside the folder you pass as `folders.locales` when you construct the `Server` (‘src/locales’ in the project template):

```
src/locales/
├─ en/
│  └─ translation.json
└─ ru/
   └─ translation.json
```

:::note

Backends besides files are not supported.

:::

:::note

Your locale folder is the **only** one that is loaded. The framework ships locale files for its own tests and for translators to start from, but they are not merged into your app — so a key you do not define is not silently taken from somewhere else. That is exactly why framework messages carry their English text in code.

:::

You can find detailed documentation about JSON files in the [i18next JSON documentation](https://www.i18next.com/misc/json-format).

## Translating framework messages

The built-in middleware, the built-in auth controller (its validation messages included) and the shipped account emails all produce their text through a **key plus an in-code English default**:

- If your locale file for the detected language defines the key, your wording is used.
- If it does not, the English default is used — never the bare key.

So you translate only what you care about, one key at a time, and you never have to copy a full catalog into your project to keep responses readable.

Keys are plain nested JSON — `middleware.auth.notLoggedIn` is `middleware` → `auth` → `notLoggedIn`:

```json title="src/locales/ru/translation.json"
{
  "middleware": {
    "auth": {
      "notLoggedIn": "Пожалуйста, войдите в приложение"
    },
    "rateLimiter": {
      "tooManyRequests": "Слишком много запросов"
    }
  },
  "auth": {
    "errorUPValid": "Неверный логин или пароль",
    "emailValid": "Некорректный email"
  }
}
```

A request with `X-Lang: ru` now gets those four sentences in Russian; everything else still answers in English.

:::note

Status codes and machine-readable fields never change with the language. The auth 401 still carries `error: "AUTH001"`, and a login to an unverified account `error: "EMAIL_NOT_VERIFIED"`, whatever `message` says — branch on the code, not on the prose. Your own errors can follow the same pattern: an `HttpError` with `code` and `i18nKey` answers `{ error, message }` with the message translated (see [Error codes and translated messages](./06-Controllers/04-error-handling.md#error-codes-and-translated-messages)).

:::

### HTTP keys

The framework's own responses, before and after your handlers run:

| Key | Status | Default (English) |
|---|---|---|
| `http.notFound` | 404 | `Not found` |
| `http.methodNotAllowed` | 405 | `Method not allowed` |
| `http.malformedUrl` | 400 | `Malformed URL` |
| `http.unsupportedContentType` | 415 | `Unsupported Content-Type. Expected one of: {{types}}` |
| `http.validationFailed` | 400 | `Validation failed` |
| `http.serverError` | 500 | `Something went wrong. Please try again later.` |

In `http.unsupportedContentType`, keep the `{{types}}` placeholder: the framework fills it with the content types the route accepts.

### Middleware keys

| Key | `error` | Default (English) |
|---|---|---|
| `middleware.auth.notLoggedIn` | `AUTH001` | `Please login to application` |
| `middleware.role.userRequired` | `AUTH001` | `User should be provided` |
| `middleware.role.noAccess` | `NO_ACCESS` | `You do not have access` |
| `middleware.rateLimiter.tooManyRequests` | `TOO_MANY_REQUESTS` | `Too Many Requests` |
| `middleware.requestParser.entityTooLarge` | — | `Request entity too large. Your upload exceeds the allowed size or count limits.` |
| `middleware.requestParser.parseError` | — | `Error to parse your request. You provided invalid content type or content-length. Please check your request headers and content type.` |

The rate limiter's **500** `RateLimiter error` is deliberately not translatable: it reports a misconfigured limiter to operators, not something the caller can act on.

Your own middleware get the same behavior from the [`translate()` helper](./06-Controllers/03-middleware.md#translatable-messages).

### Auth controller, validation and email keys

| Key | Default (English) |
|---|---|
| `auth.emailProvided` | `Email must be provided` |
| `auth.emailValid` | `Email is not valid` |
| `auth.passwordProvided` | `Password must be provided` |
| `auth.passwordTooShort` | `Password must be at least {{min}} characters` |
| `auth.passwordTooLong` | `Password must be at most {{max}} characters` |
| `auth.passwordRecoveryTokenProvided` | `Password recovery token must be provided` |
| `auth.nickNameValid` | `Nick name is not valid,only a-z,A-Z,0-9` |
| `auth.nameValid` | `Name is not valid` |
| `auth.errorUPValid` | `User/password not valid` |
| `auth.nicknameExists` | `User with such nickname already exists` |
| `auth.recoveryEmailSent` | `If an account exists for this address, a recovery email has been sent.` |
| `auth.verificationEmailSent` | `If an account exists for this address, a verification email has been sent.` |
| `email.notVerified` | `Your email is not verified` |
| `email.registered` | `User with such an email already registered` |
| `email.alreadyVerifiedOrWrongToken` | `Your email is already verified or your verification token is wrong` |
| `email.passwordRecovery` | `Recovery password` |
| `email.passwordChanged` | `Password changed` |
| `email.emailConfirm` | `Email confirmation` |
| `email.verify` | `Verify email` |
| `email.verifyInstructions` | `To verify your email address, follow the link:` |
| `email.greeting` | `Dear user` |
| `password.wrongToken` | `Password recovery token is not valid` |

Since 5.4.1, built-in registration and password reset accept 15–128 Unicode code points by default, including spaces. Customize these limits with `auth.passwordPolicy.minLength` and `maxLength`. Existing login passwords remain valid. The two password-length keys above replace `auth.passwordValid`; direct model writes and custom password endpoints must enforce their own policy.

Some of the `email.*` entries are API responses, and some are the actual text of the account emails the framework sends — subject, heading and body of the recovery and verification mails ([which template uses which](./12-email.md#templates-the-framework-ships)) — so overriding those changes what lands in the mailbox, not just what the API answers.

:::info Changed in 5.4

The verification mail was hardcoded Russian and emitted no keys at all before 5.4. It is now English by default and translatable through `email.emailConfirm`, `email.verify`, `email.verifyInstructions` and `email.greeting`, like every other framework message. (`email.greeating` — the pre-5.4 typo spelling — still works as a fallback until v6; translate `email.greeting` going forward.)

:::

### Finding what is left to translate

Set `saveMissing: true` in ‘config/i18n.ts’ during development. Every framework message that is rendered without a matching key in your locale file is written to ‘\{localeCode\}/translation.missing.json’ — with its English default as the value. Exercise the flows you care about, then use that file as the starting point for a translator and merge the result into ‘translation.json’.

This is an i18next feature, so it needs the [optional packages](#i18next-is-optional) installed. Keep `saveMissing: false` in production: it writes files on request.

## i18next is optional

`i18next` and `i18next-fs-backend` are **optional peer dependencies**, the same treatment `@redis/client`, `yup` and `oxc-parser` already get. A fresh install has neither, and that is a perfectly valid state: every framework message is served in English, and requests continue to work.

Install both once you actually translate something:

```bash
npm i i18next i18next-fs-backend
```

Without them, the first request that needs a translator logs **one** warning naming both packages and the `enabled` flag, then falls back for the rest of the process — it does not repeat per request and it does not fail the request. `enabled: true` (the default) therefore no longer implies the packages are present.

Setting `enabled: false` is the explicit way to say "this app is English-only": no i18next is loaded and every framework message still reads as English.

:::info Fixed in framework 5.4.1

Framework 5.4.1 removes mandatory i18next type imports from the core declarations. Consumers can import `helpers/appInstance.js`, request types, validation and user email APIs with `skipLibCheck: false` while neither `i18next` nor `i18next-fs-backend` is installed. These APIs use the [translation types](#translation-types) described below.

Framework **5.4.0** reports `Cannot find module 'i18next'` during declaration checking when the package is absent. Until you upgrade to **5.4.1 or newer**, use `skipLibCheck: true` or install `i18next` as a workaround. `skipLibCheck: true` remains an application choice for faster compilation; the fix removes the need to enable it specifically for optional i18n.

:::

## API

The framework provides easy integration for controllers. You can grab the i18n instance with:

```js
req.appInfo.i18n;
req.appInfo.i18n.language; // current language
req.appInfo.i18n.t("some.phrase"); // translate some phrase https://www.i18next.com/overview/api#t
```

Pass a default of your own so a missing key never reaches a client, exactly like the framework does:

```js
req.appInfo.i18n.t("order.cancelled", { defaultValue: "Order cancelled" });
```

### Translation types

Since 5.4.1, `TI18n` describes the translator available on requests and returned by `getI18nForLang()`: `{ t: TranslationFunction; language: string }`. Both types, along with `TranslationOptions` and `I18nBaseInstance`, are exported from `@adaptivestone/framework/services/i18n/types.js`. The existing `TI18n` exports from `services/i18n/I18n.js` and `services/http/middleware/I18n.js` remain available.

```ts
import type { TI18n } from "@adaptivestone/framework/services/i18n/types.js";

function orderCancelled(i18n: TI18n): string {
  return i18n.t("order.cancelled", { defaultValue: "Order cancelled" });
}
```

Ordinary calls return `string` and accept string keys, fallback key arrays, an options object with interpolation values, or a positional default (`t(key, "Default", options)`). Calls requesting `returnObjects` or `returnDetails` return `unknown`; narrow the result before using it. With translations disabled or the peers absent, the fallback returns your default, or the last key in a key array, and does not interpolate values.

The shared types do not include i18next's resource-derived key checking or selector API. Consumers needing those features or additional instance methods can use the [full i18next API](#full-i18next-api).

:::tip

You can pass controller `request` / `query` error messages as i18n keys (or plain strings). The framework processes them with i18next before sending the response, regardless of which validator library produced the error — Yup, Zod, Valibot, ArkType, or a custom Standard Schema validator.

```js
class SomeController extends AbstractController {
  get routes() {
    return {
      post: {
        "/login": {
          handler: this.postLogin,
          request: yup.object().shape({
            email: yup.string().email().required("auth.emailProvided"), // <-- look here i18n
          }),
        },
      },
    };
  }
}
```

A key of yours that no locale file defines is answered as the key itself — the in-code default is a framework-message feature, and your schema has nowhere to put one. Either define the key or use a plain sentence as the message.

### Interpolation

Validators that produce parameters (yup's `min` / `max` / `length`, etc.) forward those parameters to i18next, so locale strings can use `{{placeholder}}` syntax:

```js
// schema
request: yup.object().shape({
  password: yup.string().min(8, "auth.passwordTooShort").required(),
});

// locales/en/translation.json
// "passwordTooShort": "Password must be at least {{min}} characters"

// response when password is too short:
// { "errors": { "password": ["Password must be at least 8 characters"] } }
```

:::


## Direct usage.

Sometimes you may want to use i18n outside of HTTP requests (such as for emails, WebSockets, etc.). For that purpose, frameworks provide an easy way to interact with i18n using the same configuration (translations, languages, etc.).

App instance provides lang services for you

```ts
import { appInstance } from '@adaptivestone/framework/helpers/appInstance.js';

const i18nService = await appInstance.getI18nService();
const i18n = await i18nService.getI18nForLang(lang);
```

The returned translator provides `language` and `t()` using your i18n configuration.

If `i18next` is not installed (or `enabled` is `false`), you still get a working `t()` — it returns the `defaultValue` you pass, or the key when you pass none.

### Full i18next API

`getI18nBaseInstance()` returns the initialized i18next instance. Since 5.4.1, its public type is `I18nBaseInstance`, exposing translation, cloning and language-detection methods. If you need additional vendor APIs, install [both optional packages](#i18next-is-optional), import i18next's type in your application and assert it at this boundary:

```ts
import type { i18n as I18nextInstance } from "i18next";
import { appInstance } from "@adaptivestone/framework/helpers/appInstance.js";

const service = await appInstance.getI18nService();
const base = (await service.getI18nBaseInstance()) as I18nextInstance;
const translateEnglish = base.getFixedT("en");
```

The returned runtime object is unchanged. `getI18nBaseInstance()` throws when the optional packages are missing. `getI18nBaseInstanceIfAvailable()` returns `null` for missing packages and logs one warning; other initialization failures still throw.

### Validation outside HTTP

`ValidateService.validate` accepts an optional `i18n` argument. Pass it to get the same auto-translation the HTTP path provides; omit it to receive raw keys (useful in workers / RPC where you'd rather forward structured errors than translated text).

```ts
import { appInstance } from "@adaptivestone/framework/helpers/appInstance.js";
import ValidateService from "@adaptivestone/framework/services/validate/ValidateService.js";
import { ValidationError } from "@adaptivestone/framework/services/validate/ValidationError.js";

async function processQueueMessage(payload, schema) {
  const i18nService = await appInstance.getI18nService();
  const i18n = await i18nService.getI18nForLang("en");

  try {
    return await new ValidateService(appInstance, schema).validate(payload, i18n);
  } catch (err) {
    if (err instanceof ValidationError) {
      // err.message → translated wire-shape; err.issues → structured
      logger.error({ issues: err.issues }, "queue payload invalid");
    }
    throw err;
  }
}
```


---


# Document 13: 09-testsing

<!-- Source: 09-testsing.md -->

# Testing

The framework supports Node.js's built-in test runner and Vitest. The built-in
runner is the default for new projects: it executes TypeScript test files
natively, has no additional test-runner dependency, and integrates with the
framework's shared MongoDB and per-test isolation helpers. Node.js 24 remains
the minimum supported runtime; the framework's own test infrastructure and CI
run on Node.js 26.

Vitest remains a fully supported alternative. Choose the runner that best fits
the project's existing tooling and plugins; the native runner is not presented
as an execution-speed upgrade.

Name tests `*.test.ts` or `*.test.js` and keep them next to the file they cover.
For example, test `src/controllers/Auth.ts` in
`src/controllers/Auth.test.ts`.

## Install the test database

The framework loads `mongodb-memory-server` lazily, so applications that use
the supplied in-memory MongoDB global setup must install it directly:

```bash
npm install --save-dev mongodb-memory-server
```

Redis is optional during tests. When `REDIS_URI` is configured, the framework
uses a fresh namespace for each test and clears it afterward.

## Node.js test-runner setup

Node.js runs every test file in a separate process. The framework therefore
splits its lifecycle into:

- a global setup that starts one MongoDB replica set for the complete run;
- per-file hooks that start and stop a framework server with a fresh database;
- per-test hooks that isolate the Redis namespace.

### Project test configuration

Keep project-specific test configuration in `src/tests/setup.ts`. This file can
set test folder locations or other environment required before the framework
server starts.

Create one preload file at `src/tests/setupNodeTest.ts`:

```ts
import './setup.ts';
import '@adaptivestone/framework/tests/setupNodeTest.js';
import './setupHooks.ts';
```

The runner preloads this file for every test file. Do not import it from each
individual test.

### Production HTTP wiring (`bootHttp`)

The framework builds the test server itself, so the `Server` options your
`src/index.ts` passes are not picked up automatically — including the
[`bootHttp` hook](06-Controllers/01-intro.md#project-boot-hook-boothttp).
Declare them with `configureTestServer` from `src/tests/setup.ts`, which loads
before the framework preload:

```ts title="src/tests/setup.ts"
import { configureTestServer } from '@adaptivestone/framework/tests/testHelpers.js';
import bootHttp from '../bootHttp.ts';

configureTestServer({ bootHttp });
```

Point it at the **same** function production uses, rather than re-registering
the wiring from a test hook: two copies drift, and the copy that drifts is the
one the tests trust. Without this, tests run against a server that never ran
that wiring at all — an error handler registered in `bootHttp` does not exist,
so a request that returns 409 in production returns 500 under test, with nothing
reporting the difference.

`folders` is not accepted here; the bootstrap owns those (see the
`TEST_FOLDER_*` variables below). Call `configureTestServer` at module scope,
before any hook boots the server — calling it afterwards throws, because a late
call cannot retroactively wire the server that is already running.

### Global MongoDB setup

Create `src/tests/globalSetupNodeTest.ts`:

```ts
export {
  globalSetup,
  globalTeardown,
} from '@adaptivestone/framework/tests/globalSetupNodeTest.js';
```

`globalSetup` starts MongoDB once and passes `TEST_MONGO_URI` to the child test
processes. `globalTeardown` stops it after every test file has finished.

### Custom hooks

Project hooks can live in `src/tests/setupHooks.ts`:

```ts
import { after, afterEach, before, beforeEach } from 'node:test';
import {
  createDefaultTestUser,
  ensureTestServerReady,
} from '@adaptivestone/framework/tests/testHelpers.js';

before(async () => {
  // Root hooks registered by separate modules are siblings and may start
  // concurrently. Always await framework readiness before using app state.
  await ensureTestServerReady();
  await createDefaultTestUser();
});

after(async () => {
  // Clean up project-level test state.
});

beforeEach(async () => {
  // Prepare each test.
});

afterEach(async () => {
  // Clean up each test.
});
```

The framework hooks are already registered by `setupNodeTest.js`. Project hooks
should contain only application-specific preparation and cleanup.

Node.js does not serialize sibling root-level `before()` hooks registered by
different modules. A project root hook that reads config, models, `appInstance`,
or the HTTP server must call `await ensureTestServerReady()` first. The helper
and framework preload share one idempotent startup promise, so concurrent calls
wait for the same server instead of constructing two servers.

Setup used by only one test file should normally live inside the same
`describe()` as those tests. Suite-scoped hooks wait for the root framework
hook and do not accidentally affect unrelated suites.

### Validation messages and application locales

The framework test helper loads its built-in locale folder by default. It does
not automatically load the application's locale folder: set
`TEST_FOLDER_LOCALES` in `src/tests/setup.ts` when a suite specifically needs
rendered application copy.

Without that opt-in, **your own** message keys remain raw in HTTP 400 responses.
This is intentional for ordinary API tests—assert the stable key and status code
rather than translated prose that can change between locales. A copy-specific
test may point `TEST_FOLDER_LOCALES` at `src/locales`, but should do so before
`setupNodeTest.js` loads.

Messages the framework itself emits behave differently: since 5.4 they carry an
English default in code, so a built-in middleware rejection or a built-in auth
controller error reads as a proper English sentence under test whatever
`TEST_FOLDER_LOCALES` points at — it can never come back as a bare key. Assert
the status code and the machine-readable `error` field on those; asserting the
English prose ties the test to wording you do not own.

### Package scripts

Use a small command for local tests and watch mode. Keep coverage and reporters
in the CI command so ordinary development runs stay fast:

```json
{
  "scripts": {
    "test": "node --import=./src/tests/setupNodeTest.ts --test --test-global-setup=./src/tests/globalSetupNodeTest.ts \"src/**/*.test.ts\"",
    "t": "node --import=./src/tests/setupNodeTest.ts --test --watch --test-global-setup=./src/tests/globalSetupNodeTest.ts \"src/**/*.test.ts\"",
    "test:ci": "mkdir -p coverage && node --import=./src/tests/setupNodeTest.ts --test --experimental-test-coverage --test-coverage-exclude=\"src/**/*.test.ts\" --test-coverage-exclude=\"src/tests/**\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=75 --test-global-setup=./src/tests/globalSetupNodeTest.ts --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=coverage/junit.xml --test-reporter=lcov --test-reporter-destination=coverage/lcov.info \"src/**/*.test.ts\""
  }
}
```

Run the suite once:

```bash
npm test
```

Run it in watch mode:

```bash
npm run t
```

Run the CI configuration with coverage thresholds and LCOV output:

```bash
npm run test:ci
```

The example thresholds are 80% for lines, 80% for branches, and 75% for
functions. These are enforcement flags: a below-threshold run exits with code
1 even when multiple reporters are enabled. Adjust them deliberately as the
project grows. LCOV is written to `coverage/lcov.info`, and JUnit test results
are written to `coverage/junit.xml`.

Native global setup, whole-module mocks, and test coverage remain experimental
Node.js test-runner surfaces. Pin the test runtime in CI rather than following
an unbounded `latest` release.

## Running tests with Bun

Bun 1.4.0 or newer runs the same test files and the same preload. Bun
implements the `node:test` API, but not Node's test-runner command line, so
the run is configured with different flags:

| Node.js | Bun |
| --- | --- |
| `node --test` | `bun test` |
| `--import=./src/tests/setupNodeTest.ts` | `--preload ./src/tests/setupNodeTest.ts` (the same file) |
| One process per test file | `--isolate`: a fresh module registry per file, so each file boots its own server as under Node |
| `--test-timeout=10000` | `--timeout=10000` |
| `--test-global-setup=./src/tests/globalSetupNodeTest.ts` | No equivalent: start MongoDB yourself and pass `TEST_MONGO_URI` |

`TEST_MONGO_URI` must contain the placeholder `__DB_TO_REPLACE__`; each test
file replaces it with its own database name. This script starts an in-memory
replica set unless `TEST_MONGO_URI` is already set (for example, by CI or Docker
Compose):

```bash title="scripts/bun-test.sh"
#!/usr/bin/env bash
# Run the test suite with Bun. Bun has no global-setup hook, so this script
# starts MongoDB itself unless TEST_MONGO_URI is already set.
set -euo pipefail

if [ -z "${TEST_MONGO_URI:-}" ]; then
  URI_FILE="$(mktemp)"
  MONGO_URI_FILE="$URI_FILE" bun -e '
    import { writeFileSync } from "node:fs";
    import { MongoMemoryReplSet } from "mongodb-memory-server";
    const rs = await MongoMemoryReplSet.create({
      replSet: { count: 1, storageEngine: "wiredTiger" },
    });
    await rs.waitUntilRunning();
    writeFileSync(process.env.MONGO_URI_FILE, rs.getUri("__DB_TO_REPLACE__"));
    process.on("SIGTERM", async () => { await rs.stop(); process.exit(0); });
    setInterval(() => {}, 1 << 30);
  ' &
  MONGO_PID=$!
  trap 'kill "$MONGO_PID" 2>/dev/null || true; rm -f "$URI_FILE"' EXIT
  for _ in $(seq 1 120); do
    [ -s "$URI_FILE" ] && break
    kill -0 "$MONGO_PID" 2>/dev/null || { echo "MongoDB failed to start" >&2; exit 1; }
    sleep 1
  done
  [ -s "$URI_FILE" ] || { echo "Timed out waiting for MongoDB" >&2; exit 1; }
  export TEST_MONGO_URI="$(cat "$URI_FILE")"
fi

bun test --isolate --timeout=10000 --preload ./src/tests/setupNodeTest.ts "${@:-src/}"
```

```json title="package.json"
{
  "scripts": {
    "test:bun": "bash ./scripts/bun-test.sh"
  }
}
```

Arguments are passed through, so `npm run test:bun -- src/controllers/Auth.test.ts`
runs one file.

### What works and what differs

- **Server readiness needs no extra code.** The preload's hooks finish before
  the first test runs, as under Node, so the first test can call the server
  right away. Do not add a top-level `await` to a preload: it delays the rest
  of that preload, and a `configureTestServer()` call placed after it arrives
  once the server has already booted, which throws.
- **`mock.module()` is not available.** Bun does not implement Node's
  `--experimental-test-module-mocks` ([oven-sh/bun#5090](https://github.com/oven-sh/bun/issues/5090)),
  so files that mock whole modules fail. Keep them on the Node run and exclude
  them from Bun with `--path-ignore-patterns='**/name.test.ts'`.
- **Compare Mongoose arrays as plain arrays.** Bun 1.4 reports a `Proxy`,
  which is what a Mongoose array is, as unequal in `assert.deepStrictEqual`.
  Spread it first: `assert.deepStrictEqual([...doc.tags], ['a', 'b'])`.
- **Keep coverage on the Node run.** Node's `--experimental-test-coverage` and
  threshold flags do not apply to `bun test`; Bun's own coverage uses
  different flags.

The framework runs its own suite this way on Bun 1.4.0 and the latest Bun in
CI. Node remains the primary runtime, so keep `npm test` as the main CI gate
and add the Bun run alongside it.

## Writing a Node.js test

Use `node:test` with the standard strict assertion module:

```ts
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { getTestServerURL } from '@adaptivestone/framework/tests/testHelpers.js';

describe('person', () => {
  it('creates a person', async () => {
    const response = await fetch(getTestServerURL('/person'), {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        name: 'Example Person',
        age: 30,
      }),
    });

    assert.equal(response.status, 200);
  });
});
```

The preload and global setup belong in the runner command, not in this file.

### Assertion plans

`t.plan(n)` counts assertions made through `t.assert` (and registered
subtests), not calls to a separately imported `node:assert` object. If a test
uses a plan, use `t.assert.*` for every assertion in that test:

```ts
import { it } from 'node:test';

it('returns one result', (t) => {
  t.plan(2);
  t.assert.strictEqual(1, 1);
  t.assert.deepStrictEqual([{ id: 1 }], [{ id: 1 }]);
});
```

Top-level `node:assert/strict` remains appropriate in tests that do not use
`t.plan()`.

### Migration traps from Jest and Vitest

- `assert.partialDeepStrictEqual(actual, expected)` applies subset semantics to
  arrays as well as objects. Assert the array length separately when extra
  elements must fail the test. For rejected errors, use the two-argument
  `assert.rejects(promise, errorPattern)` form. Compare selected Mongoose
  document fields or deliberately normalize the document before deep matching.
- Calling `mockImplementationOnce()` twice before the mock is invoked targets
  the same next call and the later registration replaces the earlier one. Pass
  explicit zero-based `onCall` indices when queuing several results:

  ```ts
  const load = t.mock.method(service, 'load');
  load.mock.mockImplementationOnce(() => firstResult, 0);
  load.mock.mockImplementationOnce(() => secondResult, 1);
  ```

- TypeScript represents `mock.calls[n].arguments` using one overload of an
  overloaded method, which may not be the overload exercised by the test.
  Prefer assertions at the public API boundary. When argument inspection is
  necessary, keep any `unknown`-first tuple cast local to that assertion.

## Framework and server access

Use `appInstance` for the initialized framework application:

```ts
import { appInstance } from '@adaptivestone/framework/helpers/appInstance.js';
```

Use `serverInstance` when a test needs lower-level access to the server:

```ts
import { serverInstance } from '@adaptivestone/framework/tests/testHelpers.js';
```

## HTTP endpoint testing

The framework starts each test server on a random available port.
`getTestServerURL()` returns the correct URL:

```ts
import assert from 'node:assert/strict';
import { it } from 'node:test';
import {
  defaultAuthToken,
  getTestServerURL,
} from '@adaptivestone/framework/tests/testHelpers.js';

it('rejects an invalid request', async () => {
  const response = await fetch(getTestServerURL('/some/endpoint'), {
    method: 'POST',
    headers: {
      authorization: defaultAuthToken,
      'content-type': 'application/json',
    },
    body: JSON.stringify({ invalid: true }),
  });

  assert.equal(response.status, 400);
});
```

Do not catch and discard `fetch()` errors in tests. A rejected request should
fail the test and preserve the original error.

## Default test user

The framework does not create a user automatically. Call
`createDefaultTestUser()` from project setup when a suite needs one:

```ts
import {
  createDefaultTestUser,
  defaultAuthToken,
  defaultUser,
} from '@adaptivestone/framework/tests/testHelpers.js';

const { user, token } = await createDefaultTestUser();
```

`defaultUser` and `defaultAuthToken` reference the values created by the helper.
Projects with a custom User model should implement their own creation helper and
use `setDefaultUser()` and `setDefaultAuthToken()`.

## Test helpers

The public helpers are exported from
`@adaptivestone/framework/tests/testHelpers.js`:

```ts
import {
  createDefaultTestUser,
  defaultAuthToken,
  defaultUser,
  ensureTestServerReady,
  getTestServerURL,
  serverInstance,
  setDefaultAuthToken,
  setDefaultUser,
} from '@adaptivestone/framework/tests/testHelpers.js';
```

- `getTestServerURL(path)` returns the active test server URL.
- `ensureTestServerReady()` waits for the initialized per-file server and is
  safe to call concurrently from application root hooks.
- `serverInstance` exposes the current test server.
- `createDefaultTestUser()` creates the framework's default User and token.
- `setDefaultUser()` and `setDefaultAuthToken()` support custom User models.

## MongoDB and Docker

The global setup uses `MongoMemoryReplSet` with one `wiredTiger` member. Each
test file receives a unique database, and the framework drops it during
teardown.

MongoDB publishes ARM64 binaries for Ubuntu, but not for every Debian release
used by official Node.js Docker images. Use the project's Ubuntu-based Node
image for GitLab and ARM64 Docker testing:

```text
registry.gitlab.com/adaptivestone/ubuntu-node:latest
```

When installation and tests run in separate CI jobs, use the same image for
both. This prevents Linux, libc, Node.js, and native dependency mismatches. The
current Ubuntu image supports MongoMemoryServer's automatic distro and MongoDB
version selection; application setup should not normally set
`MONGOMS_DISTRO` or `MONGOMS_VERSION`.

This template uses `npm install` in CI and production image builds. npm can
remove optional dependency records for other CPU architectures when it rewrites
`package-lock.json`; a later `npm ci` on another architecture may then reject
the otherwise valid lockfile. `npm install` repairs those optional records in
the CI workspace and avoids making an ARM-generated lockfile block an x64 job.

## GitLab CI

The following pipeline installs dependencies once and runs quality checks and
tests with the exact same Ubuntu/Node artifact:

```yaml
stages:
  - install
  - checks

default:
  # Keep dependency installation and execution on the same Ubuntu/Node image.
  # Ubuntu is also required for mongodb-memory-server binary availability.
  image: registry.gitlab.com/adaptivestone/ubuntu-node:latest

install:
  stage: install
  script:
    # Keep cross-platform optional dependencies resolvable after an ARM install.
    - npm install
  artifacts:
    paths:
      - node_modules/
    expire_in: 2 hours

quality:
  stage: checks
  needs:
    - install
  script:
    - npm run check

tests:
  stage: checks
  needs:
    - install
  services:
    - redis:latest
  variables:
    EMAIL_TRANSPORT: stub
    REDIS_URI: redis://redis
  script:
    - npm run test:ci
  coverage: '/[Aa]ll files[^|]*\|[^|]*\s+([\d\.]+)/'
  artifacts:
    when: always
    paths:
      - coverage/lcov.info
```

## GitHub Actions

GitHub-hosted Ubuntu runners can use Node.js 26 for the current test
infrastructure. Applications that deliberately verify the minimum supported
runtime may add a separate Node.js 24 job:

```yaml
name: Test

on:
  push:
    branches: ['*']

jobs:
  test:
    name: Node 26
    runs-on: ubuntu-latest
    permissions:
      contents: read

    services:
      redis:
        image: redis:latest
        ports:
          - 6379:6379

    env:
      LOGGER_CONSOLE_LEVEL: error
      REDIS_URI: redis://localhost

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v6
        with:
          node-version: '26'
          cache: npm

      - name: Install dependencies
        # ARM npm can omit optional x64 peers when it rewrites package-lock.json.
        run: npm install

      - name: Run tests
        run: npm run test:ci

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v6
        with:
          token: ${{ secrets.CODECOV_TOKEN }}

      - name: Upload test results to Codecov
        if: ${{ !cancelled() }}
        uses: codecov/codecov-action@v6
        with:
          report_type: test_results
          files: coverage/junit.xml
          token: ${{ secrets.CODECOV_TOKEN }}
```

## Mocking

Node.js provides function and method mocks through each test's `MockTracker`:

```ts
import assert from 'node:assert/strict';
import { it } from 'node:test';
import S3 from '../S3.ts';

it('validates credentials', (t) => {
  const validateCreds = t.mock.method(S3, 'validateCreds', () => true);

  assert.equal(S3.validateCreds(), true);
  assert.equal(validateCreds.mock.callCount(), 1);
});
```

Mocks created through `t.mock` are restored automatically after the test.
Whole-module ESM mocking is experimental in Node.js 26 and requires
`--experimental-test-module-mocks`; prefer method mocks or dependency injection
unless module replacement is necessary.

## Vitest setup

Vitest is a fully supported alternative runner and remains an optional peer
dependency. Install it in projects that choose it:

```bash
npm install --save-dev vitest
```

Configure the framework's public adapters instead of importing lifecycle
internals:

```ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globalSetup: [
      '@adaptivestone/framework/tests/globalSetupVitest.js',
    ],
    setupFiles: [
      './src/tests/setup.ts',
      '@adaptivestone/framework/tests/setupVitest.js',
      './src/tests/setupHooks.ts',
    ],
  },
});
```

`./src/tests/setup.ts` loads before the framework adapter here too, so
[`configureTestServer`](#production-http-wiring-boothttp) belongs in the same
place for both runners.

Vitest hooks and mocks should use Vitest's APIs. Do not load the Node.js and
Vitest adapters in the same test run. The framework does not require a Vitest
coverage provider; projects that enable Vitest coverage should install and
configure their preferred provider separately.


---


# Document 14: 10-cli

<!-- Source: 10-cli.md -->

# CLI

The CLI (Command Line Interface) is a part of the framework system that allows you to use the full power of the framework on the command line - manipulate data, import, export, etc.

The framework scans the directory for a list of commands and provides you with the ability to see what commands are available to run.

:::note

CLI commands are part of the [framework inheritance process](03-files-inheritance.md).

:::

## Run Command

Your project's CLI entry must forward the command result to the process exit
code. This makes failed migrations, code generation, and other commands fail CI
and deployment steps instead of appearing successful:

```ts
import Cli from "@adaptivestone/framework/Cli.js";
import folderConfig from "./folderConfig.ts";

const cli = new Cli(folderConfig);
const result = await cli.run();

process.exit(result ? 0 : 1);
```

You are able to create a group of commands by putting files in a directory. You can see ‘migration’ as an example of grouping commands.

```bash
# On the project level
node src/cli.ts {command}

# OR
npm run cli
```

The command path works the same way as in controllers. Any file will be parsed as a command, and folders will group commands together.
But unlike at the controller level, you are not able to change that behavior.

You are able to create a group of commands by putting files in a directory. You can see ‘migration’ as an example of grouping commands.

```js
commands / migration / create.ts; // migration/create command
commands / migration / migrate.ts; // migration/migrate command
```

## API

You are able to run a command from any place in the framework.

```js
this.app.runCliCommand(commandName: string, args: {}): Promise;
```

Where:
`commandName` - the name of the command that you want to start.
`args` - the arguments that you want to pass to the command.

## Creating Your Own Command

All passed arguments on the command line are parsed with the help of the `parseArgs` module.

```ts
import AbstractCommand from "@adaptivestone/framework/modules/AbstractCommand.js";
import type { CommandArgumentToTypes } from "@adaptivestone/framework/modules/AbstractCommand.js";

class CommandName extends AbstractCommand {
  static get description() {
    return "Some nice description of the command";
  }

  /**
   * You are able to add command arguments for parsing here.
   * https://nodejs.org/api/util.html#utilparseargsconfig
   */
  static get commandArguments() {
    return {
      id: {
        type: "string",
        description: "User ID to find the user",
      },
      email: {
        type: "string",
        description: "User email to find/create the user",
      },
      password: {
        type: "string",
        description: "New password for the user",
      },
      roles: {
        type: "string",
        required: true, // make sure that command will ask this from user
        description:
          "User roles as a comma-separated string (--roles=user,admin,someOtherRoles)",
      },
      update: {
        type: "boolean",
        default: false,
        description: "Update the user if they exist",
      },
    } as const; // <- this is important for type generation
  }

  static isShouldInitModels = true; // Default value. Can be omitted.

  /**
   * If true, then this command will get model paths with inheritance.
   */
  static isShouldGetModelPaths = true;

  /**
   * Return the name of the connection that you want to use.
   */
  static getMongoConnectionName(commandName, args) {
    return `CLI: ${commandName} ${JSON.stringify(args)}`;
  }

  async run() {
    // CommandArgumentToTypes will generate types from  commandArguments description
    const { id, email, password, roles, update } = this
      .args as CommandArgumentToTypes<typeof CommandName.commandArguments>;

    return new Promise((resolve, reject) => {});
  }
}

export default CommandName;
```

:::note Model commands wait for the database connection

`static isShouldInitModels = true` (the default) makes the framework load and initialize your models before the command runs **and wait for the MongoDB connection to be ready** — so your command's first query never races a not-yet-established connection (the cause of intermittent "buffering timed out" errors). You don't need to add your own connection-readiness check.

Set it to `false` for commands that don't touch the database (e.g. code generation, crypto helpers) so they start instantly without connecting. `static isShouldGetModelPaths` loads model _paths_ only (for type/path resolution) — it does not initialize models or open a connection.

:::

:::tip

For boolean types, we also support negative values (without a prefix).

```js
      update: {
        type: "boolean",
      },
```
```bash
node src/cli.ts ourCommand --update
```
Update Argument will by true

```bash
node src/cli.ts ourCommand --no-update
```
update argumant will be false 

:::

## Framework Commands

The framework comes with a few built-in commands.

### Migration

Migration commands allow you to migrate some data to another, or fill the database with some data.

The key point here is that a migration is executed only once per file.

:::tip

You can use migrations for different cases, not only to modify data in the database.

:::

#### Creating a Migration

The migration command comes with a template to generate a migration.

```js
node src/cli.ts migration/create --name={someName}
```

After creating the migration, please edit it and implement any logic that you want here.

#### Applying a Migration

```js
node src/cli.ts migration/migrate
```

A migration is executed in the order it was created. It is executed only once per life.

### DropIndex

Sometimes it is very useful to drop indexes on already created models. For example, you created a unique index for non-required fields and missed that `null` values also should be unique per collection.

The framework will take care of creating indexes based on your model on the next start, so you can drop an index and be sure that it will be recreated after.

#### Run dropindex

```js
node src/cli.ts dropindex --model={modelName}
```

### SyncIndexes

Synchronizes the indexes defined in the models with the real ones indexed in the database. The command will remove all indexes from the database that do not exist in the model OR have different parameters. Then it will create new indexes.

:::warning

This can be a dangerous command in case you have some unique index features.

:::

#### Run SyncIndexes

```js
node src/cli.ts SyncIndexes
```

### CreateUser

The `createuser` command creates a new user.

#### Run CreateUser

```js
node src/cli.ts createuser --email=somemail@gmail.com --password=somePassword --roles=user,admin,someOtherRoles
```

Only email and password are required.

You are able to update a user as well. You need to specify the email or user ID to find the user and the '--update' flag to allow user updates.

Add `--token` (framework 5.4.2 or newer) to also log the user in: the command creates a 30-day session and prints its token once.

```bash
node src/cli.ts createuser --email=somemail@gmail.com --password=somePassword --token
# Session token (valid until 2026-10-31T12:00:00.000Z): aB3x…
```

The token is printed to standard output only — never to the logger, so it does not reach log files or Sentry. The database keeps only its hash, so this line is the only copy. Without `--token`, no session is created.

### Create .env

Creates a `.env` for a fresh clone: it copies `.env.example` and replaces its `AUTH_SALT` line with a newly generated secret (32 random bytes, hex). Without `.env.example`, the new `.env` contains only `AUTH_SALT`. If `.env` already exists, the command changes nothing, so it never overwrites your secrets. The secret is written to the file only, never printed or logged.

```bash
npm run cli createEnv
```

The command is safe to run every time, so a project can call it before starting in development:

```json
{
  "scripts": {
    "dev": "npm run cli createEnv && node --watch src/index.ts"
  }
}
```

Keep `AUTH_SALT` stable once real data exists: password and code hashes depend on it.

### Generate Random Bytes

In some cases, you need a random byte string. This command helps you to generate a random byte string.

#### Run Generate Random Bytes

```js
node src/cli.ts generateRandomBytes
```

or

```js
npm run cli generateRandomBytes
```

### Generate TypeScript Types

Generates two kinds of TS source from the framework's introspection:

1. **`genTypes.d.ts`** at the project root — augments `IApp` and its `AppModelTypes` map so `getConfig('foo')`, `getModel('Bar')`, and known-name `getModelOrThrow('Bar')` calls are typed. Config inference widens homogeneous arrays to `T[]`, preserves heterogeneous tuples, and keeps finite object keys exact; see [Typed config](02-configs.md#typed-config).
2. **`<File>.routes.gen.ts`** next to every controller — typed `<MethodName>Request` aliases for handler signatures (per-route schema output, middleware-provided `appInfo` fields, etc.). The middleware chain comes from `RouteRegistry.flatten()` — same matcher the runtime uses, so types match runtime behavior. See [Routes → Typed handler signatures (codegen)](06-Controllers/02-routes.md#typed-handler-signatures-codegen) for usage.

#### Run Generate TypeScript Types

:::note Requires `oxc-parser`
Framework 5.6.0 requires the optional peer range `^0.156.0` (5.5.1 required `^0.153.0`). Existing projects can update it with `npm i -D oxc-parser@^0.156.0`.

Code generation parses your controller sources with [`oxc-parser`](https://www.npmjs.com/package/oxc-parser), an **optional peer dependency**. Install it as a devDependency — `npm i -D oxc-parser`. It is never loaded at runtime, so it stays out of production installs; the command fails with that instruction if it is missing.
:::

```bash
node src/cli.ts generatetypes
# or
npm run cli generatetypes
```

#### Recommended setup

Add to `package.json`:

```json
"gen": "node src/cli.ts generatetypes",
"check:types": "npm run gen && tsc --noEmit"
```

Add to `.gitignore`:

```
genTypes.d.ts
**/*.routes.gen.ts
```

Gen files regenerate on every type-check — no postinstall hook needed.

#### TypeScript 7 memory and checking time

For local checks with the Go-based TypeScript 7 compiler, try one checker and
incremental caching when memory is limited. With the script above:

```bash
npm run check:types -- --checkers 1 --incremental --tsBuildInfoFile node_modules/.cache/tsc/app.tsbuildinfo
```

This still runs codegen and checks types. Keep the cache between local checks;
unchanged inputs can reuse earlier results, while edits may require substantial
rechecking. Use a different cache file for each TypeScript configuration, such
as `tests.tsbuildinfo` for a separate test-suite check. The cache is disposable
and should stay out of version control; the path above is inside `node_modules`.

`--checkers 1` selects one checker per project, not one Go thread. It does not
require `GOMAXPROCS=1`. Lower checker concurrency can reduce repeated generic
instantiations and memory use, but the fastest setting depends on the project
and available memory. Measure CI separately, and run independent local compiler
commands sequentially when memory is scarce. This flag requires TypeScript 7;
check the installed compiler's help before using it with another version.

To measure a cold check with the script above, disable incremental reuse and
request diagnostics:

```bash
npm run check:types -- --checkers 1 --incremental false --extendedDiagnostics
```

Compare `Types`, `Instantiations`, `Memory used`, and `Check time` on the same
source and compiler version. Instantiations count evaluations of generic types,
not the number of models or interfaces you wrote. Compiler-reported memory is
not peak process memory. These flags tune checking; keep the project's normal
test, lint and packaging checks as well.

#### When to run codegen

Codegen only affects **types**, never runtime — so you run it whenever something that changes a handler's or `IApp`'s type shape changes, then type-check. In practice you wire it into `check:types` and forget it's there. The decision matrix:

| You changed… | Run `gen`? | Why |
|---|---|---|
| A route's `request:` / `query:` schema | **Yes** | `req.appInfo.request` / `.query` types change |
| A route path (added `:param` / `{*splat}`, renamed) | **Yes** | `req.params` and the `<Method>Request` alias change |
| A controller's `static get middleware()` chain | **Yes** | which `provides` fields land on `req.appInfo` changes |
| A middleware's `static get provides()` | **Yes** | downstream `req.appInfo` types change |
| A middleware's `relatedRequestParameters` / `relatedQueryParameters` schema | **Yes** | generated validated request/query output types change |
| Added / renamed a model or config | **Yes** | `getModel('X')` / `getConfig('Y')` typings change |
| Only handler body logic (no signature/schema change) | No | the generated types are unchanged |
| Prose, comments, formatting | No | nothing type-bearing changed |

When in doubt, just run it — it's idempotent and cheap. The standard wiring (`"check:types": "npm run gen && tsc --noEmit"`) regenerates before every type-check, so you never run it by hand in CI. See [Routes → Typed handler signatures](06-Controllers/02-routes.md#typed-handler-signatures-codegen).

### Generate OpenAPI

Generates an OpenAPI 3.1 document from your controllers (paths, parameters, request bodies, security, tags) — derived from the route definitions you already write. Opens no database/network connection and binds no port, so it's safe in CI.

```bash
node src/cli.ts openapi                       # print to stdout
node src/cli.ts openapi --output openapi.json # write to a file
```

See the [OpenAPI chapter](17-openapi.md) for what's documented, how schemas are introspected, and how middlewares contribute security schemes.

### List Routes

Prints your project's route tree — every mounted method, full path, path/splat parameters, and the middleware chain that runs for each route — by walking the same route registry the server logs at boot. Like `openapi`, it opens no database/network connection and binds no port.

```bash
node src/cli.ts routes
```

Example output:

```text
Registered routes:
/
├── GET     /
└── auth  (mw: GetUserByToken, RateLimiter)
    ├── login
    │   └── POST    /auth/login  [request]
    └── verify
        └── POST    /auth/verify  [request]

3 route(s) across 5 node(s) in the tree.
```

Reading the annotations:

- **`(mw: A, B)`** — middleware newly attached at this node. Inherited middleware from parent nodes is shown as `pmw:` so each route line is self-contained about what runs before it.
- **`[request]` / `[query]`** — this route **validates** a request body / query string. They are presence flags, not the schema itself: a route either declares a validator or it doesn't. To see the actual field shapes, run `openapi` — it resolves each schema to JSON Schema (where the validator supports introspection). Imperative validators such as `defineSchema` can supply an explicit `jsonSchema`; without one they appear here as `[request]` and degrade to a placeholder in the OpenAPI document.

Useful for answering "what's actually mounted in my app?" without starting the server. For the full request/response contract, use [`openapi`](#generate-openapi).


---


# Document 15: 11-cache

<!-- Source: 11-cache.md -->

# Cache

The cache subsystem is designed to store some values for quick access and a unified interface. It is useful when you have some values grabbed from an external API or some stuff that requires a lot of calculation and does not change from time to time.

Caches have an expiration time, and the developer should not worry about checking it. If a value has expired or does not exist, a callback will be executed, and its return value will be used as the value to store in the cache.

:::note

The cache subsystem handles all values and takes care of serialization/deserialization.

:::

## API

The API is simple:

```ts
  async getSetValue(
    key: string,
    onNotFound: () => Promise<any>,
    storeTime: number, // in seconds
  ): Promise<any>;
```

By default, the store time is 5 minutes. A store time of `0` means **"don't cache"** — the callback runs on every call and nothing is written.

Example:

```javascript
const cacheTime = 60 * 5; // seconds
const someValueFromCache = await this.app.cache.getSetValue(
  "someKey",
  async () => {
    const someValue = await someLongAsyncOperation();
    return someValue;
  },
  cacheTime // in seconds
);
```

:::note

You can request the same value multiple times, and only one callback will be executed. All other calls will be resolved as a Promise (the same promise).

```js
const promiseArr = [];
for (let n = 0; n < 100; n++) {
  promiseArr.push(
    this.app.cache.getSetValue(
      "someKey",
      async () => {
        // Will be called once! Other calls will find that "someKey" is already processing and return the same Promise.
        const someValue = await someLongAsyncOperation();
        return someValue;
      },
      3600
    )
  );
}
```

Please note that it works that way **per process**, as checking promises happens at the process level and is not synchronized via a master process.

:::

## Upgrading to 5.4.1

The cache serializer now preserves signed BigInts and strings that resemble its serialization markers. Cache-hit logs omit cached values and keys.

This correction uses a fresh `cache-v2` key space. Existing entries expire naturally, while upgraded workers repopulate their caches on first use. Mixed framework versions use separate cache entries and invalidation, so complete the rollout across workers promptly. This applies to the memory, Redis and custom drivers through the shared cache service.

## Drivers

The cache is built on a small `CacheDriver` interface (`get` / `set` / `del`), with two first-party drivers:

- **`memory`** — **the default.** A per-process `Map` with per-key TTL. Needs no external service, so a plain install works out of the box and never loads `@redis/client`. Because it is per-process, each clustered worker has its own cache — fine for development and single-node deployments.
- **`redis`** — a shared cache backed by Redis. Use this for **multi-node deployments** (or anywhere multiple processes must see the same cached values). It lazy-loads `@redis/client`, which is an **optional peer dependency** — install it yourself (`npm i @redis/client`) when you select this driver.

The orchestration around the driver — namespacing, single-flight request dedup, serialization, and fail-soft degradation (a cache outage degrades to running your callback, it never fails the request) — is identical across drivers.

## Configuration

The driver is selected in `config/cache.ts`:

```ts title="config/cache.ts"
export default {
  // 'memory' (default) or 'redis'. Overridable via the CACHE_DRIVER env var.
  driver: (process.env.CACHE_DRIVER || "memory") as "memory" | "redis",
};
```

Two related settings live in `config/redis.ts` rather than here, because they are **shared with the rate limiter**:

- **`namespace`** — a key prefix applied to **every** cache (and rate-limiter) key, regardless of driver. Despite living in `redis.ts`, it is _not_ redis-specific: the in-memory driver prefixes its keys with it too. Think of it as a keyspace/tenant label (e.g. per environment). Keeping it in one place means the cache and rate limiter never drift apart, and the test helper `setTestRedisNamespace` can isolate both with a single switch.
- **`url`** — the Redis connection string, used only by the `redis` backends (this cache and the rate limiter's redis driver share one client). Irrelevant when both run on non-redis drivers.

:::tip Custom driver

You can supply your own backend by setting `driver` to an object implementing `CacheDriver` (`get`, `set`, `del`) instead of a string.

:::


---


# Document 16: 12-email

<!-- Source: 12-email.md -->

# Sending Emails

:::warning

As of framework version 5.0, we have moved the email module to a separate package: [@adaptivestone/framework-module-email](https://www.npmjs.com/package/@adaptivestone/framework-module-email).

:::

The email subsystem is based on [Nodemailer](https://github.com/nodemailer/nodemailer). In addition, we are using [Juice](https://www.npmjs.com/package/juice) to inline CSS and [html-to-text](https://www.npmjs.com/package/html-to-text) to generate text from the HTML of files.

:::note

Sadly, email clients are outdated and do not support a lot of web features. Some clients do not even support “style” tags. That is why all styles should be inlined.

:::

## Installation

```bash
npm i @adaptivestone/framework-module-email
```

:::info Required version since 5.4

Framework 5.4 declares `@adaptivestone/framework-module-email` `^2.1.0` as an **optional** peer dependency. Optional because an app that never sends the built-in account mails needs no mailer at all; `^2.1.0` because the templates the framework ships are now [template modules](#templates-the-framework-ships), which only the module's 2.1 engines can render.

On an older module those two mails fail with `Template type js is not supported` instead of being sent — the same failure the previous `.pug` defaults already produced on module v2, which dropped the bundled Pug. So nothing that works today regresses; but if you send password recovery or email verification, install 2.1 or newer.

:::

## Templates

A template is a folder of files; each file's extension selects the engine that renders it. For each email you provide an HTML version, a subject, and (optionally) a text version, as separate files inside the template directory.

If the text version of the email is not provided, it will be generated from the HTML version by removing all HTML tags with the help of the [html-to-text](https://www.npmjs.com/package/html-to-text) package.

Your templates live in the folder `folders.emails` points at in `src/folderConfig.ts` — `src/services/messaging/email/templates/{templateName}` in the project template. That folder is searched first, so a folder named after a template the framework ships replaces it (see [Overriding a shipped template](#overriding-a-shipped-template)).

The module has no template-engine dependency of its own. Out of the box it renders two kinds of file:

| Extensions | Engine |
| --- | --- |
| `html`, `text`, `css` | plain files, read as-is |
| `js`, `ts`, `mjs`, `cjs` | [module templates](#module-templates) — the file is imported and its default export is called with the render data |

A plain template folder looks like this:

```js
html.html; // HTML markup of the email
subject.text; // Subject to generate
text.text; // Text version of the email (optional)
style.css; // Styles to inline inside the HTML
```

and the same template written as modules like this:

```js
html.ts; // export default (data) => "<h1>...</h1>"
subject.ts;
text.ts; // optional
style.css; // Styles to inline inside the HTML
```

Each file is resolved on its own, so mixing extensions inside one folder is fine.

To use a real template language such as Pug, register its engine first (see [Bring your own engine](#bring-your-own-engine)); then your files can be `html.pug`, `subject.pug`, and so on.

## Templates the framework ships

The framework ships two templates and sends them itself — `recovery` (from `user.sendPasswordRecoveryEmail()`) and `verification` (from `user.sendVerificationEmail()`).

:::info Changed in 5.4

Both used to be `.pug` files, so an app that sent them had to install Pug and register its engine. They are now [module templates](#module-templates) — TypeScript in the framework source, published to `dist` as compiled `.js` — rendered by the module's built-in module engine. **Nothing to install and nothing to register**, as long as the mailer module is [2.1 or newer](#installation).

:::

They are English out of the box and translatable key by key: every string is emitted as `t(key, { defaultValue })`, so a key defined in your locale files wins and a missing one reads as English rather than as a bare key. Overriding the text is a locale-file edit, not a template rewrite:

| Template | Key | Default (English) |
| --- | --- | --- |
| `recovery` | `email.passwordRecovery` | `Recovery password` |
| `recovery` | `email.passwordChanged` | `Password changed` |
| `recovery` | `email.greeting` | `Dear user` |
| `verification` | `email.emailConfirm` | `Email confirmation` |
| `verification` | `email.verify` | `Verify email` |
| `verification` | `email.verifyInstructions` | `To verify your email address, follow the link:` |
| `verification` | `email.greeting` | `Dear user` |

The same keys are listed with the rest of the framework's messages in [i18n › Auth controller, validation and email keys](./08-i18n.md#auth-controller-validation-and-email-keys).

:::info Fixed in 5.4

The verification mail used to be hardcoded Russian with no `t()` call in it at all — every user received Russian whatever their locale — and its greeting interpolated a variable the auth flow never passes, so it rendered empty for everyone. It now mirrors `recovery`: English defaults, every string translatable.

:::

Two more details of the shipped HTML, worth copying if you write your own:

- The `<html lang="…">` attribute is rendered from the request locale (`en` when none was detected), so a Russian mail no longer announces itself as English to screen readers and mail clients.
- Every interpolated value is HTML-escaped. A module template builds markup as a plain string, so the escaping a template language did implicitly has to be explicit.

## Overriding a shipped template

Put a folder with the same name (`recovery`, `verification`) in your own emails folder — it is found first and used instead of the framework's. The framework never merges the two: your folder must contain the whole template (`html` and `subject` at minimum; `text` and `style.css` are optional).

A module template is the natural format — `.ts` if you run TypeScript natively, `.js` after your build step, both rendered by the built-in engine with nothing to register. Pug, EJS or anything else still works here; [register the engine](#bring-your-own-engine) first.

```ts title="src/services/messaging/email/templates/verification/html.ts"
// The data the framework's auth flow passes to these two templates.
type TVerificationTemplateData = {
  /** Language the mail is rendered for — the request locale, `en` by default. */
  locale: string;
  /** Translator from the request i18n. Always pass the English text as `defaultValue`. */
  t: (key: string, options?: { defaultValue?: string }) => string;
  /** Link the auth flow asks the user to follow. */
  link: string;
  /** Nickname of the user the mail is about, when they set one. */
  editor?: string | null;
};

const escape = (value: unknown) =>
  String(value ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");

export default ({ t, link, locale }: TVerificationTemplateData) => `<!DOCTYPE html>
<html lang="${escape(locale || "en")}">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>${escape(t("email.verify", { defaultValue: "Verify email" }))}</h1>
    <p>
      ${escape(
        t("email.verifyInstructions", {
          defaultValue: "To verify your email address, follow the link:",
        }),
      )}
      <a href="${escape(link)}">${escape(link)}</a>
    </p>
  </body>
</html>
`;
```

`subject` and `text` are the same contract, returning plain strings.

:::note

The framework types this data internally as `TEmailTemplateData`, but the type is not on the package's `exports` map yet — declare the shape inline as above rather than importing it out of `dist`. Anything your app adds through `globalVariablesToTemplates` or the `Mailer` constructor arrives on the same object, so widen the type with your own fields when you use them.

:::

## Template engines

:::warning Breaking change in v2

Before v2, Pug was bundled and `.pug` templates worked out of the box. As of **v2 the module ships no template-engine dependency** — only the built-in engines listed above. To keep using `.pug` (or any other language) you must install that engine and register it yourself.

This is about **your** templates only: since framework 5.4 the [templates the framework ships](#templates-the-framework-ships) are module templates, so they need no engine registration.

:::

### Module templates

:::info New in framework-module-email 2.1

`js`, `ts`, `mjs` and `cjs` templates are rendered by a built-in engine — nothing to install and nothing to register.

:::

A module template is an ordinary module whose default export turns the render data into the rendered string:

```ts
// src/services/messaging/email/templates/welcome/html.ts

type TWelcomeData = {
  t: (key: string, options?: { defaultValue?: string }) => string;
  locale: string;
  userName: string;
};

export default ({ t, userName }: TWelcomeData) => `
  <h1>${t("email.welcome.title", { defaultValue: "Welcome!" })}</h1>
  <p>${t("email.welcome.greeting", { defaultValue: "Hi" })} ${userName}!</p>
`;
```

- The default export may be sync or async: `(data) => string | Promise<string>`. A missing or non-function default export fails with an error naming that file.
- It receives the same data every engine gets — `locale`, `t`, `globalVariablesToTemplates` and your own template variables (see [Template Variables](#template-variables)).
- `html`, `subject` and `text` can each be a module. `style` is rendered without the template data, so keep it a plain `.css` file.
- `js`, `ts`, `mjs` and `cjs` share one engine — ship whichever extension your app runs (`.ts` when you run TypeScript natively, `.js` after a build step).
- Template modules are imported once per process and cached by `import()`, so a template edited on disk needs a restart to be picked up.
- The framework's own `recovery` and `verification` templates are written this way — a working reference if you need one.
- The module exports a `TTemplateModule` type (`import type { TTemplateModule } from "@adaptivestone/framework-module-email/dist/types.d.ts"`) describing the contract if you prefer to annotate the export.

### Bring your own engine

For a real templating language, install it in your app and register an engine by mapping a file extension to a render function. The function receives the absolute path to the template file and the render data, and returns the rendered string (sync or async):

```js
import pug from "pug";
import ejs from "ejs";
import Mailer from "@adaptivestone/framework-module-email";

// Pug — was bundled by default before v2; now opt-in
Mailer.registerTemplateEngine("pug", (fullPath, data) =>
  pug.compileFile(fullPath)(data),
);

// any engine works the same way
Mailer.registerTemplateEngine("ejs", (fullPath, data) =>
  ejs.renderFile(fullPath, data),
);
```

### Where to register

Engines live in a **single process-wide registry** shared by every `Mailer` instance, so register them **once at process startup, before any email is sent** — not per request and not per `Mailer` instance.

The natural place is the worker bootstrap (`src/server.ts`), the file each worker process runs. Register before `startServer()`:

```js
// src/server.ts
import Server from "@adaptivestone/framework/server.js";
import Mailer from "@adaptivestone/framework-module-email";
import pug from "pug";
import folderConfig from "./folderConfig.ts";

Mailer.registerTemplateEngine("pug", (fullPath, data) =>
  pug.compileFile(fullPath)(data),
);

const server = new Server(folderConfig);
await server.startServer();
```

:::note

The registry is per **process**. If your app uses the cluster manager (`src/index.ts` forking workers), register in `src/server.ts` (which every worker runs), not in the master `src/index.ts` (which never sends mail).

:::

### Registering more than once

`registerTemplateEngine` can be called as many times as you like:

- **Different extensions accumulate** — call it once per engine you want (`pug`, `ejs`, `mjml`, …).
- **The same extension overrides** — the last registration for a given extension wins. The built-ins are ordinary entries with no special casing, so `Mailer.registerTemplateEngine("js", ...)` replaces the module engine with your own contract and `Mailer.unregisterTemplateEngine("js")` removes it, exactly as for a custom engine. There is no error on re-registration.
- Extensions are normalized, so `"pug"`, `".pug"` and `".PUG"` all target the same engine.

### Helpers

- `Mailer.registerTemplateEngine(extension, engine)` — register/override an engine for a file extension (leading dot optional, case-insensitive).
- `Mailer.unregisterTemplateEngine(extension)` — remove an engine; returns `true` if one was removed.
- `Mailer.hasTemplateEngine(extension)` — check whether an engine is registered.

### Inline Images

For a publicly hosted image, use its CDN URL in the template:

```html
<img src="https://media.example.com/logo.png" width="180" alt="Brand" />
```

To embed an image in one email, pass it as a Nodemailer attachment to that
message's `mail.send()` call. This standard per-message option is supported by
`@adaptivestone/framework-module-email` **2.1.0**. Use the same content ID in the
HTML template.

```ts
import path from "node:path";
import Mailer from "@adaptivestone/framework-module-email";

const mail = new Mailer(app, "welcome", data);
// Leave the from argument empty to use the configured sender.
await mail.send("user@example.com", "", {
  attachments: [
    {
      filename: "logo.png",
      path: path.resolve("src/services/messaging/email/resources/logo.png"),
      cid: "brand@example.com",
    },
  ],
});
```

```html
<img src="cid:brand@example.com" width="180" alt="Brand" />
```

The attachment applies to this send only. Other messages are unaffected, and
ordinary attachments can be included in the same `attachments` array. The image
file must be available to the sending process. Nodemailer embeds it in the
message, so the recipient does not need to fetch it from a remote server.

For direct sends, pass CID images through the usual Nodemailer `attachments`
option as the last argument to `Mailer.sendRaw()`:

```ts
import path from "node:path";
import Mailer from "@adaptivestone/framework-module-email";

await Mailer.sendRaw(app, to, subject, html, text, from, {
  attachments: [
    {
      filename: "logo.png",
      path: path.resolve("src/services/messaging/email/resources/logo.png"),
      cid: "brand@example.com",
    },
  ],
});
```

The existing `data-inline` option is separate: Juice replaces the image source
with a data URI during template rendering when you add the attribute:

```html
<img src="/cats.jpg" data-inline />
```

The image path is relative to your project's
`src/services/messaging/email/resources` folder. Use a CDN URL when the
recipient's email client can load a remote image.

### Template Variables

Each template has these variables:

- `locale` - the current locale of the request.
- `t` - the translate function from i18n. Call it the i18next way, with an English default: `t("email.welcome.title", { defaultValue: "Welcome!" })`.
- `globalVariablesToTemplates` - from the config.
- User-provided variables (see the API section).

:::info Changed in framework-module-email 2.1

When no i18n object is passed to `new Mailer(...)`, `t` is a fallback translator. It now honours the i18next defaults instead of returning the raw key, so `t("email.welcome.title", { defaultValue: "Welcome!" })` renders `Welcome!` and a template reads correctly with no i18n setup at all. A key that **is** present in the request's i18n still wins. The positional form `t("email.welcome.title", "Welcome!")` is honoured at runtime too, though only the options object is declared in the types. A key with no default still renders as the key.

:::

## API

### Init Mailer

```js
import Mailer from "@adaptivestone/framework-module-email";

const mail = new Mailer(
  this.app,
  "recovery", // template name
  {
    // variables for the template. These are user-provided variables. They will be merged with the default variables.
    oneTemplateVariable: "1",
    anotherTemplateVariable: "2",
  },
  req.appInfo.i18n
);
```

Inside the template, `oneTemplateVariable` and `anotherTemplateVariable` will be available as top-level variables.

```ts
// html.ts
export default (data) => `<p>${data.oneTemplateVariable} ${data.anotherTemplateVariable}</p>`;
```

or, if you registered a Pug engine:

```pug
p #{oneTemplateVariable} #{anotherTemplateVariable}
```

### Send Email

```js
const result = await mail.send(
  "some@email.com", // To
  "optional@from.com", // OPTIONAL. From email. If not provided, it will be grabbed from the config.
  {} // OPTIONAL. Any additional options for Nodemailer: https://nodemailer.com/message/
);
```

### Send Raw

For advanced usage (your own templates, mail headers, attachments), another low-level method exists.

```js
import Mailer from "@adaptivestone/framework-module-email";

const result = await Mailer.sendRaw(
  this.app, // framework app
  "to@email.com", // To
  "email subject", // topic
  "<html><body><h1>Email html body</h1></body></html>", // HTML body of the email
  "Email text body", // OPTIONAL. If not provided, it will be generated from the HTML string.
  "from@email.com", // OPTIONAL. From email. If not provided, it will be grabbed from the config.
  {} // OPTIONAL. Any additional options for Nodemailer: https://nodemailer.com/message/
);
```

### Render Template

In some cases, you may want to render templates to a string for future usage. For example, to send an email via Gmail OAuth2 authorization on behalf of a user.

```js
const { subject, text, inlinedHTML, htmlRaw } = await mail.renderTemplate();
```

## Configuration

Please look at the `src/config/mail.ts` file for all configuration options.

### Environment Variables

Here are the most important environment variables:

```js
EMAIL_HOST; // smtp.mailtrap.io by default
EMAIL_PORT; // 2525 by default
EMAIL_USER;
EMAIL_PASSWORD;
EMAIL_TRANSPORT; // smtp by default
```


---


# Document 17: 12-resize

<!-- Source: 12-resize.md -->

# Image Resizing

`@adaptivestone/framework-module-resize` makes resized copies of uploaded images. You store the uploaded **original** once. The module then creates **previews**, such as a `320×320` thumbnail and a `620`-pixel-wide detail image, with [`sharp`](https://sharp.pixelplumbing.com), stores them, and records them on your media document. When you build a response, it turns that record into image URLs.

- **Original**: the uploaded file, stored unchanged and privately.
- **Preview**: a generated image file. Its metadata is stored in the media document's `previews[]`.
- **Variant**: one requested size and format, plus optional filters. One size in JPEG, WebP and AVIF is three variants, and so three files.

The module handles resizing, storage calls and deciding which URLs are ready. Your app handles the upload endpoint, the media model, access checks, the response shape and deleting files.

<div className="resize-diagram" role="region" aria-label="From an uploaded original to a displayable preview" tabIndex={0}>

```mermaid
flowchart TB
  accTitle: From an uploaded original to a displayable preview
  accDescr: The host saves the original and media document. Generation uploads a preview file and appends its metadata. A read of the updated media produces a URL that the frontend uses to download the preview.
  Original["Original saved by your app<br/>2400 × 1600 PNG"] --> Generate["generate() or worker<br/>Resize + encode"]
  Generate --> File["Storage<br/>320 × 320 WebP file"]
  Generate --> Metadata["Media document<br/>previews[] metadata"]
  Metadata --> Read["resolve()<br/>Build ready URLs"]
  Read --> Frontend["Your frontend<br/>Fetch the image by URL"]
  File -. "Image bytes via that URL" .-> Frontend
```

</div>

## Choose a workflow

| You want… | Call | The call waits for… | It returns |
|---|---|---|---|
| Previews ready when the upload request finishes | `generate()`: **eager** | resizing, upload and saving | `{ created, failed }` |
| A fast upload, with previews made in the background | `prewarm()`: **pre-warm** | queueing and its confirmation | `{ status, … }` per variant |
| Previews only for the sizes readers actually request | `resolve()` with a queue: **lazy** | queueing of the missing variants | `{ decision, output }` |

Every workflow reads URLs with `resolve()` and writes the same `previews[]`. You can mix them, for example pre-warm thumbnails and let detail sizes generate lazily. You can also switch later without migrating data. Start with eager, and add the [queue](#background) when uploads must stay fast.

## Set up

### 1. Install and scaffold

You need Node `>=24`, `@adaptivestone/framework` `^5.1.0`, and `mongoose` 9 (already in a framework app). From your app's root:

```bash
npm i @adaptivestone/framework-module-resize
npm exec --package=@adaptivestone/framework-module-resize -- resize-scaffold --eager
```

`resize-scaffold` ships with the package.

- `--eager` creates `src/resizer.ts` and `src/config/resize.ts`. Without it, the command also creates the queue model and the worker command (see [background generation](#background)).
- It never overwrites existing files; `--force` does.
- It adds a pointer to the package's agent guide to your `AGENTS.md`. Use `--agents claude|print|skip` to change that.
- In CI, run `resize-scaffold --check` (`--check --eager` for eager apps). It fails when a generated file is missing or has been changed in a way that breaks it.

### 2. Add the fields to your media model

```ts
// src/models/File.ts
import { BaseModel } from '@adaptivestone/framework/modules/BaseModel.js';
import { resizeMediaSchemaFragment } from '@adaptivestone/framework-module-resize/framework.js';

export default class File extends BaseModel {
  static get modelSchema() {
    return { name: { type: String }, ...resizeMediaSchemaFragment } as const;
  }
}
```

The fragment adds:
- `original`: where the original is stored, plus its format, size and dimensions.
- `previews[]`: one entry per generated file. Besides its URL fields, each entry records `bytes`, `createdAt`, `origin` (which original it was made from) and `encodeSig` (what it was encoded with: its format's encode settings, the sharpen setting of its fit mode, its animation settings (for animated formats: `animated`, `limits.animationFrames` and the pixel budget `min(limits.sourcePixels, limits.inputPixels)`, which also caps the frames at the larger of the source's and the preview's size), the result-dimension cap, the fit box (for fit rows) and the pipeline `version`). Its `identity` field lets the media store keep one entry per preview. A hand-written schema that declares preview entries as strict sub-documents needs `identity`, `origin` and `encodeSig` in them, each `{ type: String }`, and `fit` as `{ type: Boolean }`; `verify()` reports `RESIZE_MONGO_MEDIA_MODEL_OUTDATED` without the first three and logs one warning without `fit`.

Keep Mongoose's `minimize: false`, which is the `BaseModel` default, because storage locators can contain empty objects. Save the media document before you generate previews; the module never creates it.

### 3. Configure

```ts
// src/config/resize.ts
import {
  defaultFrameworkResizeConfig,
  type FrameworkResizeConfig,
} from '@adaptivestone/framework-module-resize/framework.js';

export default {
  ...defaultFrameworkResizeConfig,
  mediaModelName: 'File', // your media model
  storage: { driver: 'local', rootDir: './var/media', publicBaseUrl: '/media' },
} satisfies FrameworkResizeConfig;
```

The module merges the image settings over the package defaults, so a key you leave out keeps its default; spreading the defaults, as the scaffold does, keeps them visible in the file. It then validates the result and throws `ResizeConfigError` if anything is wrong. Put environment-specific changes in `resize.production.ts` and similar files; the framework merges them. For example, S3 in production only:

```ts
// src/config/resize.production.ts
import type { FrameworkResizeConfig } from '@adaptivestone/framework-module-resize/framework.js';

export default {
  storage: {
    driver: 's3',
    bucketPublic: 'my-cdn',
    bucketPrivate: 'my-originals',
    publicBaseUrl: 'https://cdn.example.com',
  },
} satisfies Partial<FrameworkResizeConfig>;
```

An override that changes only nested keys, such as `limits: { sourcePixels: 20_000_000 }`, writes `satisfies PartialFrameworkResizeConfig` (from `…/framework.js`) instead. All options are listed under [configuration](#configuration).

### 4. Create the Resizer

```ts
// src/resizer.ts
import { FrameworkResizer } from '@adaptivestone/framework-module-resize/framework.js';

export const resizer = new FrameworkResizer({ pipelines: { default: {} } });
```

`FrameworkResizer` builds everything else from `src/config/resize.ts`: the image settings, the storage, the task queue, the media store (`FrameworkMediaStore`, over your media model `mediaModelName`), for a queue that cannot gate by itself, such as SQS, the lock store (`FrameworkLockStore`, the framework's `Lock` model; the database queue needs none), and the app logger. So `src/resizer.ts` holds only behaviour: pipelines and hooks. Options win over the config; for example, `new FrameworkResizer({ storage: new S3Storage({ …, client }) })` reuses your own S3 client. Import `src/resizer.ts` wherever you need the Resizer; a normal static import is fine, because nothing is read from the framework until first use. Elsewhere in your code, `getResizer()` returns the same instance.

A config mistake then shows up at the first upload or read. To catch it at startup instead, verify after initialization:

```ts
// src/server.ts
await server.init();
await resizer.verify(); // config, storage, the media model, the task queue (ResizeTask model, its gate index, and the queue), and the Lock model when its queue is on SQS
await server.startServer();
```

`LocalFsStorage` writes:
- previews under `rootDir`;
- private originals under `privateRootDir`, which defaults to `./var/media-private`.

Serve only `rootDir`, at `/media`, with a long-lived cache: every file name the module writes there is new (previews and public raster originals), so a file never changes under its URL; if you write your own files under `rootDir`, give each a new name. Never serve the private folder. For S3, see [drivers](#drivers).

### 5. Store the original at upload

```ts
import { getResizer } from '@adaptivestone/framework-module-resize';

fileDoc.original = await getResizer().uploadOriginal({
  body: buffer, // the uploaded bytes
  visibility: 'private',
  // namespace: `users/${user.id}`, // optional key prefix; not access control
});
await fileDoc.save();
```

`uploadOriginal()` detects the format and dimensions with its decoders (Sharp for raster images and SVG), then stores the bytes unchanged under a random name. It returns the value to save as `original`. It does not create the document or queue any work. Input larger than `upload.maxBytes` (25 MiB by default), or in a format not listed in `upload.formats`, throws `ResizeOriginalError`.

Save `original` exactly as returned. Its `storageRef` is the storage driver's own locator: `{ path, visibility }` for local files, `{ bucket, key }` for S3. Never build it by hand.

## Sizes and formats

Define a fixed catalog of sizes for each use, and pass the same catalog when you generate and when you read:

```ts
// src/mediaSizes.ts
import type { PreviewFormat, SizeInput } from '@adaptivestone/framework-module-resize';

export const thumbnailSizes: SizeInput[] = [{ width: 320, height: 320 }];
export const detailSizes: SizeInput[] = [{ width: 620 }, { fit: true }];
export const previewFormats: PreviewFormat[] = ['webp']; // the examples use one format
```

| Size | Key | Result for a `2400×1600` original |
|---|---|---|
| `{ width: 320, height: 320 }` | `320x320` | `320×320`, cropped from the center |
| `{ width: 620 }` | `620w` | about `620×413`, aspect ratio kept |
| `{ height: 400 }` | `400h` | `600×400`, aspect ratio kept |
| `{ fit: true }` | `fit` | `1800×1200`: the whole image inside `maxSize` (`2000×1200`), never enlarged |

For a pipeline without `variantSteps`, a raster original no larger than the requested width and height is never enlarged or cropped: its preview keeps the original's size (scaled down only to fit `limits.resultDimension`), without metadata such as EXIF or GPS. A pipeline with `variantSteps`, such as a watermark, always gets the full box its steps were written for. Fractional dimensions are rounded to whole pixels. No side of a preview other than `fit` exceeds `limits.resultDimension` (5000): when the side derived from the aspect ratio of a width-only or height-only size would, the preview is cropped to it.

:::warning

**The catalog is an allowlist.** Never pass dimensions from the client into `sizes`. Map a client choice such as "thumbnail" to your catalog. Otherwise anyone can make your server resize images to any size they like.

:::

Formats are Sharp output format IDs.
- The `formats` config defaults to `['jpeg', 'webp', 'avif']`, and a call can override it with `formats`.
- Each format is a separate file, so three sizes in three formats make nine files per image.
- Use `'jpeg'`, not `'jpg'`. JPEG previews put transparent areas on a white background.
- Other Sharp formats, such as `'png'` or `'tiff'`, work once you add them to both `formats` and `encode.formats`. A per-call format without an `encode.formats` entry, or one a `beforeEnqueue` hook adds, is never generated: `resolve()` skips it, `prewarm()` reports `RESIZE_FORMAT_NOT_CONFIGURED`, and `generate()` throws.
- SVG is accepted only as an original, and its previews are always raster images: the worker renders the SVG once per task, in a separate process and before any pipeline step, and makes every format from that render. `beforeSteps` receive the rendered pixels as a `Raster`, never SVG markup.

## Generate now (eager)

```ts
import { getResizer } from '@adaptivestone/framework-module-resize';
import { previewFormats, thumbnailSizes } from './mediaSizes.ts';

const { created, failed } = await getResizer().generate({
  media: fileDoc,
  sizes: thumbnailSizes,
  formats: previewFormats,
});
```

`generate()` downloads the original, resizes it, uploads the previews and adds their metadata to `previews[]`, all before it returns. The metadata goes both into MongoDB and onto `fileDoc`, so don't add it again. Reload the media before saving it after `generate()` or `invalidate()`; the module wrote the rows itself (on a Mongoose document the changed `previews` is marked modified, and saving the stale list would drop previews a worker stored since it was loaded). No queue or worker is needed.

| Field | Meaning |
|---|---|
| `created` | `Preview[]`: the files this call made. Up-to-date previews that already existed are skipped and not listed; [outdated](#operations) ones are made again. |
| `failed` | The number of variants that failed. `failed > 0` is a partial success: the successful previews are saved. |
| `replaced` | The storage refs of every row this call's write removed: the outdated previews it replaced, or a copy of the same preview another worker stored meanwhile. Set only when there were some. Their files are not deleted. |

`generate()` throws `ResizeGenerateError` if every variant fails, and `ResizeNoOriginalError` if the media has no original. So `{ created: [], failed: 0 }` means nothing new was needed. `failed` is only a count; the logs say which variant failed and why.

With `persist: false`, the files are uploaded but their metadata is not saved, so store `created` yourself. Eager calls take no locks, so two concurrent calls for the same media can both generate the same variants.

## Read URLs

```ts
import { formatPictureUrls, getResizer } from '@adaptivestone/framework-module-resize';

const { decision } = await getResizer().resolve({
  media: fileDoc,
  sizes: thumbnailSizes,
  formats: previewFormats,
});
const picture = formatPictureUrls(decision, { id: String(fileDoc.id) });
// { id: '65f0…', sizes: { '320x320': { webp: { url: '/media/previews/8d0e2b7c.webp', contentType: 'image/webp' } } } }
```

With strict types, a loaded Mongoose document is not a `MediaLike` (Mongoose types the nested fields as nullable): pass it as `media: doc as MediaLike` (`import type { MediaLike }` from the main entry), or type the model's `original` and `previews` paths with `Original` and `Preview`.

`resolve()` never resizes and never throws. It returns:

| Field | Meaning |
|---|---|
| `decision.ready` | Stored previews that can be served now, each with `sizeKey`, `format`, `url`, `contentType` and the `preview` row; never the original. An outdated preview is served too, with `stale: true` |
| `decision.missing` | Variants that cannot be served yet; they have no URL |
| `decision.stale` | Variants that would replace an outdated preview, as left after your `beforeEnqueue` hook; set only when there is one. It does not confirm that they were queued (no queue, a queue that cannot be used, `enqueueMissing: false`), nor that the old preview was served |
| `output` | The return value of your `formatPublicUrls` hook, or `undefined` if you have none |

`formatPictureUrls()` leaves missing sizes out of its map, so show your own placeholder for them.
- **With a queue configured:** `resolve()` also queues the missing variants, and the replacements of outdated ones. Pass `enqueueMissing: false` to only read.
- **Without a queue:** it only reads.
- **New previews:** `resolve()` never waits for the worker. To see new previews, load the media again on a later request.

`formatPictureUrls()` also skips variants that have filters; build the response from `decision` yourself for those. To get your own response shape directly, register a hook once: `getResizer().hook('formatPublicUrls', (decision) => toMyDto(decision))`. `output` then holds what that hook returns.

On list pages, select only the module's fields and resolve one bounded page:

```ts
import { resizeMediaPaths } from '@adaptivestone/framework-module-resize/framework.js';

const files = await File.find(query).select([...resizeMediaPaths, 'name']).limit(20).lean();
const pictures = [];
for (const file of files) {
  const { decision } = await getResizer().resolve({ media: file, sizes: thumbnailSizes, formats: previewFormats });
  pictures.push(formatPictureUrls(decision, { id: String(file._id) }));
}
```

`resolve()` uses only the fields you loaded. In lazy mode every read can write to the queue, so keep pages bounded.

## Generate in the background {/* #background */}

### Add the queue and the worker

1. Run the scaffold without `--eager`. It adds `src/models/ResizeTask.ts` (the queue's model) and `src/commands/ResizeWorker.ts` (the worker command), and keeps your existing files:

   ```bash
   npm exec --package=@adaptivestone/framework-module-resize -- resize-scaffold
   ```

2. Define the queue, where tasks wait for the worker, name it as the Resizer's queue, and allow the worker to run. In `src/config/resize.ts`:

   ```ts
   queue: 'default', // this Resizer's queue: a key of `queues`
   queues: { default: { driver: 'database' } }, // tasks in the ResizeTask model; or { driver: 'sqs', queueUrl }
   worker: { enabled: true }, // every worker key is optional; defaultWorkerOptions holds the rest
   ```

   `queues`, `worker` and `coordination` are process-wide: they are read only from `src/config/resize.ts`, for every Resizer of the process and for the worker. `queue: false`, or no `queue` key while `queues` is empty, is eager only. A `queue` name that `queues` does not define is `RESIZE_CONFIG_QUEUE_UNKNOWN`, so with `queue: 'default'` kept in the file, a missing `queues` is that error too. `worker.enabled` only permits the worker command; the API never starts a worker. `src/resizer.ts` does not change.

3. Check the queue timing if your images are large: each `queues` entry also takes `leaseMs`, `maxAttempts` and the other [timing options](#configuration), for that queue only.

4. Create the indexes. `ResizeTask` declares its indexes (and so does the framework's `Lock` model, which only a queue that cannot gate by itself, such as SQS, uses). Create them through your normal migration or deployment process before you deploy the API and the worker. The module never creates indexes at runtime. One task per media, pipeline and queue depends on the gate index, so `resizer.verify()` and the worker refuse to start without it (`RESIZE_MONGO_INDEX_MISSING`). When Mongoose builds your indexes itself (`autoIndex`, on by default in the API server), `verify()` waits for that build, so the boot check passes on a fresh database too. The worker does not: the framework CLI that runs it turns `autoIndex` off, so it builds no index and does not wait for one, and a worker started before the gate index exists stops with `RESIZE_MONGO_INDEX_MISSING`, even on a fresh database. Create the indexes before the first worker starts: through a migration that runs before the API and the worker (the order that always works), or, on a new database only, by starting the API first and letting its `verify()` pass (the build is Mongoose's own `autoIndex`, no code of yours). When you upgrade from an earlier version, create them through a migration, in this order. Create the gate index `{ resizer: 1, fileId: 1, pipeline: 1, queue: 1 }` (unique, partial on `active: true`) BEFORE the new API and workers start: without it every new task is stored, duplicate active tasks build up, and building the unique index then fails (E11000) until those tasks are no longer active (completed, or dead and taken over or expired). Create the claim index `{ queue: 1, status: 1, availableAt: 1 }` before or together with the new workers, then drop the old `{ status: 1, createdAt: 1 }` (or `{ queue: 1, status: 1, createdAt: 1 }`) index. Then drop the `requestKey` index (`{ fileId, pipeline, requestKey }`) when convenient.

5. Start the worker as a separate long-running process, kept running by your process manager:

   ```bash
   npm run cli ResizeWorker
   ```

The scaffolded command imports `src/resizer.ts`, so the worker has the same Resizers as the API:

```ts
// src/commands/ResizeWorker.ts (scaffolded)
import '../resizer.ts';

export { ResizeWorker as default } from '@adaptivestone/framework-module-resize/framework.js';
```

Keep that import if you edit the command; `resize-scaffold --check` reports a command without it. The API and the worker must use the same database and the same storage. With `LocalFsStorage` that means the same filesystem; for workers on other machines, use S3 or other shared storage.

### Lazy and pre-warm

<div className="resize-diagram resize-diagram--sequence" role="region" aria-label="Lazy and pre-warm calls do not wait for background generation" tabIndex={0}>

```mermaid
sequenceDiagram
  accTitle: Queueing and background generation are separate
  accDescr: Resolve on a read or prewarm after upload enqueues a missing thumbnail and returns without waiting for generation. A separate worker takes the task, creates the preview, and saves metadata. A later resolve with freshly loaded media returns a ready URL.
  participant App as Your app
  participant Resizer
  participant Queue
  participant Worker
  alt Lazy: a reader needs a thumbnail
    App->>Resizer: resolve()
    Resizer->>Queue: Enqueue missing WebP
    Resizer-->>App: ready: [], missing: [WebP]
  else Pre-warm: an upload was saved
    App->>Resizer: prewarm()
    Resizer->>Queue: Enqueue missing WebP
    Resizer-->>App: status: accepted
  end
  Queue->>Worker: Task
  Worker->>Worker: Resize, upload, append previews[]
  Note over App,Worker: A later request loads the media again
  App->>Resizer: resolve()
  Resizer-->>App: URL in decision.ready
```

</div>

**Lazy** needs no extra code: `resolve()` queues whatever is missing. **Pre-warm** queues the catalog right after the upload is saved, so the worker usually finishes before the first reader arrives:

```ts
const result = await getResizer().prewarm({
  media: fileDoc,
  sizes: thumbnailSizes,
  formats: previewFormats,
});
if (result.status === 'incomplete') {
  // result.unconfirmed: variants without a confirmed task
  // result.issues: why, and whether a retry can help (issue.retryable)
}
```

`prewarm()` never throws, and it reports every requested variant. All variants for one media and pipeline on one queue go into one task, and only one such task is active at a time: while it waits, runs or retries (and for `coordination.cooldownMs` after it is dead-lettered), reads and pre-warms queue nothing new for that media and pipeline on that queue. A size that is still missing is queued by the next read or pre-warm after the task ends. A request on another queue is a separate task.

| `status` | Meaning |
|---|---|
| `'ready'` | Nothing needs queueing, and at least one requested variant is already stored |
| `'accepted'` | Every variant that needs queueing has a confirmed task (`result.tasks`) |
| `'not-required'` | Nothing to do: the request was empty, or the `beforeEnqueue` hook removed everything |
| `'incomplete'` | At least one variant has no confirmed task, for example because there is no task queue or no original |

The arrays `ready`, `accepted`, `notRequired` and `unconfirmed` split the requested catalog, and `result.tasks` holds the task receipts. When a task for the same media, pipeline and queue is already active, the database queue looks it up: `prewarm()` accepts the variants that task holds, and returns the others as `unconfirmed` with the retryable `RESIZE_TASK_IN_FLIGHT` issue; call `prewarm()` again after the task ends. SQS, which gates with a lock, reports every variant as `unconfirmed` with the retryable `RESIZE_ENQUEUE_LOCK_CONTENDED` issue while the lock is held. An unexpected error, for example a media document without an ID, is `incomplete` with a `RESIZE_ENQUEUE_INTERNAL_ERROR` issue. The [issue reference](https://github.com/adaptivestone/framework-module-resizer#prewarm-issues) lists every issue code, when it happens and its `retryable`.

### Queues and workers {/* #named-queues */}

Every task waits in a named queue. When you don't name one, it is `'default'`.

| You want… | How |
|---|---|
| Another queue | An entry in `queues` of `src/config/resize.ts`, e.g. `bulk: { driver: 'database', leaseMs: 120000 }` |
| A Resizer's tasks on another queue | `queue: 'bulk'` in its config file, or `new FrameworkResizer({ …, queueName: 'bulk' })` |
| One call's tasks on another queue | `prewarm({ …, queue: 'bulk' })`; `resolve()` also accepts `queue` |
| A worker for `'default'` | `npm run cli ResizeWorker` |
| A worker for another queue | `npm run cli ResizeWorker -- --queue=bulk` |
| One worker for several queues | `npm run cli ResizeWorker -- --queue=default --queue=bulk` |
| A queue on another backend | An entry with its own driver, e.g. `bulk: { driver: 'sqs', queueUrl: '…' }` beside the database `default` |

A worker consumes the queues you name with `--queue`, which you may repeat; every name must be served, or the worker stops before it takes a task (`RESIZE_QUEUE_NOT_SERVED` naming it). A common setup keeps uploads and reads on `'default'` and runs a large backfill on `'bulk'` with its own worker, so the backfill never delays new uploads. The one-task-at-a-time rule is per queue: a task waiting on `'bulk'` never blocks reads on `'default'` for the same media (the media may then be rendered on both queues; each preview is still stored once).

Each queue is defined once, by name, with its own timing. Queues on one backend share one task queue: every `database` entry, and the SQS entries with the same `region`, `endpoint`, `deadLetterQueueUrl` and `waitTimeSeconds`. Queues on different backends work side by side: each call goes to its queue's backend, and the one-task-at-a-time rule is kept there (by the task row on the database, by a lock in the framework's `Lock` model on SQS). So an environment file may move only some queues, for example `queues.default` to SQS in `resize.production.ts` while `bulk` stays on the database. A backend is built when one of its queues is first used, so an SQS entry nothing uses never loads the AWS SDK; where that SDK is not installed, that backend's queues are not served (`prewarm()` reports `RESIZE_QUEUE_NOT_SERVED` naming the package, and `resolve()` logs it once per queue name), while the other queues keep working. A call on a name `queues` does not define queues nothing the same way. With queues on two backends, `resizer.tasks` routes between them: to find the backend of a queue, ask `await carrierOf(resizer.tasks, 'default')` (from the main entry) rather than checking the class. `resizer.queueName` tells a Resizer's queue; when the name comes from the config file, it is readable after `await resizer.ready()` or the first call.

Any number of workers, on any number of servers, can consume one queue; each task is processed by one worker at a time. If a worker dies, its lease (its time-limited hold on the task) expires and another worker takes the task. A task can therefore run more than once, but the worker skips previews that already exist.

## More than one Resizer

Most apps need one Resizer. Create more when parts of the app need different storage, media models or formats, for example avatars and listings:

```ts
// src/resizer.ts
export const resizer = new FrameworkResizer(); // 'default', src/config/resize.ts
export const listings = new FrameworkResizer({
  name: 'listings',
  configName: 'resizeListings', // src/config/resizeListings.ts: this Resizer's own settings
});

// elsewhere: getResizer('listings').resolve({ … })
```

- **One construction per name:** each name can be created only once per process.
- **Create them all in `src/resizer.ts`:** every task records which Resizer created it, and the worker gives the task to the Resizer with that name, so the worker needs all of them. Creating them in `src/resizer.ts` gives both the API and the worker the same set.
- **Own config files:** each file spreads `defaultFrameworkResizeConfig`, `satisfies FrameworkResizeConfig`, and holds its Resizer's own media model, storage, image settings and `queue`: a name from `queues` in `src/config/resize.ts`, such as `queue: 'bulk'`. `queues`, `worker` and `coordination` stay in `src/config/resize.ts`; in another file they are `RESIZE_CONFIG_INVALID`. Resizers whose queues are on one backend share one task queue. The worker runs one loop per backend and queue it consumes, one task at a time each, and processes each task with its own Resizer.
- **No mixing:** previews from different Resizers never mix.
- **Worker settings:** the worker reads `worker` (`enabled` and the Sharp tuning) and `queues` from `src/config/resize.ts`, and from no other file: the old `--config` flag is removed (`RESIZE_CONFIG_REMOVED_KEY`). An app whose Resizers all read other files keeps a `src/config/resize.ts` with only the process-wide sections, written `satisfies Partial<FrameworkResizeConfig>`.

## Pipelines, filters and hooks

If you register nothing, the module only resizes and encodes. For custom image processing, register a **pipeline** in `src/resizer.ts`, so the worker has it too:

```ts
import { rasterToSharp, sharpToRaster } from '@adaptivestone/framework-module-resize';

export const resizer = new FrameworkResizer({
  pipelines: {
    photo: {
      beforeSteps: [    // run once per task on the decoded source
        // async (r) => sharpToRaster(rasterToSharp(r).blur(5)), // e.g. blur plates: a Raster in, a Raster out
      ],
      variantSteps: [   // run per variant, after resize and before encode
        (img, { variant }) => (variant.filters?.blur ? img.blur(Number(variant.filters.blur)) : img),
      ],
    },
  },
});

// A read that asks for that rendering:
await getResizer().resolve({
  media: fileDoc,
  pipeline: 'photo',
  sizes: [{ width: 320, height: 320, filters: { blur: 40 } }],
});
```

- **Watermarks go in `variantSteps`.** In `beforeSteps`, the watermark is applied to the original and shrinks until it is unreadable in small previews.
- **`beforeSteps` work on pixels.** A step receives the decoded first frame as a `Raster` (raw 8-bit sRGB pixels with their size) and resolves with one; anything else, such as a `Buffer` or a Sharp object, fails with `RESIZE_PIPELINE_STEP_INVALID`. The image engine is replaceable, so a step sees pixels, not a library object; `rasterToSharp` and `sharpToRaster` wrap Sharp work, as above. For a raster source the step sees the upright original at its own size; for a vector source (SVG) the pixels can be larger, so multiply coordinates stored in the source's units by `meta.scale`. `variantSteps` receive a Sharp instance over each preview's pixels. A pipeline with steps renders only the first frame of an animation.
- **A filter such as `{ blur: 40 }` does nothing by itself.** Your `variantSteps` give it meaning.
- **`ctx` does not reach the worker.** Queued tasks carry only the pipeline name and the variants, and steps in the worker receive `ctx === {}`. Keep any data a step needs on the media document. Only eager `generate()` passes your `ctx` to the steps.
- **Each pipeline keeps its own previews.** A preview is identified by Resizer, pipeline, size, format and filters. Changing a pipeline's code does not regenerate existing previews; give the pipeline a new name, such as `photo-v2`, to do that, or remove its stored previews with [`invalidate()`](#operations). A pipeline may also set `version`, a string that is part of each preview's `encodeSig`: bump it when a step's output changes, and the pipeline's stored previews are regenerated on their next read (see [outdated previews](#operations)). Deploy the change to every worker at once.
- **Register a pipeline before you request it, in every process.** A name the Resizer doesn't know (any name but `default`) is never rendered: `resolve()` serves only previews already stored for it and queues nothing, `prewarm()` reports `RESIZE_PIPELINE_UNKNOWN`, and `generate()` and the worker throw it. When you add or rename a pipeline, deploy the worker before the API starts requesting it: a worker without the pipeline fails its tasks, retries them with backoff, and dead-letters them after the queue's `maxAttempts`. The worker itself needs the indexes first ([step 4](#add-the-queue-and-the-worker)), so create them through a migration that runs before both.
- **Pipelines are fixed at construction.** Pass every pipeline in `pipelines`; `getResizer().hasPipeline(name)` tells whether one is registered.

**Hooks** customize inputs and responses, or observe events. Register them with `hooks:` at construction or with `getResizer().hook(name, fn)`. TypeScript infers each signature from the hook name.

| Hook | Runs | Returns |
|---|---|---|
| `resolveSizes` | `generate()`, `prewarm()`, `resolve()` | The sizes to use |
| `beforeEnqueue` | `prewarm()` and `resolve()`, before queueing | The missing variants to keep |
| `formatPublicUrls` | `resolve()` | The value returned as `output` |
| `onPreviewGenerated` | After each new preview is saved | Nothing |
| `afterTaskComplete` | After a queued task stored every variant | Nothing |
| `onTaskFailed` | After a failed attempt that will be retried | Nothing |
| `onTaskDeadLettered` | After a task fails for the last time | Nothing |

Hook functions run in the order they were registered, and each one is awaited. A function that throws is logged and skipped. The three task hooks receive the task with its `attempts`: how many times it was delivered, this time included (1 on the first). The framework event bus also receives the four observer hooks (the last four rows) as `resize:<hookName>`.

## Drivers {/* #drivers */}

| Part | Config (`FrameworkResizer`) | Driver class | Import from |
|---|---|---|---|
| storage (required) | `storage: { driver: 'local' \| 's3', … }` | `LocalFsStorage`, `S3Storage` | `…/drivers/fs.js`, `…/drivers/s3.js` |
| media: your media documents (required) | always `FrameworkMediaStore` | `FrameworkMediaStore`, `MongoMediaStore` | `…/framework.js`, `…/drivers/mongo.js` |
| locks (SQS, or a custom queue that cannot gate) | `FrameworkLockStore`, used for a queue on SQS or beside a custom `tasks` without `gatesByTask` | `FrameworkLockStore`, `MongoLockStore` | `…/framework.js`, `…/drivers/mongo.js` |
| task queue (queued work only) | `queues: { <name>: { driver: 'database' \| 'sqs', … } }` and `queue: '<name>'` | `MongoTaskQueue`, `SqsTaskQueue`, and `RoutingTaskQueue` over queues on several backends | `…/drivers/mongo.js`, `…/drivers/sqs.js`, the main entry |

In a framework app you choose drivers in the config file; pass a driver object to `new FrameworkResizer({ storage, media, locks, tasks })` only when the config can't express it, for example your own S3 client. The S3 and SQS drivers are loaded only when selected; an SQS queue is checked for its `Lock` model by `verify()` only when it is the Resizer's own queue, so a Resizer on the database queue needs no `Lock` model even beside SQS queues.

The module itself runs the queue: the worker loop, the lease, retries with backoff, dead-lettering and the task events. A task queue driver only stores tasks, so Mongo and SQS behave the same. `FrameworkMediaStore` and `FrameworkLockStore` are thin wrappers over the framework-free `MongoMediaStore` and `MongoLockStore`: the first takes your media model from the app, and the second keeps locks, each with its owner, in the framework's own `Lock` model. The database task queue (every `queues` entry with `driver: 'database'`) is the `ResizeTask` model, and its rows also make sure that only one task per media, pipeline and queue is active, so it needs no locks.

**S3** needs `npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner` (3.572 or newer):

```ts
// src/config/resize.ts (or resize.production.ts)
storage: {
  driver: 's3',
  bucketPublic: 'my-cdn',        // previews
  bucketPrivate: 'my-originals', // originals; must differ from bucketPublic
  publicBaseUrl: 'https://cdn.example.com',
  region: 'eu-west-1',           // optional; also endpoint and forcePathStyle for S3-compatible stores
},
```

Credentials come from the AWS SDK's default chain, never from the config. To use an existing `S3Client`, pass `storage: new S3Storage({ …, client })` from `…/drivers/s3.js` in code instead. When an environment file switches `storage` from `local` to `s3`, set `publicBaseUrl` there too: the framework merges the section field by field. You create the buckets and their access policies; `publicBaseUrl` only builds URLs. The driver reads only from these two buckets, so a tampered `storageRef` cannot reach another bucket.

Every public object `S3Storage` uploads (previews and public raster originals, and a host's own direct uploads) carries `Cache-Control: public, max-age=31536000, immutable`. Every key the module writes is new, so an object never changes under its URL; if you call `S3Storage.upload` yourself, give every upload a new key, as the `ResizeStorage.upload` contract requires (the driver does not check). CDNs and browsers keep these objects up to a year, so purge your CDN when you delete one that must disappear sooner (browsers that already have it may keep it until it expires). Private objects get no cache header.

**SQS** needs `npm i @aws-sdk/client-sqs`, version 3.572 or newer: older clients don't return receive counts, so failing tasks would never be dead-lettered.

```ts
// src/config/resize.ts (or resize.production.ts)
queues: {
  default: {
    driver: 'sqs',
    queueUrl: 'https://sqs.eu-west-1.amazonaws.com/123456789012/resize',
    deadLetterQueueUrl: 'https://sqs.eu-west-1.amazonaws.com/123456789012/resize-dead', // optional
    region: 'eu-west-1',
    maxAttempts: 5, // the timing options work as for Mongo, per queue
  },
  bulk: { // optional; the same region and dead-letter queue keep it on the same backend
    driver: 'sqs',
    queueUrl: 'https://sqs.eu-west-1.amazonaws.com/123456789012/resize-bulk',
    deadLetterQueueUrl: 'https://sqs.eu-west-1.amazonaws.com/123456789012/resize-dead',
    region: 'eu-west-1',
  },
},
```

Each SQS entry is its own SQS queue: two entries with the same `queueUrl` are `RESIZE_CONFIG_INVALID`. `waitTimeSeconds` (the long poll, 10 by default) and `endpoint` are optional too.

SQS needs no `ResizeTask` model; media and locks stay in your database. SQS cannot tell that a task for a media is already queued, so the Resizer keeps one lock per media, pipeline and queue in the lock store (the framework's `Lock` model), `resize_gate:<resizer>:<queue>:<mediaId>:<pipeline>` with each part URI-encoded, while that task is queued, running, waiting for a retry, or cooling down after a dead-letter. This lock is best effort: when SQS does not confirm a send, the lock is kept for one lease, at most `coordination.gateTtlMs` (the message may have been stored), and a worker that lost its lease leaves the task alone, so at worst a second task renders the same variants and each preview is still stored once. Retries and dead-lettering work as with Mongo, and `onTaskDeadLettered` fires for SQS too. A redrive policy on the SQS queue is optional; if you keep one, set its `maxReceiveCount` above `maxAttempts`, so the module dead-letters a task first. A task whose lease ran out can still run twice on SQS; the worker skips previews that already exist.

**Custom drivers by name.** A driver of your own can be chosen in the config file like the shipped ones. Register it with the `drivers` option, by kind (`storage`, `database`, `queue`) and name; the config section then names it, and its type comes from the driver:

```ts
// src/resizer.ts
import { FrameworkResizer } from '@adaptivestone/framework-module-resize/framework.js';
import { GcsStorage } from './gcsStorage.ts'; // a class with static fromConfig(section, ctx)

export const resizer = new FrameworkResizer({
  pipelines: { default: {} },
  drivers: { storage: { gcs: GcsStorage } },
});

// src/config/resize.ts
//   storage: { driver: 'gcs', bucket: 'media' },
// } satisfies FrameworkResizeConfig<{ storage: { gcs: typeof GcsStorage } }>;
```

A driver is anything with a `fromConfig` function that builds the part from its section; a queue driver gets the entries of one backend, with optional `backendOf` and `validate` that group and check them before anything is loaded. `fromConfig` must not wait on the network: connecting and checking belong in the part's `verify()`. Your driver under a shipped name replaces the shipped one. A driver name the Resizer does not know is reported when the Resizer first reads that section (`RESIZE_CONFIG_INVALID`), and a `drivers` entry without `fromConfig` when the Resizer is constructed (`RESIZE_DRIVER_INVALID`). Every `FrameworkResizer` of the process shares its queues, so pass each one the same `drivers.queue` (`RESIZE_DRIVER_CONFLICT` otherwise). The [drivers-by-name reference](https://github.com/adaptivestone/framework-module-resizer#drivers-by-name) has the contract.

Every kind of driver has an exported abstract class: `ResizeStorage`, `MediaStore`, `LockStore` and `TaskQueue`. A custom driver extends one (for example `class RedisLockStore extends LockStore`), or is any object of the same shape, and replaces only its own part: `new FrameworkResizer({ locks: new RedisLockStore(redis) })` keeps the media store and the queue from the config. A lock store is used only beside SQS or a custom queue without `gatesByTask`; on the database queue only its `verify()` runs. Drivers receive no `app` argument; each one uses its own clients. The [package reference](https://github.com/adaptivestone/framework-module-resizer#drivers) lists every option and contract.

**Decoders** read the originals: `uploadOriginal()` measures an upload through them, and the worker renders every source through them. The built-in ones read the raster formats Sharp reads and SVG. To accept another kind of source, such as PDF, pass a decoder: `new FrameworkResizer({ decoders: [new PdfDecoder()] })`. A decoder extends `SourceDecoder`, is asked before the built-in ones, and must be passed in every process (API and worker); add its format to `upload.formats` too. The worker uses the stored `original.format` to pick the decoder to try first, so keep it as the decoder's ID (`jpeg`, `png`, `svg`, not `jpg` or a MIME type), as `uploadOriginal()` returns it. A value no decoder lists, or one whose decoder refuses the bytes, is logged as a warning and the bytes are probed, so the preview still renders; fix the record to silence the warning. The [decoder reference](https://github.com/adaptivestone/framework-module-resizer#decoders) has the contract.

## Originals, SVG and private access

Previews are public. Store originals privately (`visibility: 'private'`). Your app decides who may upload, read and delete media.

- **SVG is untrusted.** An SVG file can contain scripts and external references, so the module never serves SVG markup, not even to its owner.
  - `uploadOriginal()` accepts SVG only with `visibility: 'private'`.
  - The generator renders it into your raster formats and never loads anything the file references. The render runs in a separate Node process and is killed after `limits.processingTimeoutSeconds` or when the task stops. Your app must allow child processes (`--allow-child-process` under Node's permission model), and a bundle must keep `svgRasterChild.js` next to `svgRaster.js`.
  - The stored file is not cleaned, so never serve it yourself.
- **The module never serves an original.** `resolve()` returns stored previews only, whoever reads; `ctx` reaches your hooks but does not change the result. A small raster original gets a preview at its own size instead, unless the pipeline has `variantSteps` (see [sizes](#sizes-and-formats)).
- **To give an owner the private original,** check access in your app and call the storage driver yourself. `S3Storage` signs URLs; `LocalFsStorage` has no `signedUrl`.

  ```ts
  const resizer = getResizer();
  await resizer.ready(); // loads the drivers built from the config
  const url = await resizer.storage.signedUrl?.(fileDoc.original.storageRef, 300); // valid for 5 minutes
  ```

## Without the framework

The core and the shipped drivers contain no framework code, and the framework is an optional peer dependency.

### `createResizer` {/* #create-resizer */}

A plain Node app describes its Resizer in one config object, the same sections a framework config file has, and builds it with one call:

```ts
import mongoose from 'mongoose';
import { createResizer, runWorker } from '@adaptivestone/framework-module-resize';

export const resizer = createResizer({
  formats: ['webp'], // image settings, merged over the package defaults
  storage: { driver: 'local', rootDir: './var/media', publicBaseUrl: '/media' },
  database: { driver: 'mongo', connection: mongoose.connection, mediaModel: File }, // File spreads resizeMediaSchemaFragment
  queues: { default: { driver: 'database' } },
});

// In the worker process:
await runWorker({ signal: shutdown.signal, queue: 'default' });
```

Options in the second argument win over the config (`pipelines`, `hooks`, your own `storage` or `tasks`, `drivers`, …). Only the drivers the config names are loaded, and every part is built on first use. Each `createResizer` call builds its own queues; Resizers that should share one are wired by hand, as below. The [package reference](https://github.com/adaptivestone/framework-module-resizer#without-the-framework) lists every section and option.

### Wired by hand

```ts
import mongoose from 'mongoose';
import { Resizer, runWorker } from '@adaptivestone/framework-module-resize';
import defaultResizeConfig from '@adaptivestone/framework-module-resize/config/resize.js';
import { LocalFsStorage } from '@adaptivestone/framework-module-resize/drivers/fs.js';
import { mongoParts } from '@adaptivestone/framework-module-resize/drivers/mongo.js';

// { media, locks, tasks }: your media model, and locks and the task queue on the package's
// ResizeLock / ResizeTask models. Call it once: each call makes its own task queue, so spread the
// same parts into every Resizer.
const parts = mongoParts(mongoose.connection, { mediaModel: File }); // File spreads resizeMediaSchemaFragment

const resizer = new Resizer({
  config: { ...defaultResizeConfig, formats: ['webp'] },
  storage: new LocalFsStorage({ rootDir: './var/media', publicBaseUrl: '/media' }),
  ...parts, // eager only: media: new MongoMediaStore({ model: File }) instead (no queue or lock models)
});

// In the worker process:
await runWorker({ signal: shutdown.signal, queue: 'default' });
```

- `mongoParts()` registers `ResizeTask` (the queue) and `ResizeLock` (the locks) on that connection with the package's schemas and indexes, and turns `autoIndex` off: create the indexes of both through your migration process (for example `await mongoose.connection.models.ResizeTask.createIndexes()`, and the same for `ResizeLock`). For other setups, `new MongoMediaStore(…)`, `new MongoLockStore(…)` and `new MongoTaskQueue(…)` take your models directly.
- `storage` and `media` are required. `locks` is required only beside a task queue that cannot keep one task per media, pipeline and queue by itself, such as `SqsTaskQueue`; `MongoTaskQueue` needs none, and the parts include a lock store anyway. To swap one part, set it after the spread, for example `tasks: new SqsTaskQueue({ queueUrl })`.
- `config` is optional and holds image settings only. Queue timing (`leaseMs`, `maxAttempts`, …) belongs to the task queue (`mongoParts(…, { timing })`, `new SqsTaskQueue({ timing })`; `getTiming(queue)` on `MongoTaskQueue` and `SqsTaskQueue` gives one queue its own). A Resizer's queue is its `queueName` option (`'default'` when omitted). How long the gate lock holds a media, pipeline and queue (one gate per Resizer, media, pipeline and queue) and a dead task blocks new ones is the Resizer's `coordination` option, `new Resizer({ coordination: { gateTtlMs, cooldownMs } })` (see the [package reference](https://github.com/adaptivestone/framework-module-resizer#coordination)). Sharp tuning is `runWorker({ sharp: { concurrency, cache } })`.
- A task queue passed in code without the `locks` it needs, or an invalid `coordination`, does not break your app: the Resizer logs the error once, `resolve()` still serves the stored previews (it just queues nothing), uploads and `generate()` work, and `prewarm()` reports the error. Only `await resizer.verify()` and the worker reject with it (`RESIZE_LOCKS_REQUIRED` or the coordination error), so call `verify()` at startup to stop such a deploy. Invalid timing of a queue is checked per queue: `verify()` rejects for the Resizer's own queue, the worker for the queues it consumes, `prewarm()` reports it, and `resolve()` logs it once per queue on its first read. For a `FrameworkResizer` that takes its task queue from the config file (or whose file sets no `queue`), invalid timing in a `queues` entry of `src/config/resize.ts`, or a malformed `queues` or `worker` section, is still a config error at the first call and in `verify()`, like the rest of the file: `uploadOriginal()`, `generate()` and `invalidate()` throw it, and `resolve()` and `prewarm()` return the empty decision and `incomplete`, so even stored previews are not served until the file is fixed. A `FrameworkResizer` with a task queue passed in code (and no `coordination` in code) reads that file only for `coordination`, so a broken file behaves as described here, like an invalid `coordination` section.
- `storage`, `media`, `locks` and `tasks` may also be functions, sync or async, called once on first use; `await resizer.ready()` loads them, and the Resizer's own methods do it for you.
- `runWorker()` serves the Resizers constructed in its process when it starts, or the ones you pass as `resizers`. Construct every Resizer before you start it: one constructed later is not served. The worker asks the queue only for tasks of the Resizers it serves; the database queue honours that, so it never hands the worker another Resizer's task. SQS cannot: a task for a Resizer the worker does not serve is never run there, but goes back to the queue for a worker that serves it. SQS counts the receive, so such a task can still reach `maxAttempts` on the worker that serves it. A custom queue that can neither filter nor give tasks back retries such a task as before: it fails with `RESIZE_NO_RESIZER` and is dead-lettered after `maxAttempts`. The worker logs each such Resizer once. If you pass a list and a task queue the worker consumes cannot filter (SQS), the list must include every Resizer of the process that uses that queue; otherwise the worker would take their tasks without running them, so it stops at start with `RESIZE_QUEUE_SHARED_RESIZER_UNLISTED`. With `queues` on more than one available backend, every `FrameworkResizer` that takes its task queue from the config file shares one router that reaches every queue, so a list for a worker that consumes a queue on SQS must name all of them, whatever their own queue (`npm run cli ResizeWorker` serves every Resizer, so it needs no list). Two Resizers in the list need two names.
- Push delivery (an SQS-triggered Lambda) is not supported in 0.3.0: run the worker (`runWorker()`, or `npm run cli ResizeWorker` in a framework app) as a long-lived process.
- The framework adapter (`…/framework.js`) does exactly this wiring for you, from the config file.

## Configuration

`src/config/resize.ts` spreads `defaultFrameworkResizeConfig` (from `…/framework.js`) and adds `mediaModelName`, `storage`, `queue` plus your changes. It also holds the process-wide `queues`, `worker` and `coordination`, which no other file may set. The framework merges `resize.<NODE_ENV>.ts` over it (write that file `satisfies Partial<FrameworkResizeConfig>`, or `satisfies PartialFrameworkResizeConfig` when it leaves out nested keys): objects merge field by field, and arrays are replaced. The module then merges the image settings over the package defaults the same way (`encode.formats` is replaced whole), so a file may set only what it changes. The image settings go to the Resizer; `FrameworkResizer` builds the drivers from `storage` and the `queues` entry its `queue` names, and the worker command reads `worker` and `queues`.

| Option | Default | Meaning |
|---|---|---|
| `mediaModelName` | required | Your media model's name |
| `storage` | required (unless passed in code) | `{ driver: 'local', rootDir, publicBaseUrl, privateRootDir? }` or `{ driver: 's3', bucketPublic, bucketPrivate?, publicBaseUrl?, region?, endpoint?, forcePathStyle? }`, or the section of a [driver you register](#drivers) |
| `queue` | `'default'` when `queues` has entries, else eager only | The name of this Resizer's queue (a key of `queues`), or `false` = eager only |
| `queues` | none (a Resizer with no `queue` key is then eager only) | Process-wide. Every queue by name: `{ driver: 'database' }` or `{ driver: 'sqs', queueUrl, deadLetterQueueUrl?, waitTimeSeconds?, region?, endpoint? }` (or a registered queue driver's section), plus that queue's timing options below. Queues may be on different backends. An entry set to `undefined` is not defined: set one to `undefined` in an environment file to remove it there |
| `formats` | `['jpeg', 'webp', 'avif']` | Formats generated when a call doesn't pass `formats`; each needs an `encode.formats` entry |
| `upload.maxBytes` | 25 MiB | Largest original `uploadOriginal()` accepts |
| `upload.formats` | `jpeg`, `png`, `webp`, `avif`, `gif`, `svg` | Original formats `uploadOriginal()` accepts |
| `maxSize` | `{ width: 2000, height: 1200 }` | The box for `fit` |
| `encode.formats` | JPEG quality 88, WebP 82, AVIF 64 | Sharp encoder options per format; `{}` keeps Sharp's defaults |
| `animated` | `false` | `true`: WebP and GIF previews of an animated original keep its frames (up to `limits.animationFrames`, 64), unless the pipeline has `beforeSteps` or `variantSteps`; other formats and pipelines with steps use the first frame |
| `concurrency` | `4` | Variants processed in parallel per task or `generate()` call |
| `worker.enabled` | `false` | Process-wide. Allows the worker command to run; every `worker` key is optional, and an unknown one (a misspelled `sharpConcurency`, say) is `RESIZE_CONFIG_INVALID` |
| `queues.<name>.maxAttempts` | `5` | Attempts before a task is dead-lettered |
| `queues.<name>.leaseMs` | `60000` | The task lease: how long a worker holds a task between heartbeats |
| `coordination.gateTtlMs`, `coordination.cooldownMs` | `600000`, `600000` | Process-wide. How long the lock of a QUEUED task holds its media, pipeline and queue before a worker starts the task (the worker then holds it through the task; raise it when tasks wait longer in the queue), and how long reads queue nothing for a media, pipeline and queue after its task was dead-lettered. The lock exists only with a queue that cannot gate (SQS). On Mongo a dead task is kept about 30 days, so a longer cooldown ends with it |
| `queues.<name>.retryBackoffMs`, `queues.<name>.idlePollMs`, `queues.<name>.taskTimeoutMs` | `{ base: 5000, max: 300000 }`, `1000`, `600000` | Retry delay, how often an idle worker polls for new tasks (one indexed query per worker on Mongo), and the task time limit |

To change one encoder setting, spread the nested defaults:

```ts
encode: {
  ...defaultFrameworkResizeConfig.encode,
  formats: { ...defaultFrameworkResizeConfig.encode.formats, avif: { quality: 55, effort: 4 } },
},
```

The [full config reference](https://github.com/adaptivestone/framework-module-resizer#config-reference) covers limits, sharpening, animation, queue timing and coordination. Keys renamed since 0.2, and the earlier queue shape, fail with `RESIZE_CONFIG_REMOVED_KEY`:

| Old key | Use instead |
|---|---|
| `webpAvifOnly: true` | `formats: ['webp', 'avif']` |
| `encode.quality.<format>`, `encode.effort.<format>` | `encode.formats.<format>.quality`, `encode.formats.<format>.effort` |
| `encode.mozjpeg`, `encode.chromaSubsampling` | `encode.formats.jpeg.mozjpeg`, `encode.formats.jpeg.chromaSubsampling` |
| `encode.flattenBackground` | `encode.flatten.background` |
| `worker.concurrency` | the top-level `concurrency` |
| `queue: { driver, … }` | `queues: { default: { driver, … } }` in `src/config/resize.ts`, and `queue: 'default'` |
| `queue.queues: { bulk: url }` (SQS) | one `queues` entry per name: `bulk: { driver: 'sqs', queueUrl: url, … }` |
| `queue.lockTtlMs` (or `queues.<name>.lockTtlMs`) | `coordination`: `dispatch` → `gateTtlMs` (a different lock: the old one held one variant for 60 s, the new one holds a queued task's media; set it to your worst queue wait), `failed` → `cooldownMs`; drop `worker` |
| `npm run cli ResizeWorker -- --config=<name>` | nothing: the worker reads `worker` and `queues` from `src/config/resize.ts` |

After the upgrade, `resize-scaffold --check` reports every `src/config/resize.ts`, and every `resize.<NODE_ENV>.ts` override of it, written for an earlier version (a top-level `queue: { … }` object, or `defaultFrameworkResizeConfig` imported from `…/config/resize.js`; only full-line `//` comments are skipped, and a second Resizer's `configName` file is not checked), and every ejected `ResizeTask` model without `startedAt` and `finishedAt`. That is intended: rewrite the config to the shape above, and add both fields as `{ type: Date }` (or move `src/models/ResizeTask.ts` aside (or delete it), run `resize-scaffold --eject` again, then restore your customizations; the scaffold never overwrites a file, so running `--eject` again alone changes nothing). Such a model keeps working, without the two times.

## Errors

`resolve()` and `prewarm()` never throw: they log the failure and return a safe result (`prewarm()` reports it as an issue). Every other error from the module extends `ResizeError` and carries a stable `code`:

| Error | Meaning | What to do |
|---|---|---|
| `ResizeSetupError` | The wiring is wrong, e.g. a duplicate Resizer name | Fix the code |
| `ResizeConfigError` | The config is invalid or incomplete | Fix the config; `resizer.verify()` reports it at startup |
| `ResizeOriginalError` | Uploaded bytes are invalid, unsupported or too large | Reject the upload |
| `ResizeNoOriginalError` | The media has no original | Upload the original first |
| `ResizeMediaError` | The media can't be used; the two errors above extend it | Skip that media |
| `ResizeGenerateError` | `generate()` made nothing, or a queued task left variants missing | Check `failed`, `requested`, `missing` and the logs |
| `ResizeStorageError` | A storage operation failed | A retry may help |
| `ResizeSecurityError` | A refused storage access, such as path traversal | Never retry; investigate |

```ts
import { ResizeError, ResizeNoOriginalError } from '@adaptivestone/framework-module-resize';

try {
  await getResizer().generate({ media: fileDoc, sizes: thumbnailSizes });
} catch (err) {
  if (err instanceof ResizeNoOriginalError) return badRequest('Upload the image first');
  if (ResizeError.isResizeError(err)) return badRequest(err.message);
  throw err; // not from this module
}
```

If two copies of the package are installed, `instanceof` can fail across them. `ResizeError.isResizeError(err)` still works in that case.

Each error also has `retryable`. The worker reads it on the error that fails a queued task, when that error is a `ResizeError` (also one from a second copy of the package): with `retryable: false` it dead-letters the task at once instead of retrying, for example when the media has no original or the image exceeds the pixel limits. Errors from other libraries are always retried, even if they carry a `retryable` field of their own. That covers errors from loading the media, downloading the original, the decoder's checks and render, `beforeSteps`, and saving the previews, so your own errors there can stop the retries the same way: throw a `ResizeError` subclass with `retryable: false`, for example `new ResizeMediaError('…', { retryable: false })`. An error inside one variant (`variantSteps`, encoding, uploading the preview) fails only that variant; the task then fails with the retryable `RESIZE_WORKER_INCOMPLETE` and is retried for the missing variants. The [operations reference](https://github.com/adaptivestone/framework-module-resizer#operations) lists the codes that set `retryable: false`.

## Metrics {/* #metrics */}

Every Resizer reports its reads, uploads, rendered variants, task outcomes and the worker's waits to a metrics sink. By default it is `LogMetrics` on the Resizer's `logger` option, else the app logger:

- **One summary line per minute** per Resizer, at `info`, when something happened: `resize: Resizer 'default' over 60 s: reads 1200 (ready 1150, enqueued 12, in-flight 38), stale previews found 40, uploads 25 (31457280 bytes), variants 75 (5242880 bytes), claims 12 (average wait 840 ms)`.
- **One line per task outcome** (`completed`, `failed`, `dead`) and per failed variant, at once.
- **One `debug` line per event**, which that logger may drop.

A read no longer writes a log line per request: a media without an original is only counted, and an unknown pipeline, a format without encoder settings or a missing queue is logged once. Every read is counted, with its outcome.

Pass `metrics` to change this:

```ts
import { NoopMetrics } from '@adaptivestone/framework-module-resize';

new FrameworkResizer({ pipelines, metrics: new NoopMetrics() }); // off
```

A custom sink extends `ResizeMetrics` with `count(name, value, labels, context)` and `timing(name, ms, labels, context)`; group by `labels` only, since `context` holds ids for logs. The worker writes the open summary when it stops; in the API, call `await getResizer().metrics.flush?.()` at shutdown. The [metrics reference](https://github.com/adaptivestone/framework-module-resizer#metrics) lists every event, its labels, the line formats and a Prometheus example.

## Operations and troubleshooting {/* #operations */}

- **Task states.** Mongo tasks go `pending → processing → completed`. A failed attempt returns to `pending` with a growing delay. After the queue's `maxAttempts`, the task becomes `dead`. `startedAt` records when the latest attempt started and `finishedAt` when the task completed or died, for inspection only. A media and pipeline have at most one active task per queue (`active: true` on its row) from the moment it is queued until it completes, or, after a dead-letter, until `coordination.cooldownMs` has passed; the next `add()` then takes the gate over (it retires the dead row and stores a new task).
- **Partial attempts.** A task completes only when every requested variant is stored. When an attempt is only partly successful, its previews are saved and the next attempt makes only the missing ones.
- **Cleanup and retries.** Completed tasks are removed after about 24 hours and dead tasks after about 30 days. A dead task's cooldown holds only its own queue: a read or pre-warm on another queue queues the work again, so a task that always fails gets one `maxAttempts` cycle on each queue it is sent to. To retry a dead task after fixing its cause, call `prewarm()` again for that media once `coordination.cooldownMs` (10 minutes by default) has passed since the task died; until then it reports a retryable issue.
- **One row per preview.** The media store keeps each preview identity once. When two workers render the same preview, the second upload is logged as a warning with its storage location and is not recorded; delete such files if you need to.
- **Outdated previews.** Each preview row records `bytes`, `createdAt`, `origin` (the original it was made from) and `encodeSig` (the settings it was encoded with). A row whose signatures differ from what the current settings would record is outdated (stale): made from another original, with other encode settings or limits, with another pipeline `version`, or without `origin` and `encodeSig` (written by 0.2.x or earlier). It is still served, and it is made again on its next read, `prewarm()` or `generate()`; the new row replaces it in one write. Each replacement costs a render and an upload, and the old file stays in storage: clean up from the log line "resize: replaced … outdated preview(s) of media …; their files are not deleted: storage refs …", or sweep preview objects that no row references. After a settings change the regeneration wave shares the queue with new uploads, so plan worker capacity. An app without a queue serves outdated previews until it calls `generate()`. Pass `resolve()` the media's `original` as stored: a projection without `original.width` and `original.height` makes every preview look outdated. New bytes under the same `original.storageRef` and at the same size are not detected: after replacing an original in place, call `invalidate()` for that media. The [freshness reference](https://github.com/adaptivestone/framework-module-resizer#freshness) lists every rule.
- **Rolling out a settings change.** The API and the workers must run the same image settings and pipeline versions. Deploy every worker at once, or change the settings only after the old workers have stopped. While two worker versions with different settings run side by side, each makes the other's previews again: every read after a task ends queues them again, and each replaced preview costs one render, one upload and one orphaned file.
- **Removing previews.** `invalidate()` removes a media's stored previews, of one pipeline or of all, in one write, and returns their storage refs. It never deletes files and never queues; delete the files yourself, and the next read or `prewarm()` queues new previews:

  ```ts
  const refs = await getResizer().invalidate({ media: fileDoc, pipeline: 'photo' }); // omit pipeline: every pipeline
  // delete each ref's object with your own storage client
  ```

  Only an omitted `pipeline` means every pipeline. It also removes the rows from `fileDoc.previews`, so a `resolve()` in the same request does not serve them. It takes no lock: a task running for that media can still store previews after it returns. Reload the media before saving it after `generate()` or `invalidate()`; the module wrote the rows itself. Rows without an `identity` (written before 0.3.0) are never removed: delete their files yourself.
- **Throughput.** A worker processes one task at a time from each backend and queue it consumes, and `concurrency` parallelizes the variants within it. For more throughput, run more worker processes.
- **Shutdown.** On SIGTERM or SIGINT the worker stops claiming tasks, lets the variants in progress finish and saves them, and puts the task back in the queue without an `onTaskFailed` event or a retry delay; the next worker makes the rest. A task that failed with a non-retryable error, such as a missing original, is still dead-lettered. With the database queue this does not count as an attempt; with SQS it does. Custom queues: see the `release` method in the [package reference](https://github.com/adaptivestone/framework-module-resizer#drivers).

| Symptom | Check |
|---|---|
| Worker exits with "disabled" | `worker.enabled: true` in `src/config/resize.ts` (the worker reads no other file) |
| `resize-scaffold --check` reports `src/config/resize.ts`, a `resize.<NODE_ENV>.ts` override or `src/models/ResizeTask.ts` right after the upgrade | Intended for a config or an ejected model written for an earlier version: see the [old keys](#configuration) |
| `RESIZE_CONFIG_QUEUE_UNKNOWN` at the first call or from `verify()` | The Resizer's queue (its `queue`, its `queueName` option, or the implied `'default'`) is not an entry of `queues` in `src/config/resize.ts`: add it, or, for eager only, set `queue: false` in the file, or `tasks: false` in code when the name came from the `queueName` option (the option wins over the file) |
| `RESIZE_CONFIG_INVALID` saying a section "is process-wide" | `queues`, `worker` or `coordination` is in another config file (or in the `config` option): move it to `src/config/resize.ts` |
| `RESIZE_CONFIG_REMOVED_KEY` naming `queue`, `queues.<name>.queues` or `--config` | The earlier queue shape: see the [old keys](#configuration) |
| `RESIZE_QUEUE_NOT_SERVED` in `prewarm()` issues, or a warning from `resolve()` that the Resizer "cannot queue to" a queue | The call's `queue` is not defined in `queues`, or its backend's AWS SDK is not installed in that process (the message names the package): define the queue, or install the package. A queue on another backend is routed and needs nothing |
| `RESIZE_ENQUEUE_QUEUE_FAILED` with a `causeCode` in `prewarm()` issues | The backend of the call's queue could not be built; `causeCode` is the driver's error code (for example `RESIZE_PEER_MISSING`), and `retryable` is the error's own. The next call tries again |
| `RESIZE_ENQUEUE_LOCK_FAILED` with `causeCode: 'RESIZE_LOCKS_REQUIRED'` | The call's queue is on SQS (or a custom queue that cannot gate) and the Resizer has no lock store: pass `locks`, or give a framework app its `Lock` model |
| `RESIZE_DRIVER_INVALID` | A `drivers` entry has no `fromConfig` function (reported when the Resizer is constructed), or a driver built something that is not the part it should (on first use) |
| `RESIZE_DRIVER_CONFLICT` when a `FrameworkResizer` is constructed | Every `FrameworkResizer` of the process, an eager-only one too, must pass the same `drivers.queue`; an app that passes no `drivers` anywhere never sees it |
| `RESIZE_QUEUE_ROUTES_INVALID` from `new RoutingTaskQueue()` | A route is neither a task queue that serves its own name nor a function that builds one |
| `RESIZE_CONFIG_INVALID` saying a section "needs driver …" | The config names a driver the Resizer does not have: fix the name, or register the driver with `drivers`. It is reported when the Resizer first reads that section, on first use or by `verify()` (the `storage` of a config object passed in code, at construction) |
| `RESIZE_CONFIG_QUEUE_INVALID` or `RESIZE_CONFIG_QUEUE_LEASE_INVALID` | A queue's timing is invalid: fix the key the message names. `verify()` rejects for the Resizer's own queue and the worker for the queues it consumes; a call on that queue reports it (`prewarm()`) or logs it once (`resolve()`) |
| `verify()` or the worker fails with `RESIZE_MEDIA_REPLACE_MISSING`, or `generate()` and the worker fail with it when an outdated preview is replaced | A custom `MediaStore` lacks `replacePreviews(mediaId, identities, rows)`, which 0.3.0 requires: see the `MediaStore` contract in the [package reference](https://github.com/adaptivestone/framework-module-resizer#drivers) |
| `RESIZE_METRICS_INVALID` when the Resizer is created | `metrics` is not a sink (`null`, or no `count()` and `timing()`), or `LogMetrics` got a `summaryIntervalMs` that is not a positive whole number: pass `new LogMetrics(logger)`, `new NoopMetrics()` or your own `ResizeMetrics`, or leave `metrics` out |
| Previews are made again after a config change or an upgrade | Expected: they are [outdated](#operations). It costs a render and an upload per preview, and the old files stay: clean them up from the "replaced … outdated preview(s)" log line, or sweep files no row references |
| One task per read that makes nothing, and the warning "found every requested preview … already fresh" | The API and the worker run different image settings or pipeline versions (deploy them together), or `resolve()` got the media without its stored `original` (a projection that drops `original.width` and `original.height`) |
| Previews made again and again during a deploy | Two worker versions with different settings run side by side and each makes the other's previews again: deploy every worker at once, or change settings after the old workers have stopped |
| Worker warns "the media store did not record the original's dimensions", or tasks fail with a Mongoose `StrictModeError` or `CastError`, are retried and dead-lettered with no previews | A custom `MediaStore` drops `backfillDims` in `appendPreviews` (also with `previews: []`), so every read of such a media queues a task that downloads the original: save the dimensions on the original. The shipped `MongoMediaStore` drops them too when the media schema declares `original` strictly (nested paths, or a sub-schema without `strict: false`) without `width` and `height`, or stores them with the wrong type when they are declared as a type that does not read back as a number (not Number, Int32 or Mixed). Under `strict: 'throw'`, or with a type Mongoose cannot cast them to (`Boolean`, `ObjectId`), the backfill is rejected instead: the task fails, is retried and is dead-lettered after `maxAttempts`. In each case its `verify()` warns once, naming the cause: spread `resizeMediaSchemaFragment`, or declare `width` and `height` as `{ type: Number }` in `original` |
| Previews written by 0.2.x or earlier are made again | They have no `origin` or `encodeSig`, so they are outdated: each is replaced on its next read, and its old file stays. Rows without an `identity` (before 0.3.0) are never removed, and a sweep never finds their files: delete those yourself |
| Worker stops at start with `RESIZE_NO_RESIZER` | `src/commands/ResizeWorker.ts` must import `../resizer.ts`; delete the old file and run `resize-scaffold` again |
| Worker logs that a Resizer "is not served by this worker", or `RESIZE_NO_RESIZER` for a task | An SQS (or custom) queue handed the worker a task of a Resizer it doesn't have. That Resizer must be created in `src/resizer.ts`. Until then its tasks go back to the queue, or, on a queue that cannot give tasks back, are retried and then dead-lettered. On the database queue such tasks wait for a worker that has the Resizer |
| `verify()` or the worker fails with `RESIZE_MONGO_MODEL_MISSING` | The `ResizeTask` model is not registered (scaffold `src/models/ResizeTask.ts`), or the framework's `Lock` model is missing while the Resizer's own queue (for `verify()`) or a queue the worker consumes is on SQS |
| `verify()` or the worker fails with `RESIZE_MONGO_MODEL_OUTDATED`, or your app logs it once and reads queue nothing | Your ejected or hand-written `ResizeTask` model lacks the `resizer`, `queue`, `availableAt`, `active` or `cooldownUntil` field: add them (and the `{ queue, status, availableAt }` index and the gate index), or delete the file and run `resize-scaffold --eject` again |
| `verify()` or the worker fails with `RESIZE_MONGO_INDEX_MISSING`, or your app logs "reported a task in flight without its id" | The `ResizeTask` collection has no gate index: unique on `{ resizer: 1, fileId: 1, pipeline: 1, queue: 1 }` with `partialFilterExpression: { active: true }` (the filter may also be written `{ active: { $eq: true } }`), or the collection does not exist yet, or an index on those keys lacks `unique` or the partial filter, or Mongoose's own index build failed (see the error's cause). Create it through your migration; the module never creates indexes |
| `verify()` or the worker fails with `RESIZE_MONGO_NOT_CONNECTED` | The MongoDB connection is not open, or failed to open (reported once the driver gives up, after its `serverSelectionTimeoutMS`, 30 s by default; the message names the driver error): call `verify()` after the connection has opened (after `server.init()`); a connection that is still opening is awaited |
| `verify()` or the worker fails with `RESIZE_MONGO_MEDIA_MODEL_OUTDATED` | Your media schema declares preview entries as strict sub-documents without `identity`, `origin` or `encodeSig`: spread the current `resizeMediaSchemaFragment`, or add each missing field to the entry as `{ type: String }` |
| Worker logs `RESIZE_SVG_RENDER_TIMEOUT` or `RESIZE_SVG_RENDER_FAILED` | An SVG took longer than `limits.processingTimeoutSeconds` to render (dead-lettered at once), or its render process crashed (retried) |
| `RESIZE_SVG_RENDER_UNAVAILABLE` from the worker or `generate()` | The SVG render process cannot start: allow child processes (`--allow-child-process` under Node's permission model), and keep `svgRasterChild.js` next to `svgRaster.js` when bundling |
| `RESIZE_DECODER_MISSING` from the worker or `generate()` (retried) | No decoder in that process lists the stored `original.format`, and none reads the bytes: pass the decoder in `decoders` in every process, or fix an `original.format` that holds an alias |
| `RESIZE_SOURCE_FORMAT_UNSUPPORTED` (dead-lettered at once), or `RESIZE_ORIGINAL_FORMAT_UNSUPPORTED` from `uploadOriginal()` | Every decoder refused the bytes: no decoder reads that format. Add a decoder for it, or reject the file |
| Worker warns that a media "is stored as '…' but its bytes are '…'" | `original.format` holds an alias such as `jpg`, a MIME type or a wrong format. The preview renders; fix the record to the decoder's ID |
| `RESIZE_SOURCE_DECODE_FAILED` | Sharp (or your decoder) could not decode the original; the error's cause says why. Retried, then dead-lettered |
| `RESIZE_DECODER_INVALID` | A `decoders` entry is not a decoder, or a decoder broke the contract (what its `inspect` reported, or the raster it returned) |
| `RESIZE_PIPELINE_STEP_INVALID` | A `beforeStep` resolved with something that is not a one-frame `Raster`, such as a `Buffer` or a Sharp object, or `sharpToRaster` got a multi-page image: return `sharpToRaster(…)` |
| Sharp's "Input file is missing" from a `beforeStep` | An old step still calls `sharp(buf)` on its first argument, which is now a `Raster`: rewrite it as `async (r) => sharpToRaster(rasterToSharp(r)…)` |
| `verify()` or the worker fails with `RESIZE_CONFIG_MEDIA_MODEL_UNKNOWN` | `mediaModelName` must name a registered model |
| `verify()` or the first call fails with `RESIZE_PEER_MISSING` | The S3 or SQS driver selected in the config (a config file or a `createResizer` config) needs its AWS SDK packages: install the ones named in the message. An SQS queue beside queues on another backend is only not served in that process (`RESIZE_QUEUE_NOT_SERVED`); `verify()` reports `RESIZE_PEER_MISSING` when it is the Resizer's own queue |
| `RESIZE_PIPELINE_UNKNOWN` in `prewarm()` issues, from `generate()` or in worker logs | That process has no pipeline with this name: register it in `src/resizer.ts`, and deploy the worker before the API |
| `RESIZE_FORMAT_NOT_CONFIGURED` | A call or a `beforeEnqueue` hook asked for a format without an `encode.formats` entry, such as `'jpg'`: use a configured format ID |
| Tasks stay `pending` | Is a worker running for that queue (`--queue`), on the same database? Such a task holds back new tasks for its media and pipeline on that queue only |
| `verify()` or the first upload fails with `RESIZE_CONFIG_STORAGE_MISSING` | Add `storage: { driver: 'local', … }` (or `'s3'`) to the config file named in the message |
| Worker stops with `RESIZE_QUEUE_NOT_SERVED` | No task queue serves a queue it was given, for example a `--queue` name that `queues` does not define (with several `--queue` flags, the message names the one), or a queue whose backend's AWS SDK is not installed (the message names the package): define it, install the package, or start the worker for other queues |
| Worker stops with `RESIZE_QUEUE_INVALID` | `--queue` (or `runWorker({ queue })`) got an empty name or an empty list |
| Worker stops with `RESIZE_QUEUE_SHARED_RESIZER_UNLISTED` | The `resizers` list leaves out a Resizer that uses the same SQS (or other non-filtering) task queue: add it to the list, or give it its own task queue. With `queues` on more than one available backend, every `FrameworkResizer` that takes its task queue from the config file reaches every queue, so list all of them |
| `verify()` or the worker fails with `RESIZE_LOCKS_REQUIRED`, while reads still work | A Resizer without the framework has an SQS (or custom) task queue but no `locks`: spread the parts of `mongoParts()`, or pass a lock store |
| `verify()` or the worker fails with `RESIZE_CONFIG_COORDINATION_INVALID`, while reads still work | `coordination` is not an object (`null` included), or a value in it is not a positive whole number of milliseconds |
| `RESIZE_TASK_IN_FLIGHT` in `prewarm()` issues | A task for this media, pipeline and queue is still active, or cooling down after a dead-letter, and does not include these variants: call `prewarm()` again after it ends |
| Variants are missing but there are no tasks | `enqueueMissing`, the original's `storageRef`, the indexes, hooks and logs; `prewarm()` reports the reason per variant |
| Tasks fail repeatedly | Original access, image limits, pipeline code and worker logs; `RESIZE_WORKER_INCOMPLETE` lists the missing variants |
| `previews[]` has entries but the response is empty | The query projection (`resizeMediaPaths`), stale caches, or how you map `decision` |
| A returned URL gives 404 or 403 | Static-file, CDN or bucket access; the module doesn't check whether the file exists |

Your app owns replacing and deleting media and their storage files (the module only adds preview rows, and `invalidate()` only removes rows and returns their refs), access checks, and refreshing cached responses (public S3 objects are cached for a year: purge your CDN when you delete one that must disappear sooner; browsers that already have it may keep it until it expires).


---


# Document 18: 13-deploy

<!-- Source: 13-deploy.md -->

# Deployment and process lifecycle

Run each application process through exactly one supervisor. Docker,
Kubernetes, systemd, and PM2 already manage replica count and restarts, so they
should normally run the framework's single-process server entry. Use the
framework cluster runner only when one Node primary should supervise multiple
workers on the same host.

Do not nest supervisors. For example, do not run `runCluster()` inside PM2
cluster mode or start several clustered processes in one Kubernetes pod.

:::note HTTP/1.1 only — terminate TLS and HTTP/2 at your proxy
The framework serves **plain HTTP/1.1** (`http.createServer`); it does not implement TLS or HTTP/2.
That is the normal shape for a Node service: your load balancer, ingress, or CDN speaks HTTPS and
HTTP/2 to clients and forwards HTTP/1.1 to the app. Configure certificates there, not here.
:::

## Single process under an external supervisor (recommended)

Keep server construction in a dedicated module:

```ts title="src/server.ts"
import Server from '@adaptivestone/framework/server.js';
import folderConfig from './folderConfig.ts';

const server = new Server(folderConfig);
await server.startServer();
```

Run that entry directly:

```bash
NODE_ENV=production node src/server.ts
```

Since 5.4.2 the port opens only once every route, `bootHttp` hook and error handler is mounted, so a TCP readiness probe never reaches a half-booted server.

### PM2

Install PM2 and configure it to start with the host:

```bash
npm install pm2@latest -g
pm2 startup
```

Start one application process. PM2 owns its restart lifecycle:

```bash
NODE_ENV=production pm2 start src/server.ts --name YOUR_APP_NAME
pm2 save
```

If you choose PM2's own cluster mode, continue to run `src/server.ts`; do not
also use the framework cluster runner.

## Framework cluster runner

For a standalone Node deployment on one host, use the public Node-only
`runCluster()` helper:

```ts title="src/index.ts"
import { runCluster } from '@adaptivestone/framework/cluster.js';

await runCluster(
  async () => {
    // Dynamic import is important: this callback runs only in workers, so the
    // primary never constructs a Server or opens application connections.
    await import('./server.ts');
  },
  {
    workers: 'auto',
    shutdownTimeoutMs: 30_000,
  },
);
```

Start it without file watching:

```bash
NODE_ENV=production node src/index.ts
```

The primary forks the configured workers and the callback executes only in
those workers. An abnormal worker exit is restarted after a fixed safety delay;
exceeding the framework's fixed rolling crash limit shuts down the cluster with
a non-zero exit status. A clean worker exit is not restarted. Backoff, jitter,
and rolling-deployment policy belong to an external process supervisor and are
deliberately not part of this API.

On `SIGTERM` or `SIGINT`, the primary stops scheduling restarts and forwards the
signal to every worker. Each framework server stops accepting requests and
drains its open connections. Workers still alive after `shutdownTimeoutMs` are
force-terminated and the primary exits non-zero.

`workers: 'auto'` uses Node's available parallelism. A positive integer pins
the worker count. Early lifecycle messages use `console` by default. Pass an
`onEvent` callback to send structured primary, worker-exit, shutdown, and error
events to an observability provider before the application itself exists.

### Which entry should I run?

| Deployment | Entry | Process-count owner |
|---|---|---|
| Docker/Kubernetes | `src/server.ts` | Orchestrator |
| systemd | `src/server.ts` | systemd/unit replicas |
| PM2 fork or cluster mode | `src/server.ts` | PM2 |
| Standalone multi-core host | `src/index.ts` with `runCluster()` | Framework cluster primary |

## Health checks

The framework ships two probe endpoints:

| Endpoint | Checks | Answers |
|---|---|---|
| `GET /health/live` | Nothing beyond the process serving requests | `200 {"status": "ok"}` |
| `GET /health/ready` | Also pings MongoDB (1 s timeout) | `200 {"status": "ok", "checks": {"mongo": "ok"}}`, or `503` with `"error"` |

Use `/health/live` for **liveness** probes and `/health/ready` for **readiness** probes and post-deploy checks. Keep dependencies out of liveness: if a liveness probe pinged the database, a short database outage would make the orchestrator restart every instance at once. A failed `ready` check returns no error details (the endpoint may be public) and is logged at `warn`.

```yaml
# Kubernetes
livenessProbe:
  httpGet: { path: /health/live, port: 3300 }
readinessProbe:
  httpGet: { path: /health/ready, port: 3300 }
```

```sh
# Post-deploy check
curl -fsS http://127.0.0.1:3300/health/ready
```

### Protecting the endpoints

By default the endpoints are open. To limit them to your own systems, set a token:

```sh
HEALTH_TOKEN=some-long-random-string
```

Probes then send it as the `X-Health-Token` header, or as `?token=` for load balancers that cannot send custom headers (for example, AWS ALB health checks). A missing or wrong token gets `401`. Prefer the header: query strings can end up in proxy logs.

```yaml
livenessProbe:
  httpGet:
    path: /health/live
    port: 3300
    httpHeaders: [{ name: X-Health-Token, value: some-long-random-string }]
```

Successful probe requests are not written to the request log, so frequent probes don't flood it; failed ones are logged at `warn`.

### Custom checks

The endpoints come from a built-in `Health` controller. To add checks (Redis, an external API), middleware, or a different mount path, add your own `controllers/Health.ts`: it replaces the built-in one, and can extend it. `GET /health` itself is left free, so an existing app route there keeps working. If your app already has a `controllers/Health.ts` from before 5.5.0, it replaces the built-in controller too: `/health/live` and `/health/ready` are not served until that class extends the built-in `Health` and declares those routes.

## Nginx

The Node process listens on localhost port 3300 in the default configuration.
Proxy requests to it from Nginx:

```nginx
server {

	root /var/www/YOUR_FOLDER/src/public;

	server_name YOUR_SERVER_NAME;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ @backend;
	}

	location @backend {
		proxy_pass http://localhost:3300;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection 'upgrade';
		proxy_set_header Host $host;
		proxy_set_header  X-Forwarded-For $remote_addr;
		proxy_cache_bypass $http_upgrade;
	}

}
```

## Docker

You can create a Docker image with all your data and run it on any server, including Kubernetes.

Run one Node process per container and let the orchestrator scale replicas. The
Dockerfile can look like this:

```dockerfile
FROM node:24
RUN mkdir -p /opt/app && chown -R node:node /opt/app
WORKDIR /opt/app
COPY --chown=node:node package.json package-lock.json ./
USER node
# npm install tolerates optional dependency records omitted on another CPU architecture.
RUN npm install
COPY --chown=node:node src/ ./src/
EXPOSE 3300
CMD ["node", "src/server.ts"]
```

To build it, use:

```bash
docker build --platform linux/amd64 -t YOUR_REPO_NAME:TAG .
```

You can also use `buildx`:

```bash
docker buildx build --platform linux/amd64,linux/arm64 -t YOUR_REPO_NAME:TAG . --push
```

Then you can run it:

```bash
docker run -it -p 3300:3300 YOUR_REPO_NAME:TAG
```


---


# Document 19: 14-helpers

<!-- Source: 14-helpers.md -->

# Helpers

The framework provides some helpers to make your code easier to work with.

## App instance

You can access the app instance from anywhere.

```ts
import { appInstance } from "@adaptivestone/framework/helpers/appInstance.js";
```

The app instance is the core of the framework, allowing you to retrieve models, configurations, and more.

```ts
const Model = appInstance.getModel("ModelName");
const s3config = appInstance.getConfig("s3");
// etc
```

### `getAppInstance()` (recommended for early code)

The `Server` constructor is what sets the `appInstance` singleton. Code that reads the raw `appInstance` binding **before** the `Server` is constructed — module scope, lazy imports, external modules — sees `undefined` and fails later with an opaque `TypeError: cannot read properties of undefined` that gives no hint at the cause.

Prefer the `getAppInstance()` getter in that code: it returns the same singleton, or throws a guided error when nothing is set yet.

```ts
import { getAppInstance } from "@adaptivestone/framework/helpers/appInstance.js";

const app = getAppInstance();
const Model = app.getModel("ModelName");
```

If the singleton is not set, the getter throws:

```text
App instance is not initialized yet — construct the Server first (its constructor sets the singleton). In tests, use setAppInstance() to inject one and resetAppInstance() to clear it.
```

:::note Test hooks

The same module exports `setAppInstance(app)` and `resetAppInstance()` for tests that need to run app-instance-dependent code without a full `Server`. `setAppInstance` throws if an instance is already set (only one `Server` per process is supported), and `resetAppInstance()` clears it. Prefer the per-file isolation provided by the shipped Node.js or Vitest test adapters, and reach for `resetAppInstance()` only when a runner can't isolate per file (it does **not** clean up mongoose-registered models, Redis client state, or environment variables).

:::

## Redis connection

A simplified way to connect to Redis. This helper loads the configuration and adds shutdown hooks.

:::note

`@redis/client` is an **optional peer dependency**. Install it (`npm i @redis/client`) before using this helper or the redis cache / rate-limiter driver. A project on the default in-memory cache never loads it.

:::

```ts
import { getRedisClient, getRedisClientSync } from '@adaptivestone/framework/helpers/redis/redisConnection.js';
const redisClient = await getRedisClient();
const redisClientSync = await getRedisClientSync();
```

The only difference is that `getRedisClientSync` returns the Redis client immediately and establishes the connection in the background.

## Validation schema (`defineSchema`)

A zero-dependency way to build a [Standard Schema](https://standardschema.dev/) validator from a plain function — for simple `request:` / `query:` schemas, without pulling in a validator library. The framework itself uses it, so it ships validator-free.

```ts
import { defineSchema } from "@adaptivestone/framework/services/validate/defineSchema.js";

const loginSchema = defineSchema<{ email: string }>((value) => {
  const v = (value ?? {}) as Record<string, unknown>;
  if (typeof v.email !== "string" || !v.email.includes("@")) {
    return { issues: [{ message: "validation.email", path: ["email"] }] };
  }
  // Return only known keys — unknown input is stripped by construction.
  return { value: { email: v.email } };
});
```

The `Output` generic (`{ email: string }`) feeds the typed handler signature — codegen reads `StandardSchemaV1.InferOutput`. Return `{ value }` on success or `{ issues }` on failure; each message is an i18n key or literal text. For richer or deeply-nested validation, bring zod / valibot / arktype / yup as the route schema instead — `defineSchema` has no combinators on purpose. See [Routes → Validation](./06-Controllers/02-routes.md#validation).

## Uploaded-file type (`File`)

A vendor-neutral type for files uploaded via `multipart/form-data`. It aliases the parser's file class today and re-points at the web-standard `File` after the transport-neutral parser swap, so your validation code stays stable across that change.

```ts
import { File } from "@adaptivestone/framework/types.js";
import { z } from "zod";

request: z.object({
  avatar: z.array(z.instanceof(File)).length(1).transform(([f]) => f), // one file  -> File
  avatars: z.array(z.instanceof(File)),                                // many files -> File[]
});
```

`File` is exported as both a value (for `instanceof`) and a type. Every multipart field arrives as an array, so declare cardinality with your validator's array support. See [Routes → File Validation](./06-Controllers/02-routes.md#file-validation).

:::warning Deprecated: `YupFile`
The older yup-specific `YupFile` helper (`@adaptivestone/framework/helpers/yup.js`) is **deprecated and will be removed in v6** — it now emits a runtime `DeprecationWarning` (escalate it to a thrown error with Node's `--throw-deprecation`). Migrate to the `File` export above; it works with any validator and needs no yup.
:::

## Hashing secrets

Never store a secret in plain text. Pick the hash by what you store:

| You store | Use | Why |
| --- | --- | --- |
| A long random token (session, recovery link) | `hashToken` from `models/User.js` | Fast; 256 random bits cannot be guessed |
| A short code (e-mail/SMS login, reset code) | `hashSecret` / `verifySecret` from `helpers/crypto.js` | Keyed with `AUTH_SALT`, so a leaked hash cannot be brute-forced offline |
| A user password | `hashPassword` / `verifyPassword` from `helpers/crypto.js` | Deliberately slow per guess |

```ts
import { hashSecret, verifySecret } from "@adaptivestone/framework/helpers/crypto.js";

const LOGIN_CODE = { purpose: "email-login" };

// when sending the code
loginCode.codeHash = hashSecret(code, LOGIN_CODE);

// when the user submits it (constant-time comparison)
const valid = verifySecret(submittedCode, loginCode.codeHash, LOGIN_CODE);
```

- `purpose` names the feature. A hash made for one purpose never verifies under another, so give each feature its own.
- The protection is `AUTH_SALT` staying out of the database. Anyone holding both finds a 6-digit code instantly, so keep codes short-lived and limit attempts.
- Rotating `AUTH_SALT` invalidates every stored code hash. That suits codes that expire in minutes; reissue them after a rotation.
- Hash exactly what you compare: normalize input (for example, strip spaces) before both calls.

### Comparing secrets

To check a secret you hold in configuration — an API key, a webhook secret, a probe token — never use `===`: its timing reveals how much of the guess matched. Use `timingSafeEqualStrings`, which also hides the secret's length:

```ts
import { timingSafeEqualStrings } from "@adaptivestone/framework/helpers/crypto.js";

const apiKey = process.env.API_KEY;
const sent = req.headers["x-api-key"];
// Require a configured key: two empty strings are equal too.
const valid = !!apiKey && typeof sent === "string" && timingSafeEqualStrings(sent, apiKey);
```


---


# Document 20: 15-recipes

<!-- Source: 15-recipes.md -->

# Recipes

A task-oriented cookbook for the things you build most often. Each recipe is a minimal, copy-paste starting point — follow the links into [Controllers](06-Controllers/01-intro.md) and [Routes](06-Controllers/02-routes.md) for the full reference.

:::note
Framework **package** imports use the published `.js` extension (the package ships compiled `.js`). Your own project files can be `.ts`.
:::

## Where the handler types come from

The recipes below type handlers with two things — here's where each comes from:

- **`FrameworkRequest`** — imported from `@adaptivestone/framework/services/http/HttpServer.js`. It's the Express `Request` plus the base `req.appInfo` (`app`, `ip`, `request`, `query`, `i18n`). Use it for handlers that only read `req.params` / `req.body` and don't need validated input or middleware-provided fields. `Response` and `NextFunction` come from `express`.
- **Generated `<Method>Request` aliases** — emitted by `npm run gen` into `<Controller>.routes.gen.ts`, one per handler method (`postCreate` → `PostCreateRequest`). Each one extends the base context with what *that route* actually carries: typed `req.params`, your `request:` / `query:` schema output on `req.appInfo`, and every field the route's middleware chain declares via `static get provides()` (`req.appInfo.user`, `req.appInfo.pagination`, …).

Rule of thumb: if the handler reads `req.appInfo.request` / `.query` / `.user` / `.pagination` or precise `req.params`, use the generated alias; otherwise `FrameworkRequest` is enough. See [Typed handler signatures](06-Controllers/02-routes.md#typed-handler-signatures-codegen).

## Add a controller

Drop a file in `src/controllers/`. The framework auto-loads it, but the filename does **not**
define the route. The default mount is the controller folder prefix plus the lowercased **class
name** (`src/controllers/admin/Article.ts` exporting `class Article` → `/admin/article`). Name the
file after the class for clarity, and never export the same controller class from two files—the
autoloader registers both. Every method listed in `routes` becomes an endpoint with no manual
registration step.

```ts
// src/controllers/Article.ts
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";
import type { FrameworkRequest } from "@adaptivestone/framework/services/http/HttpServer.js";
import type { Response } from "express";

class Article extends AbstractController {
  get routes() {
    return {
      get: {
        "/": { handler: this.list },
        "/:id": { handler: this.getOne },
      },
    };
  }

  async list(req: FrameworkRequest, res: Response) {
    const Article = this.app.getModel("Article");
    return res.status(200).json({ data: await Article.find() });
  }

  async getOne(req: FrameworkRequest, res: Response) {
    const Article = this.app.getModel("Article");
    return res.status(200).json({ data: await Article.findById(req.params.id) });
  }
}

export default Article;
```

These handlers read only `req.params` and the model, so the base `FrameworkRequest` is enough. To customize the prefix, override `getHttpPath()`. See [Controllers](06-Controllers/01-intro.md).

:::warning
Raw `req.params.id` is never validated. Declare a route [`params:` schema](06-Controllers/02-routes.md#params) and read `req.appInfo.params` instead — see [Validate an ObjectId](#validate-an-objectid).
:::

## Add a route with a body schema

Declare a `request:` schema inline. The framework validates and casts the body **before** your handler runs, strips unknown keys, and exposes the typed result on `req.appInfo.request`. Run `npm run gen` to emit `Article.routes.gen.ts` (where `PostCreateRequest` lives) and type the handler with it.

```ts
// src/controllers/Article.ts
import type { PostCreateRequest } from "./Article.routes.gen.ts";
import AbstractController from "@adaptivestone/framework/modules/AbstractController.js";
import type { Response } from "express";
import { object, string } from "yup";

class Article extends AbstractController {
  get routes() {
    return {
      post: {
        "/": {
          handler: this.postCreate,
          request: object().shape({
            title: string().trim().min(3).max(300).required(),
            body: string().trim().required(),
          }),
        },
      },
    };
  }

  async postCreate(req: PostCreateRequest, res: Response) {
    // req.appInfo.request.title / .body are typed (from the schema) and already validated
    const Article = this.app.getModel("Article");
    const created = await Article.create(req.appInfo.request);
    return res.status(201).json({ data: created });
  }
}
```

The handler type `PostCreateRequest` is generated from the method name (`postCreate` → `PostCreateRequest`). Any [Standard Schema](https://standardschema.dev/) validator works (yup, zod, valibot, arktype), or the zero-dependency [`defineSchema`](14-helpers.md). See [Routes → Validation](06-Controllers/02-routes.md#validation).

## Validate an ObjectId

The framework validates `request:` (body), `query:` (query string) and `params:` (path params) before your handler runs. Ids are worth an explicit pattern in whichever of the three carries them — a raw 24-hex string is the one input shape Mongoose will reject at the driver level rather than at yours.

**Body / query fields** — add the check to the schema you already declare. A strict 24-hex pattern is enough:

```ts
import { object, string } from "yup";

// in a route:
query: object().shape({
  authorId: string().matches(/^[0-9a-fA-F]{24}$/, "must be a valid id"),
}),
// zod equivalent: z.object({ authorId: z.string().regex(/^[0-9a-fA-F]{24}$/) })
```

A bad value is rejected with the framework's standard `{ errors: { authorId: [...] } }` 400 — it never reaches your handler.

**Path params (`:id`)** — declare a `params:` schema on the route. The check runs before your handler, so the model only ever sees a well-formed id:

```ts
import { object, string } from "yup";
import type { GetOneRequest } from "./Article.routes.gen.ts";
import type { Response } from "express";

// in the routes getter:
"/:id": {
  handler: this.getOne,
  params: object().shape({
    id: string().matches(/^[0-9a-fA-F]{24}$/, "must be a valid id"),
  }),
},

// the handler no longer guards anything:
async getOne(req: GetOneRequest, res: Response) {
  const Article = this.app.getModel("Article");
  const { id } = req.appInfo.params; // validated, and typed by codegen
  return res.status(200).json({ data: await Article.findById(id) });
}
```

A malformed id is rejected with the same `{ errors: { id: [...] } }` 400 as any body or query failure.

:::note Strict vs loose
`mongoose.isValidObjectId` — the guard this recipe used to recommend — is lenient: it also accepts any 12-character string (and some numbers). The 24-hex regex above is the tighter check, and works without importing mongoose into your controller.
:::

:::tip
Forgot the schema on some route? The framework still answers **400** rather than 500 when an unvalidated client value fails to cast — see [Error handling → the Mongoose cast safety net](06-Controllers/04-error-handling.md#built-in-the-mongoose-cast-safety-net). Treat that as a floor, not a replacement: only a `params:` schema gives you your own message, i18n wording, coercion, and a typed path parameter in your OpenAPI document.
:::

## Wire pagination

Add the built-in `Pagination` middleware to the route. It reads `page` / `limit` from the query and puts `{ page, limit, skip }` on `req.appInfo.pagination`. Because that field is middleware-provided, type the handler with its generated alias (`ListRequest`) — `Pagination`'s `provides` flows into it.

```ts
import Pagination from "@adaptivestone/framework/services/http/middleware/Pagination.js";
import type { ListRequest } from "./Article.routes.gen.ts";
import type { Response } from "express";

get routes() {
  return {
    get: {
      "/": {
        handler: this.list,
        middleware: [[Pagination, { limit: 20, maxLimit: 100 }]],
      },
    },
  };
}

async list(req: ListRequest, res: Response) {
  const { skip, limit, page } = req.appInfo.pagination; // typed via Pagination's `provides`
  const Article = this.app.getModel("Article");
  const [items, total] = await Promise.all([
    Article.find().skip(skip).limit(limit),
    Article.countDocuments(),
  ]);
  return res.status(200).json({ data: { items, page, limit, total } });
}
```

`[Pagination, { limit, maxLimit }]` is the tuple form — a middleware class plus its params. See [Middleware → Pagination](06-Controllers/03-middleware.md#pagination).

## Require authentication

Put `GetUserByToken` (parses the token → `req.appInfo.user`) and `Auth` (rejects unauthenticated requests) in the chain. After `Auth`, `req.appInfo.user` is typed as required in the generated alias — no `if (!user)` guard needed.

```ts
import GetUserByToken from "@adaptivestone/framework/services/http/middleware/GetUserByToken.js";
import Auth from "@adaptivestone/framework/services/http/middleware/Auth.js";
import type { ListMineRequest } from "./Article.routes.gen.ts";
import type { Response } from "express";

get routes() {
  return {
    get: {
      "/mine": {
        handler: this.listMine,
        middleware: [GetUserByToken, Auth],
      },
    },
  };
}

async listMine(req: ListMineRequest, res: Response) {
  // req.appInfo.user is required here (Auth's `provides`)
  const Article = this.app.getModel("Article");
  return res.status(200).json({
    data: await Article.find({ owner: req.appInfo.user._id }),
  });
}
```

To apply one chain to **every** route in the controller, use the middleware Map instead:

```ts
static get middleware() {
  return new Map([["/{*splat}", [GetUserByToken, Auth]]]);
}
```

See [Middleware](06-Controllers/03-middleware.md).

## Write a middleware that contributes to `req.appInfo`

Extend `AbstractMiddleware`, set your field on `req.appInfo`, and declare `static get provides()` so handlers downstream get it typed. Type the middleware's own `req` with the field it writes (an inline intersection on the base `FrameworkRequest`).

```ts
// src/middleware/WithArticleCount.ts
import AbstractMiddleware from "@adaptivestone/framework/services/http/middleware/AbstractMiddleware.js";
import type { FrameworkRequest } from "@adaptivestone/framework/services/http/HttpServer.js";
import type { Response, NextFunction } from "express";

class WithArticleCount extends AbstractMiddleware {
  static get description() {
    return "Adds the total article count to req.appInfo";
  }

  static get provides() {
    return {} as { articleCount: number };
  }

  async middleware(
    req: FrameworkRequest & { appInfo: { articleCount?: number } },
    res: Response,
    next: NextFunction,
  ) {
    const Article = this.app.getModel("Article");
    req.appInfo.articleCount = await Article.countDocuments();
    return next();
  }
}

export default WithArticleCount;
```

The object `provides` returns is always `{}` — only its cast type matters (codegen reads it; the runtime ignores it). Any route with `WithArticleCount` in its chain now has `req.appInfo.articleCount: number` in its generated alias. See [Routes → Middleware-provided types](06-Controllers/02-routes.md#middleware-provided-types).

## Override a framework controller

Create a controller with the same filename as a built-in one and extend it — your version wins via the [file-inheritance](03-files-inheritance.md) mechanism. Override only the handlers you want to change.

```ts
// src/controllers/Auth.ts
import OriginalAuth from "@adaptivestone/framework/controllers/Auth.js";
import type { FrameworkRequest } from "@adaptivestone/framework/services/http/HttpServer.js";
import type { Response } from "express";

class Auth extends OriginalAuth {
  async postLogin(req: FrameworkRequest, res: Response) {
    // your custom login — call super for the default behavior, or replace it
    return super.postLogin(req, res);
  }
}

export default Auth;
```

The same approach works for models and configs. See [File Inheritance](03-files-inheritance.md).

## Test a controller with the framework helpers

The framework boots a real test server and an in-memory Mongo. Use `getTestServerURL()` for the base URL and `appInstance.getModel()` to seed and reset data.

```ts
// src/controllers/Article.test.ts
import assert from "node:assert/strict";
import { beforeEach, describe, it } from "node:test";
import { appInstance } from "@adaptivestone/framework/helpers/appInstance.js";
import { getTestServerURL } from "@adaptivestone/framework/tests/testHelpers.js";

describe("Article controller", () => {
  beforeEach(async () => {
    await appInstance.getModel("Article").deleteMany({});
  });

  it("creates an article", async () => {
    const res = await fetch(getTestServerURL("/article"), {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: "Hello world", body: "..." }),
    });
    assert.equal(res.status, 201);
  });
});
```

For authenticated requests, create a user and send its token in the `Authorization` header. See the [Testing](09-testsing.md) chapter for the full setup, helpers, and CI examples.


---


# Document 21: 16-anti-patterns

<!-- Source: 16-anti-patterns.md -->

# Anti-patterns

Common mistakes when working with the framework, and what to do instead. Most of them map to a feature that already solves the problem — reach for the seam, not the workaround.

## Don't hand-edit `.routes.gen.ts`

❌ Editing a generated `<File>.routes.gen.ts` file.
✅ Edit the `routes` getter / `request:` schema, then run `npm run gen`.

Gen files are overwritten on every `npm run gen` (and every `check:types`) — your edits vanish. They're derived from the `routes` getter and the resolved middleware chain, and they're gitignored for that reason. Change the source and regenerate. See [When to run codegen](10-cli.md#when-to-run-codegen).

## Don't `new` a middleware yourself

❌ `middleware: [new Pagination(app, { limit: 20 })]`
✅ `middleware: [[Pagination, { limit: 20 }]]`

Declare middleware as a class, or a `[Class, params]` tuple. The framework instantiates and caches them for you, and reads their static metadata (`provides`, schemas) **without** constructing them. A manual `new` runs constructor side effects at the wrong time and bypasses that caching. See [Middleware](06-Controllers/03-middleware.md).

## Don't mutate `req.body` to "validate"

❌ Reading and normalizing `req.body` by hand inside the handler.
✅ Declare a `request:` (or `query:`) schema; read the validated, cast result from `req.appInfo.request`.

The route schemas validate and coerce before the handler runs, produce a typed `req.appInfo.request` / `req.appInfo.query`, strip unknown keys, and feed codegen (and later OpenAPI). Hand-rolled parsing in the handler gets none of that. See [Validation](06-Controllers/02-routes.md#validation).

## Don't put state in the `routes` getter

❌ A `routes` getter that reads `this.something` assigned in the constructor.
✅ Keep `routes` declarative — list handler methods and inline schemas only.

`npm run gen` reads `routes` **statically from the source AST** — it never imports or constructs your controller, so type generation stays free of constructor side effects. The cost: if the `routes` getter isn't a plain object literal (it reads `this.something`, loops, or otherwise computes the route shape), codegen can't analyze it and **the run fails** — there is no constructor fallback. Move the dynamic part into handlers or a module-level constant so the returned shape stays literal. See [Keep `routes` declarative](06-Controllers/02-routes.md#keep-routes-declarative-codegen-reads-the-source-never-your-constructor).

## Don't reach into raw Express when `req.appInfo` already has it

❌ Re-parsing cookies, re-loading the user, or recomputing pagination in every handler.
✅ Read what middleware already put on `req.appInfo` — `user`, `request`, `query`, `pagination`, `i18n`, plus any field your own middleware declares via `provides`.

`req.appInfo` is the framework's typed request context. Middleware populates it once; handlers and codegen consume it. Reaching around it duplicates work and loses the types. See [Middleware-provided types](06-Controllers/02-routes.md#middleware-provided-types).

## Don't monkey-patch the framework — report it

❌ Copy-pasting a framework file to tweak it, overriding internals to route around a bug, or shimming a private method.
✅ Open an issue at [github.com/adaptivestone/framework/issues](https://github.com/adaptivestone/framework/issues) with a minimal repro.

Local workarounds rot, hide the bug from everyone else, and break on the next update. The framework is built to be extended through supported seams — [file inheritance](03-files-inheritance.md), middleware, `provides`, and config — not patched. If the seam you need is missing, that's worth an issue too.


---


# Document 22: 17-openapi

<!-- Source: 17-openapi.md -->

# OpenAPI

The framework generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0/) document from your controllers. Paths, parameters, request bodies, security, and tags are all derived from the route definitions you already write — point Swagger UI, Redoc, or a client-SDK generator at the output.

## Generate

```bash
node src/cli.ts openapi                       # print to stdout
node src/cli.ts openapi --output openapi.json # write to a file
```

Add a script to `package.json`:

```json
"openapi": "node src/cli.ts openapi"
```

```bash
npm run openapi -- --output openapi.json
```

:::note
The command loads your controllers but **opens no database or network connection and binds no port** — it walks the route registry and reads your schemas in-process. It's safe to run in CI. (Unlike codegen, which is on your hot path, this is a cold, occasional command, so it loads the real controller instances to read live schema objects.)
:::

## What gets documented

Everything comes from the route definitions you already have — there is nothing OpenAPI-specific to maintain separately:

| OpenAPI field | Source |
|---|---|
| `operationId` | handler method name |
| `tags` | controller class name |
| `summary` | route [`description`](06-Controllers/02-routes.md#route-third-level-route-object-level) |
| path `parameters` | `:name` path segments; typed by the route [`params:`](06-Controllers/02-routes.md#params) schema when declared, otherwise `string` |
| query `parameters` | route [`query:`](06-Controllers/02-routes.md#query) schema (+ middleware query schemas) |
| `requestBody` | route [`request:`](06-Controllers/02-routes.md#request) schema or [content-type map](06-Controllers/02-routes.md#different-schemas-per-content-type) (+ middleware request schemas) |
| `security` | middleware [`static get authSchemes()`](#documenting-auth-security-schemes) (schemes) and `static get requiresAuth()` (required vs optional) |
| `info` / `servers` | your `package.json` + the `http` config (`port`, `myDomain`) |

Output is **OpenAPI 3.1** (JSON Schema 2020-12) only.

## Request bodies come from your schemas

Body, query and path-param shapes are produced by introspecting the **same validation schemas** you already use at runtime — through the validator driver's `toJsonSchema`. How much detail you get depends on the validator:

| Validator | OpenAPI body |
|---|---|
| [Zod](https://zod.dev/) | full JSON Schema via native `z.toJSONSchema` — types, formats, `min`/`max`, patterns, enums, defaults |
| [Yup](https://github.com/jquense/yup) | JSON Schema from `.describe()` — types, `required`, enums, nullable, arrays, `date` → `date-time` |
| [ArkType](https://arktype.io/) / any schema exposing a `.toJsonSchema()` method | its native output |
| [`defineSchema`](06-Controllers/02-routes.md#zero-dependency-schemas-defineschema) | optional explicit `jsonSchema`; otherwise a placeholder schema + a warning |
| A hand-rolled `~standard` function | **not introspectable** unless it exposes `.toJsonSchema()` — a placeholder schema + a warning |

### Zod request-input semantics

OpenAPI describes what a client sends, not the value after Zod transforms it.
For example, `z.string().transform(Number)` is documented as a string.
`z.coerce.date()` is documented as a `{ "type": "string", "format":
"date-time" }` request value. Other Zod values that cannot be represented in
JSON Schema, such as custom `instanceof` checks, safely degrade to `{}` rather
than aborting the whole document.

For file uploads, use a content-type map with an explicit
`multipart/form-data` entry. A custom runtime `instanceof` check cannot by
itself tell OpenAPI that a field contains binary data.

:::note Describe imperative schemas explicitly
`defineSchema` callbacks are imperative, so their code cannot be inferred as a shape. Pass its optional `jsonSchema` option when the endpoint should be documented, or use a declarative validator such as Zod or Yup. A custom `~standard` schema can likewise expose a `.toJsonSchema()` method. Without either, the generator emits a placeholder object and prints a warning, e.g.:

```
OpenAPI: 1 schema(s) could not be fully introspected:
  POST /auth/login body: schema introspection unavailable.
```
:::

Schema conversion is contained per route and middleware schema. Warnings name
the HTTP method, route, and schema position. An unavailable body schema gets a
placeholder object, an unavailable query schema is omitted, and other healthy
routes remain fully documented. Genuine command boot, generator, and file-write
failures still exit nonzero.

The built-in `Pagination` middleware already supplies its explicit schema, so
every route using it documents optional numeric `page` and `limit` query
parameters without application-specific OpenAPI annotations.

This is why the generator must load your controllers at runtime rather than read the generated types: JSON Schema can only be produced from the live schema object (`z.toJSONSchema(...)`, `schema.describe()`), not from a TypeScript type.

## Documenting auth (security schemes)

A middleware advertises the security scheme(s) it reads credentials from with a `static get authSchemes()` getter. The generator reads it **off the class — no instantiation** — adds each entry to `components.securitySchemes`, and attaches a `security` entry to every operation whose middleware chain includes that middleware.

```ts
import AbstractMiddleware from "@adaptivestone/framework/services/http/middleware/AbstractMiddleware.js";

class TokenAuth extends AbstractMiddleware {
  static get authSchemes() {
    return [
      // http bearer scheme
      { name: "bearerAuth", type: "http", scheme: "bearer", description: "Bearer token" },
      // or an apiKey header
      { name: "X-Api-Key", type: "apiKey", in: "header", description: "API key" },
    ];
  }

  async middleware(req, res, next) {
    // ... runtime auth logic ...
  }
}
```

| Field | Meaning |
|---|---|
| `name` | scheme key in `components.securitySchemes` (for `apiKey`, also the header/query name) |
| `type` | `'apiKey'` or `'http'` |
| `in` | for `apiKey`: `'header'` (default) / `'query'` / `'cookie'` |
| `scheme` | for `http`: `'bearer'`, `'basic'`, … |
| `description` | shown in the docs UI |

:::note Renamed in 5.5.0
`authSchemes` was called `usedAuthParameters` before. The old name still works until v6, with a one-time deprecation warning; rename it in your middleware.
:::

### Required or optional

Reading a token is not the same as requiring one. A middleware that **rejects** requests without an authenticated user says so with `static get requiresAuth()`:

```ts
class TokenAuth extends AbstractMiddleware {
  static get requiresAuth() {
    return true; // this middleware answers 401 without a user
  }
}
```

- If **any** middleware in a route's chain has `requiresAuth`, the operation's security is **required**: `security: [{ bearerAuth: [] }, …]`.
- If the chain only **reads** credentials, the security is **optional**: `security: [{}, { bearerAuth: [] }, …]`. The empty `{}` tells clients an anonymous request is valid too, so generated clients send a token when they have one but don't require it.

The built-in [`GetUserByToken`](06-Controllers/03-middleware.md) declares the `Authorization` header and bearer schemes and only reads the token, so on its own it documents auth as optional (for example, a public login route). The built-in `Auth` and `Role` middleware have `requiresAuth`, so routes behind them are documented as requiring a token.

## Current limitations

- **Response bodies are not yet schema-documented.** Every operation carries a generic `200`/`400`/`401`/`404` response with a text description but no body schema. (Documenting response shapes is on the roadmap — it needs a declared `response:` schema, since a response has no runtime schema object to introspect.)
- **Catch-all (`{*splat}`) routes** are approximated as a single `{splat}` path parameter, because OpenAPI has no catch-all; the command warns when it does this.
- The route `description` becomes the operation `summary`; there is no separate long description, `deprecated` flag, or per-tag description yet.


---


<!-- End of Documentation -->
