Skip to content

Для AI-агентов ​

Краткая и точная шпаргалка для coding-агентов (Claude Code, Cursor, Copilot...), которые работают с библиотекой. Тот же текст (на английском — так надёжнее для агентов) поставляется в npm-пакете как AGENTS.md (лежит в node_modules/@alt-point/active-models/), а индекс llms.txt публикуется рядом с этим сайтом.

Подсказка: сошлитесь на него из CLAUDE.md / AGENTS.md своего проекта:

md
Перед работой с моделями прочитай node_modules/@alt-point/active-models/AGENTS.md.

@alt-point/active-models — guide for AI agents ​

Use this file when writing code with this library (a consumer) or on it (a contributor). Full docs: https://alt-point.github.io/active-models/ · Source of truth is src/ and tests/.

What it is ​

Reactive, self-validating DTO models built on Proxy + legacy TypeScript decorators. A model class extends ActiveModel; each field is declared with @ActiveField(options).

Requires "experimentalDecorators": true in tsconfig (legacy decorators, not TC39 stage-3).

ts
import { ActiveModel } from '@alt-point/active-models/ActiveModel'
import { ActiveField } from '@alt-point/active-models/decorators'
import { EventType } from '@alt-point/active-models/types'

class User extends ActiveModel {
  @ActiveField({ readonly: true }) id: string = ''
  @ActiveField({ validator: (_m, prop, v) => { if (!v) throw new TypeError(`${prop} required`) } })
  name: string = 'Guest'
  @ActiveField({ hidden: true }) passwordHash: string = ''
  @ActiveField({ factory: Address }) address?: Address        // nested model (arrays too)
}

const user = User.create({ id: '1', name: 'Ann' })   // ALWAYS create via the factory
user.name = 'Bob'
JSON.stringify(user)                                  // hidden fields are excluded

Imports: one subpath per capability, no root entry ​

import ... from '@alt-point/active-models' does not resolve (no barrel). Import each capability from its own subpath, so a bundler only includes what you use (ActiveModel alone is ~8 KB gzipped; collections, maps, sets and scalars cost nothing until imported).

SubpathExports
/ActiveModelActiveModel, type InvariantCheck
/decoratorsActiveField, ActiveFactory, GetterMethod, SetterMethod, InvariantMethod, isHidden, isFillable, isProtected
/typesEventType and every option / payload type (FactoryOptions, CollectionOptions, ActiveFieldDescriptor, EventListener, ...)
/pipelineValidationError; types ValidationIssue, ValidationResult, ValidationCode, FieldRules, Transform, Transitions, CoerceTo, ValueType, Coercible, Bound
/ActiveCollection, /ActiveMap, /ActiveSetthe class of the same name (ActiveCollection also exports type CollectionInput)
/collectionRegistryisCollection
/scalars/Decimal, /scalars/Money, /scalars/LocalDate, /scalars/immutableDecimal (+ DecimalInput, RoundingMode); Money, minorUnits; LocalDate; markImmutable
/CallableModel, /utilsCallableModel; types ModelProperties, RecursivePartialActiveModel

Containers are opt-in: a model, @ActiveField and the rest never load ActiveCollection / ActiveMap / ActiveSet. To use a typed container in a field, import it and describe the field with it: @ActiveField({ container: ActiveCollection.field(Task, { sortBy: 'id' }) }).

Rules that prevent the most bugs ​

  1. Build models with Model.create(data), never new Model(data). Field initializers run after the constructor and overwrite the data new filled in. (createLazy returns an existing instance as-is.)
  2. Lists: Model.createFromCollection([...]). create([...]) throws.
  3. Async data: Model.asyncCreate(promise), asyncCreateFromCollection(promise).
  4. A validator rejects by throwing or by returning false (a ValidationError, code validator). It runs only when the value actually changes, so it can't enforce "field is required" — check keys before create().
  5. Never rely on a listener to veto a write (the value is already written); use validator.
  6. Replace values instead of mutating them in place: m.items = [...m.items, x], not m.items.push(x) — in-place mutation emits no events (nested ActiveModels via factory do bubble touched).
  7. Don't reach into the raw object: the target in beforeSetValue/afterSetValue/nulling/ beforeDeletingAttribute payloads is the raw instance — read only.
  8. There is no model.emitter and no startTracking() (removed in 4.0) — see migration below.

@ActiveField options ​

OptionEffect
value / attributedefault for a key absent from create() data (value or () => value)
validator(model, prop, value)throw or return false to reject
setter(model, prop, value, receiver) / getter(model, prop, receiver)transform on write / read
readonly: truecan be set once at creation, later writes are silently ignored
fillable: falsedata can never set it; direct assignment throws
hidden: trueexcluded from Object.keys, spread, in, JSON.stringify, isTouched(); still readable directly
protected (default true)delete throws; set false to allow delete
factory: Model / [Model, () => default]wrap nested object / array items in Model; many: false / true refuses the other shape
on: { afterSetValue, ... } / oncefield-level hooks, shared by all instances (and subclasses)

Validation pipeline (every write) ​

transform (trim/lowercase/uppercase/fn) → coerce → same value? stop → transitions → rules → validator → events. Rules: required (not null/undefined/''), type, min/max (number or Date), minLength/maxLength, pattern, oneOf (array or TS enum). A refused write throws ValidationError (.issues). model.validate() → { valid, issues } covers all fields, including ones never set (required), nested models and collections (history[1].city); assertValid() throws; create(data, { validate: true }) too. transitions: { new: ['paid'], paid: [] } restricts state changes (first value and creation from data are free); canTransition(), allowedTransitions(). static strict = true refuses writes to undeclared properties. Rules are bypassed when values are restored (undo/rollback). Cross-field rules: @InvariantMethod('msg') static ok(m) { return … } / Model.defineInvariant(name, check), checked by validate()/transaction()/atomic fill(), not per write. model.transaction(fn) is all-or-nothing (rolls back on a throw or an invalid result; async ok); fill(data, { atomic: true }). Tracked models ({ tracked: true }) have changes(), dirtyFields(), isDirty(f), revert(f?), reset(). create(data, { history: true | { limit } }) enables undo()/redo()/canUndo()/canRedo()/clearHistory(); a transaction is one step.

Events ​

EventType: beforeSetValue, afterSetValue, nulling (non-null → null only), beforeDeletingAttribute, touched, created. Payloads: { target, prop, value, oldValue }; beforeDeletingAttribute → { target, prop }; touched/created → { target } (the model itself).

ts
const off = user.on(EventType.afterSetValue, ({ prop, value }) => {})   // one instance; returns unsubscribe
User.on(EventType.created, ({ target }) => {})                          // every instance + subclasses
user.once(...) / User.once(...)
  • create() emits created synchronously; new Model() emits it in a microtask. Children before parents.
  • touched is not emitted during creation. created listeners must be registered before create() (use Model.on, or static beforeFill(model, data) to reach the instance under construction).
  • Listener errors: all listeners run, then the first error is rethrown (several → error.errors).

Other API ​

  • model.fill(data, force?) — partial update; ignores unknown / fillable: false keys unless force. Does not re-apply value defaults.
  • model.toJSON() — hidden/functions/symbols dropped; honors toJSON() (Date), Set→array, Map→object.
  • model.clone() — deep, fully working proxied copy (hidden kept, locks + isTouched baseline carried).
  • model.makeFreeze() — shallow; later write/delete throws TypeError.
  • Dirty tracking: Model.create(data, { tracked: true }); model.isTouched() → true/false, or undefined if never tracked. Reset the baseline by re-creating the model. model.getRaw() returns the frozen source data exactly as passed to that create() (pre-defaults, pre-strip), undefined if untracked. { tracked: 'shallow' } keeps the field values by reference and compares them with Object.is (O(fields), no deep copy): a reassignment counts, an edit inside a nested model or collection does not; revert() puts the kept instance back.
  • Mapping: Model.mapTo(Target, (m, ...args) => ...), model.mapTo(Target, lazy = true, ...args), hasMapping(Target). lazy (default) falls back to clone(); lazy: false throws.
  • Collections: ActiveCollection.create(Model, items, { sortBy, compare, order, coerce }) / ActiveCollection.createFromData(Model, data, opts) (every item through Model.create()) / @ActiveField({ container: ActiveCollection.field(Model, options) }) give an ActiveCollection: an array that accepts only instances of that model (plain objects are coerced unless coerce: false; anything else throws), never has holes, and — with sortBy/compare — stays sorted (push inserts in place, items move when their key changes, bisectLeft/Right, findByKey, range). unique: 'field' | fn rejects duplicate keys atomically (ValidationError code unique; getByKey/hasKey). ActiveMap.create(Model, { key }, items) (map.addAll(iterable) adds a batch later) / ActiveSet.create(Model, items, { unique }) and the container: ActiveMap.field(Model, { key }) / container: ActiveSet.field(Model, opts) field options give the keyed / set flavours with the same rules (.field(), not .of() — ActiveCollection extends Array, whose static of is taken). Events: itemsAdded, itemsRemoved, touched (bubbles into the parent model). Use its own methods, not Array.prototype.x.call(collection) (guarded but not atomic).
  • Scalars: @ActiveField({ coerce: Money | Decimal | LocalDate }) turns strings/numbers/objects into immutable value objects (Money.of('19.99','USD'), '19.99 USD'; Decimal.from('0.1').add('0.2'); LocalDate.from('2026-09-25')). Never use number for money. min/max work with any value having compareTo() (mixed currencies fail the bound). Custom class: static from(), compareTo, toJSON, markImmutable(Class).
  • CallableModel — instances are callable, implement __call.

Migrating 5.x → 6.0 ​

No codemod. Model.create(primitive) / new Model(primitive) throw a TypeError (an empty model before). Enum, EnumItemType and the /Enum entry are gone: use a TS enum or a string union with oneOf (the codemod prints a MANUAL line for them). A validator that returns false refuses the write (ignored before). transaction() rolls back from a journal of writes, so an in-place mutation of a plain value (m.tags.push(x)) stays after the rollback - replace the value instead. Details: docs/en/migration-6.md.

Migrating 4.x → 5.0 ​

Run npx @alt-point/active-models migrate <dir> (dry run; --write applies, --check for CI): it rewrites root imports into subpath imports in ts/tsx/js/jsx/mjs/cjs/vue files and the collection API as below; leftovers are printed as MANUAL with file:line. No root import (use subpaths); collection/map/set field options → container: ActiveCollection.field(...) / ActiveMap.field(...) / ActiveSet.field(...); Model.collection() / createCollection() → ActiveCollection.create() / createFromData(). Details: docs/en/migration-5.md.

Migrating 3.x → 4.0 ​

model.emitter.on(...) → model.on(...); form.startTracking() → form = Form.create(saved, { tracked: true }); create([...]) → createFromCollection([...]). Details: docs/en/migration.md.

Contributing to this repo ​

bash
bun install
bun run typecheck && bun run lint && bun run test        # all must pass
bun run test:coverage                                    # thresholds enforced
bun run test:perf                                        # performance budgets
bun run test:mutation                                    # Stryker mutation testing
bun run build                                            # tsup -> dist/
bun run test:dist                                        # smoke test of the built package (after build)
bun run docs:dev                                         # VitePress
  • Tests use a custom esbuild transform (vitest.config.ts) so they compile decorators exactly like the published build; don't replace it with SWC/oxc — class-field/Proxy timing differs.
  • Every public capability is a tsup entry and a package.json exports subpath (+ typesVersions); there is no src/index.ts. Adding one means touching tsup.config.ts, exports, typesVersions (tests/package-entries.test.ts fails otherwise) and typedoc.json. Internals (meta, emitter, history, equal, clone, collectionCore, mapper, journal) must stay unexported. Zero runtime dependencies is enforced.
  • bun run test:dist checks the built package (ESM + CJS load by subpath and share one copy of every class); tests/treeshake.test.ts bundles each entry and fails if it pulls in code it should not, or grows past its size budget.
  • Style: no semicolons, single quotes, space-before-function-paren (enforced by ESLint).
  • Add a test for every behavior change and update docs/ (RU) + docs/en/ (EN) + CHANGELOG.md.
  • Versioning is strict SemVer (rules at the top of CHANGELOG.md): breaking → MAJOR, feature → MINOR, fix → PATCH. Record every user-visible change under ## [Unreleased] in the same commit and mark breaking commits with ! (fix!:) plus a BREAKING CHANGE: footer.
  • Commit messages: conventional commits; do not add co-author footers.