Open MercatoDocsSearch docsAPI reference

Framework

Reference Example Module

When a convention is easier to understand in code, open the example module alongside the feature you are building. Find one complete path, such as a todo's form, API, command and subscriber, and follow it before adapting the pieces.

example is the platform's canonical reference module. It is real, compiling code – not prose, not a tutorial – that demonstrates one working way to use nearly every extension point this framework exposes: CRUD, custom fields, encryption, events, UMES, AI tools, notifications, search, integrations, and more. This page is a capability-by-capability index into it: look up what you want to build, follow the exact source link, and read only that file.

What this module is – and is not

How to read this page

Every row below carries:

Sections are grouped by what you're trying to build, not by where the files happen to live. A readable row (everything below except the final section) passed the module's own reference-quality gate and is safe to read and adapt. The final Testing Evidence section is different: it is qa-only – present because the module doubles as QA surface, working, but never a pattern to copy. See the module's README for the full reference-quality gate and the read-status legend.

Module Foundation & Lifecycle

For the normative rule behind these capabilities (not just one compiling example), see om-module-scaffold, om-integration-builder.

CapabilityDemonstratesSource
module.metadata
Module metadata and auto-discovery entrypoint
Minimal ModuleInfo export that makes the directory a discoverable module. Everything else in the module is found by file convention, not by registration in this file.src/modules/example/index.ts
module.acl-features
ACL feature declarations with dependencies
Declarative feature ids used by requireFeatures guards, including dependsOn chains so granting a manage feature implies its view feature.src/modules/example/acl.ts
module.setup-role-features
Tenant setup: role grants and all three seeding hooks
ModuleSetupConfig mapping built-in roles to wildcard feature grants, plus the three hooks the framework calls at different moments with different capabilities: onTenantCreated (EntityManager only, no container, fires per new tenant) installs the module's custom-entity definitions; seedDefaults (container available, never skipped) writes scoped reference records through the DI-resolved data engine with deterministic upserting ids; seedExamples (skipped by --no-examples) delegates demo Todos to the same seeder the module CLI exposes.src/modules/example/setup.ts
src/modules/example/lib/exampleSeeds.ts
module.di-registration
Module DI registrar
register(container) entrypoint. Registers the module's own scoped Awilix service (asFunction(...).scoped() under the exampleTodoSummaryService token, consumed by api/todos/summary/route.ts) alongside payment-gateway, shipping-carrier, and inbound-webhook adapters plus provider descriptors. The two halves are deliberately different: adapters go into module-external registries, the summary service goes into this container.src/modules/example/di.ts
src/modules/example/lib/todoSummaryService.ts
module.cli-command
Module CLI command and seeding helper
Module-owned CLI entrypoint that installs custom entities and seeds example Todos for a tenant/organization pair.src/modules/example/cli.ts
module.i18n-catalogs
Module locale catalogs
Per-module translation catalogs consumed by useT() on the client and resolveTranslations() on the server. Every user-facing string in the module resolves through a key defined here.src/modules/example/i18n/en.json
src/modules/example/i18n/de.json
src/modules/example/i18n/es.json
src/modules/example/i18n/pl.json
module.translatable-fields
Translatable field declarations
Module-root translations.ts mapping an <module>:<entity> type to the field names the Translation Manager may translate. Declaring the file is what injects the Translation Manager widget into that entity's CrudForm header spot.src/modules/example/translations.ts
module.setup-scheduler-target
Tenant setup: registering a module-owned scheduler target
Idempotent organization-scoped ScheduledJob registered from seedDefaults – the only always-running hook that receives a container, because onTenantCreated gets an EntityManager and nothing else. The schedule id is a deterministic hash of (module, tenant, organization) so repeated setup runs upsert one row per scope. The call is wrapped so a SchedulerService.register rejection – notably the per-tenant active-schedule cap, which answers 422 – degrades to a logged warning instead of aborting tenant initialization.src/modules/example/setup.ts
module.generator-plugin
Deterministic module reference-index generator plugin
A type-only-import generators.ts declaration aggregates the module reference convention into example-reference-index.generated.ts. Bootstrap registers the generated entries with the module-local consumer, which rejects duplicate module/capability rows and non-portable source paths. Generator ownership removes the output when the module is disabled.src/modules/example/generators.ts
src/modules/example/reference-index.ts
src/modules/example/lib/module-reference-index.ts

Data Model

For the normative rule behind these capabilities (not just one compiling example), see om-data-model-design, om-system-extension.

CapabilityDemonstratesSource
data.entities
MikroORM entities with tenant/organization columns
Module-owned entities using UUID primary keys, snake_case columns, created_at/updated_at/deleted_at, and explicit tenant_id/organization_id scope columns. No cross-module ORM relationships.src/modules/example/data/entities.ts
data.validators
Zod validators and inferred types
Create/update/list schemas in data/validators.ts with types derived via z.infer, including a shared enum schema reused across create, update, and list contracts.src/modules/example/data/validators.ts
data.custom-fields
Custom entities and custom field definitions (ce.ts)
Declarative CustomEntitySpec / CustomFieldDefinition set covering integer, select, boolean, multi-text tags, markdown multiline, dynamic optionsUrl, listbox input, attachments, defaults, and validation rules.src/modules/example/ce.ts
data.migrations
Module migrations and ORM snapshot
Generated SQL migrations plus the module-scoped .snapshot-open-mercato.json that yarn db:generate diffs against, including a later additive alter table ... add column alongside the initial create table. Copy the workflow, never the files.src/modules/example/migrations/Migration20251030150038.ts
src/modules/example/migrations/Migration20260226161000_example.ts
src/modules/example/migrations/Migration20260804120546_example.ts
src/modules/example/migrations/.snapshot-open-mercato.json
data.encryption-map
Tenant data encryption map for a module entity
defaultEncryptionMaps declaring one at-rest-encrypted column (example:todo.notes). Shows the choice the declaration forces on every read path: the column is projected only for single-record requests, absent from sortFieldMap and from the CSV headers, never filtered with $ilike, and written through TenantDataEncryptionService.encryptEntityPayload on the nativeUpdate path because that path fires no ORM lifecycle hooks. Pre-image reads that feed undo snapshots use findOneWithDecryption.src/modules/example/encryption.ts
src/modules/example/data/entities.ts
src/modules/example/commands/todos.ts
data.entity-extensions
Cross-module entity link declaration
EntityExtension in data/extensions.ts linking the customers base entity to this module's per-customer priority entity through plain FK-id join keys, the shape the ban on cross-module ORM relations forces. Declares table explicitly even though the query engine's regular pluralizer now derives the same example_customer_priorities; the field is the escape hatch for an entity whose @Entity({ tableName }) does not match the derived name. DECLARATION-ONLY: no runtime call site exists – nothing in the platform passes includeExtensions, the basic engine's extension join adds no projection and no filterable alias, and the hybrid engine DI registers ignores the flag outside its basic-engine fallback.src/modules/example/data/extensions.ts

APIs & Commands

For the normative rule behind these capabilities (not just one compiling example), see om-module-scaffold, om-system-extension, om-data-model-design.

CapabilityDemonstratesSource
api.crud-factory
CRUD route via makeCrudRoute
Smallest complete makeCrudRoute slice: per-method ACL metadata, ORM binding with org/tenant/soft-delete fields, list schema and sort map, mapToEntity/applyToEntity, soft delete, and scoped cross-module cache invalidation in afterCreate/afterUpdate/afterDelete.src/modules/example/api/customer-priorities/route.ts
api.crud-query-engine-custom-fields
CRUD list through the Query Engine with dynamic custom fields and CSV export
Todo list route: query-engine field selectors, cf:* custom-field projection and filtering, per-request custom-field definition discovery published on the request context in beforeList, command-backed create/update/delete actions, and CSV export configuration.src/modules/example/api/todos/route.ts
api.openapi
OpenAPI specs for module routes
Module-local OpenAPI factory built on the shared CRUD OpenAPI helpers: shared error/ok/created schemas, paged list response schema, and per-resource create/update/delete documentation.src/modules/example/api/openapi.ts
api.custom-route
Hand-written (non-CRUD) API route
Custom GET handler that builds its own request container, reads auth from cookies, and queries the directory module through the Query Engine.src/modules/example/api/organizations/route.ts
api.option-source-routes
Dynamic option sources for custom fields (optionsUrl)
Routes backing the optionsUrl of the labels (tags) and assignee (listbox) custom fields declared in ce.ts.src/modules/example/api/tags/route.ts
src/modules/example/api/assignees/route.ts
src/modules/example/api/notifications/route.ts
api.interceptors
API route interceptors (before/after, body and query rewrite)
Exact-route and wildcard targetRoute interceptors covering request rejection, timeout handling, thrown-error handling, query rewriting, cross-module query narrowing to ?ids=, and after response merging via shared metadata.src/modules/example/api/interceptors.ts
commands.write
Command-mediated create/update/delete
Registered command handlers with Zod parsing, custom-field extraction, ensureScope tenant/organization enforcement, prepare snapshots, CRUD side effects, and a fork-isolated native update that avoids flushing unrelated request-scoped state.src/modules/example/commands/todos.ts
commands.undo-redo
Undo, redo, and audit log snapshots
isUndoable handlers with captureAfter, translated buildLog audit entries, buildChanges diffs including custom fields, scope-validating resolveUndoScope, and makeCreateRedo for redo support.src/modules/example/commands/todos.ts
commands.interceptors
Command interceptors (beforeExecute / afterExecute)
Pattern-targeted command interceptor that passes state from beforeExecute to afterExecute through the interceptor metadata bag.src/modules/example/commands/interceptors.ts

Events, Indexing & Cache

For the normative rule behind these capabilities (not just one compiling example), see om-system-extension, om-data-model-design, om-module-scaffold.

CapabilityDemonstratesSource
events.typed-definitions
Typed module events with createModuleEvents
as const event table producing a typed emitter and a union of emittable event ids, including clientBroadcast: true for DOM Event Bridge delivery.src/modules/example/events.ts
events.crud-indexer-bridge
CRUD event and query-index payload configuration
CrudEventsConfig and CrudIndexerConfig exported from the command module and reused by both the command handlers and the CRUD route, so events and index upserts stay consistent across entrypoints.src/modules/example/commands/todos.ts
events.sync-subscribers
Synchronous before/after CRUD subscribers
Three sync subscriber shapes: payload rewriting before create, rejection with a status code before update, and a non-blocking after-delete handler.src/modules/example/subscribers/auto-default-priority.ts
src/modules/example/subscribers/prevent-uncomplete.ts
src/modules/example/subscribers/audit-delete.ts
events.ephemeral-subscriber
Ephemeral (non-persistent) event subscriber
Minimal persistent: false subscriber that resolves a service from the DI context.src/modules/example/subscribers/example-event.ts
events.portal-broadcast
Portal Event Bridge broadcast with a live emit site
The customer-facing twin of clientBroadcast: an event declared portalBroadcast: true plus the wildcard subscriber that produces it. The subscriber turns internal example.todo.* CRUD writes into one customer-addressable announcement, drops the payload to ids/scope/action so no staff-authored title or encrypted note reaches a customer transport, and returns without emitting when the write carries no tenant AND organization (the portal stream's matchesAudience would discard it anyway). The announcement uses its own todo_announcement entity segment, so the module's own example.todo.* subscribers cannot re-enter on it.src/modules/example/events.ts
src/modules/example/subscribers/announce-todo-to-portal.ts
runtime.tenant-scoped-cache
DI-resolved cache with tenant/organization scoping and tag invalidation
Cache-aside read of a Todo count summary. The logical key carries tenant AND organization, runWithCacheTenant enters the cache-tenant context around every backend call, the cached value re-asserts its own scope on read, and entries are tagged with the same crud:example.todo:tenant:<id>:org:<id>:collection tag makeCrudRoute derives – so the platform's own post-commit invalidateCrudCache drops them too. A wildcard example.todo.* subscriber invalidates after commit on every write path.src/modules/example/lib/todoSummaryCache.ts
src/modules/example/lib/todoSummaryService.ts
src/modules/example/api/todos/summary/route.ts
src/modules/example/subscribers/invalidate-todo-summary.ts
runtime.bulk-operation-progress
Durable bulk operation: outbox, leased worker, and operation progress
Selected-row DataTable bulk action wired to a real ProgressJob. The injected data-only action POSTs { ids, idempotencyKey }; the start route verifies every id inside the caller scope, claims a (tenant, organization, user, idempotency_key)-unique ExampleTodoBulkOperation row plus a progress job, and returns 202 with progressJobId – the value DataTable.runBulkAction tracks on the shared top progress bar. That same row is the transactional outbox: publication is deliberately at-least-once, and the scheduler-driven dispatcher republishes rows that were never delivered or whose execution lease expired. The queue worker takes a compare-and-swap lease, resumes from nextItemIndex, checks isCancellationRequested() before each item, and mutates through the example.todos.update command so audit, undo, events, cache and index invalidation stay intact.src/modules/example/widgets/injection/todo-bulk-complete/widget.ts
src/modules/example/api/todos/bulk-complete/route.ts
src/modules/example/lib/todoBulkComplete.ts
src/modules/example/workers/todos-bulk-complete.ts
src/modules/example/workers/todos-bulk-dispatch.ts

Backend & Frontend UI

For the normative rule behind these capabilities (not just one compiling example), see om-backend-ui-design, om-system-extension.

CapabilityDemonstratesSource
ui.page-shell
Backend page shell and page metadata
Server-rendered Page/PageHeader/PageBody shells plus page.meta.ts declarative guards, navigation group/order, icon token, and breadcrumb with labelKey fallbacks.src/modules/example/backend/todos/page.tsx
src/modules/example/backend/todos/page.meta.ts
src/modules/example/backend/page.tsx
src/modules/example/backend/page.meta.ts
ui.datatable
DataTable list page with export and row actions
Client island rendering DataTable: translated columns, BooleanIcon/EnumBadge value renderers, custom-field column visibility, fetchCrudList data loading, view and full export configs, RowActions with a confirm dialog, flash messages, and pagination.src/modules/example/components/TodosTable.tsx
src/modules/example/types.ts
ui.datatable-perspectives-filters
DataTable perspectives, filters, and organization scope
The perspective={{ tableId }} binding, filters/filterValues/onFiltersApply/onFiltersClear wiring, server-side query param mapping for checkbox and dateRange filters, and useOrganizationScopeVersion cache keying.src/modules/example/components/TodosTable.tsx
ui.form-create
CrudForm create page
CrudForm with memoized translated fields, two-column groups, a customFields group that renders ce.ts definitions, a custom component group, createCrud submission, and a flash-carrying success redirect.src/modules/example/backend/todos/create/page.tsx
src/modules/example/backend/todos/create/page.meta.ts
src/modules/example/components/TodoForm.tsx
ui.form-edit
CrudForm edit page with load, delete, and not-found states
Scoped detail load through fetchCrudList, custom-field initial values via extractCustomFieldEntries, RecordNotFoundState/ErrorMessage, group-level setValue actions, updateCrud/deleteCrud, and pushWithFlash navigation.src/modules/example/backend/todos/[id]/edit/page.tsx
src/modules/example/backend/todos/[id]/edit/page.meta.ts
src/modules/example/components/TodoForm.tsx
ui.frontend-page
Public (non-backend) module page
Minimal storefront-side page proving that a module can own routes outside /backend while still resolving translations.src/modules/example/frontend/example.tsx
ui.page-middleware
Backend page middleware
backend/middleware.ts auto-discovered into backend-middleware.generated.ts and executed by the backend catch-all page through resolvePageMiddlewareRedirect. Shows the two properties of that call site that decide what a page middleware can usefully do: it runs AFTER the route manifest matched and after the requireAuth/requireFeatures guards passed (so it is not an access gate, and a target naming an unrouted path can never fire), and BEFORE the page component loads (so a redirect costs nothing beyond the auth round-trip already paid). The decision is a pure exported pathname function; the middleware entry only maps it onto the { action: 'redirect' | 'continue' } contract.src/modules/example/backend/middleware.ts
ui.frontend-page-middleware
Frontend page middleware
frontend/middleware.ts auto-discovered into frontend-middleware.generated.ts by the same generator extension that folds the backend half, and executed by the public catch-all page through resolvePageMiddlewareRedirect. Three properties of THAT call site separate it from ui.page-middleware: context.auth is null for an anonymous visitor because a public route declares no guard, so the decision must never read the session; it does not run at all for customer-portal routes, because the catch-all returns inside the requireCustomerAuth branch first; and, like the backend half, it only fires on a path a frontend page actually registers. The entry canonicalises a public blog URL and returns continue once the path already is canonical, so the redirect cannot loop.src/modules/example/frontend/middleware.ts
ui.dashboard-widget
Dashboard widget with typed settings
DashboardWidgetModule with metadata, feature gating, default size/enabled state, a lazily loaded client component, and a hydrateSettings/dehydrateSettings pair that clamps persisted user settings back into range.src/modules/example/widgets/dashboard/todos/widget.ts
src/modules/example/widgets/dashboard/todos/config.ts

Unified Module Extension System (UMES)

For the normative rule behind these capabilities (not just one compiling example), see om-system-extension, om-backend-ui-design.

CapabilityDemonstratesSource
umes.mutation-guard
Mutation guard
MutationGuard bound to an entity kind and operation set, returning an { ok: false, message, status } rejection that the shared guard bridge turns into an HTTP error.src/modules/example/data/guards.ts
umes.response-enricher
Response enricher for another module's API
ResponseEnricher adding a namespaced _example block to customers.person list and detail responses, with enrichMany batching, a fallback value, a timeout, and an explicit cacheableOnListHit: false decision.src/modules/example/data/enrichers.ts
umes.extension-points
Declared extension hosts (extension-points.ts)
defineModuleExtensionPoints declaring the four extension hosts this module exposes to others: the Todo DataTable (dataTableExtensionHost), Todo CrudForm (crudFormExtensionHost), phase-C handler injection host (injectionExtensionHost), and component-override showcase (componentExtensionHost). Every host is consumed by its declared source file via extensionPoints.hosts.<key>, which is what the framework's binding detector requires – the extractor reports no unbound-declaration for this module.src/modules/example/extension-points.ts
umes.injection-table
Widget injection table (spot id to widget id mapping)
ModuleInjectionTable mapping every supported spot-id shape – portal sections, crud-form:<entityId>, data-table:<tableId>:<surface>, menu spots, detail spots, tab groups, and a nested widget addon spot – to widget ids. Exported as one unconditional object literal, which is what the fact extractor can fold: it reads 26 contributions from this file (it read 0 while the export was chosen by an env-flag ternary). Cross-module entries ship always-on and are inert without their host module.src/modules/example/widgets/injection-table.ts
umes.customers.calendar-event-types
Customers calendar event types and optional Visit availability
A Customers-owned widget payload adds Visit and optionally patches Meeting while preserving all six built-in types; the same definitions register through soft Customers DI for API and worker paths. The Meeting patch requires OM_EXAMPLE_CALENDAR_DEMO_OVERRIDES=true and are disabled by default. The Visit panel and command interceptor name booking conflicts and warn and skip unavailable staff/resources integrations, keeping calendar policy inside Customers and the contributing module.src/modules/example/widgets/injection/calendar-visit/widget.ts
src/modules/example/di.ts
src/modules/example/components/VisitPanel.tsx
src/modules/example/commands/interceptors.ts
src/modules/example/lib/visitAvailabilityGuard.ts
umes.injection.crud-form-field
Headless CrudForm field injection with a save handler
InjectionFieldWidget contributing a select field into another module's CrudForm, plus an onSave event handler that upserts the value through the contributing module's own API.src/modules/example/widgets/injection/customer-priority-field/widget.ts
umes.injection.datatable-column
Headless DataTable column injection
InjectionColumnWidget adding a column that reads the enricher-provided _example.priority accessor path from another module's list response.src/modules/example/widgets/injection/customer-priority-column/widget.ts
umes.injection.datatable-filter
Headless DataTable filter injection
InjectionFilterWidget contributing a server-strategy select filter whose queryParam is consumed by the module's own API interceptor to narrow the host query.src/modules/example/widgets/injection/customer-priority-filter/widget.ts
umes.injection.datatable-row-action
Headless DataTable row-action injection with placement
InjectionRowActionWidget using InjectionPosition relative placement and a defensively narrowed navigate callback from the host context.src/modules/example/widgets/injection/customer-priority-row-action/widget.ts
umes.injection.datatable-bulk-action
Headless DataTable bulk-action injection
InjectionBulkActionWidget operating on selected rows and returning { ok, affectedCount } to the host table. This is the synchronous in-request bulk-action reference; the queued variant that returns a progressJobId is runtime.bulk-operation-progress.src/modules/example/widgets/injection/customer-priority-bulk-actions/widget.ts
umes.injection.menu-items
Menu item injection into sidebar and profile dropdown
InjectionMenuItemWidget entries with labelKey, icon token, features gating, group assignment, and InjectionPosition placement (Last, and Before a named anchor item).src/modules/example/widgets/injection/example-menus/widget.ts
src/modules/example/widgets/injection/example-profile-menu/widget.ts
umes.injection.rendered-widget
Rendered injection widget with a guarded mutation
Data-only widget.ts registration plus a focused client leaf: readApiResultOrThrow load, useGuardedMutation().runMutation write, DS primitives, semantic tokens, translated loading/saving/error states, and effect cleanup.src/modules/example/widgets/injection/customer-priority-detail/widget.ts
src/modules/example/widgets/injection/customer-priority-detail/widget.client.tsx
umes.component-replacement
Component replacement, wrapping and props transform (widgets/components.ts)
ComponentOverride entries covering all three modes the union defines, exported as one unconditional array literal. wrapper decorates three handles other modules expose, with a pass-through gate that returns the original component BY IDENTITY for the demo-only checkout entries. replacement (plus the propsSchema the union requires alongside it) and propsTransform target a handle this module hosts itself in components/ComponentOverrideShowcase.tsx, rendered by /backend/component-overrides, so the two non-composing modes have a live call site without rewriting a screen that belongs to another module. Ordering is load-bearing, but only on one of the two resolvers: useRegisteredComponent – the client hook this host calls – buckets the modes, so a props transform reaches the render wherever it sorted and the highest-priority replacement wins; resolveRegisteredComponent, the server fold behind page: handles, walks in one pass and assigns resolved = override.replacement, discarding everything composed before it. The replacement takes the lowest number on the handle so both resolvers produce the same tree. Every value the fact extractor must read – the handle constant and the propsTransform callable – is declared in widgets/components.ts itself, because staticValue resolves an identifier only against initializers in the file it parses; a cross-file import publishes zero contributions for the handle and misclassifies the transform as replace.src/modules/example/widgets/components.ts
src/modules/example/components/ComponentOverrideShowcase.tsx
src/modules/example/backend/component-overrides/page.tsx
src/modules/example/backend/component-overrides/page.meta.ts

For the normative rule behind these capabilities (not just one compiling example), see om-module-scaffold, om-data-model-design.

CapabilityDemonstratesSource
search.module-config
Module search configuration
SearchModuleConfig for one entity: buildSource text chunks with checksumSource, formatResult presenter, resolveUrl deep link, per-entity aclFeatures, and a fieldPolicy whose searchable whitelist carries only plaintext columns while the encrypted column is excluded. Token search over the encrypted column still works, because search_tokens rows are built from the DECRYPTED index doc and are not gated by this policy.src/modules/example/search.ts
search.vector-config
Deterministic Todo vector configuration
VectorModuleConfig for the Todo entity with deterministic source and checksum builders, a translated presenter and deep link, and an explicit plaintext-only policy that excludes encrypted notes from embeddings.src/modules/example/vector.ts
search.encrypted-column-list-filter
List filtering over an encrypted column through the token index
Text search over the encrypted notes column uses a plain $ilike, the SAME shape as the plaintext title filter. The query engine intercepts like/ilike and rewrites it into a hashed search_tokens lookup when the column is encrypted and search is active (packages/shared/src/lib/query/engine.ts → applyFilterOp), applying the tenant/organization scope itself via applySearchTokens; the index stores hashes of the DECRYPTED value because the indexer runs decryptIndexDocForSearch before tokenizing. The lesson this row teaches is that a module must NOT hand-roll an id narrowing for an encrypted column – that duplicates platform behaviour and re-derives a scope the platform already applies. When search is off the engine warns via warnOnCiphertextLikeFallback rather than silently matching nothing.src/modules/example/api/todos/route.ts

AI Tools & Agents

For the normative rule behind these capabilities (not just one compiling example), see om-create-ai-agent.

CapabilityDemonstratesSource
ai.tool-pack
AI tool pack (ai-tools.ts)
Module-root tool pack folded into ai-tools.generated.ts and loaded into the MCP tool registry. Two read-only tools declared with defineAiTool, both gated on features that exist in acl.ts, and both resolving tenant/organization from the runtime-supplied McpToolContext through a fail-closed helper – never from tool input, which a prompt-injected model controls. example.get_todo_summary deliberately reads through this module's own DI service instead of counting rows itself, so the tool and api/todos/summary/route.ts cannot drift.src/modules/example/ai-tools.ts
ai.agent
AI agent definition (ai-agents.ts)
One read-only chat agent over this module's own tool pack. readOnly: true and mutationPolicy: 'read-only' agree because every declared tool is isMutation: false; allowedTools is a closed whitelist, so adding a tool to ai-tools.ts does not silently widen the agent. systemPrompt is assembled from named LOCAL sections for authoring clarity only – AiAgentDefinition.systemPrompt is a plain string and the override path wraps it as a single role section, so those names are NOT addressable by the prompt-override system.src/modules/example/ai-agents.ts
ai.agent-extension
Additive AI agent extension
aiAgentExtensions exported from the same ai-agents.ts, patching an agent another module owns (customers.account_assistant) instead of forking it. Purely additive – appendAllowedTools / appendSystemPrompt / appendSuggestions, no replace and no delete – and it lends only a tool this module declares. When the target agent is absent the registry logs Skipping extension for unknown agent and continues; an extension is never allowed to fail a boot.src/modules/example/ai-agents.ts
ai.tool-override
File-tier AI tool override
aiToolOverrides exported from ai-tools.ts – a keyed replace-or-disable map the generator emits as aiToolOverrideEntries and the runtime folds in through composeToolOverrideMap then applyToolOverrideMap. null removes a tool by name; a definition replaces it, and a replacement whose name does not equal its key is skipped with a warning, so key and definition cannot drift apart. It is tier 3 of four (programmatic > modules.ts > this file > the base declaration), which makes a module-shipped override a default rather than a final word. The key deliberately names a tool THIS module owns: a production override names a foreign tool, but a canonical reference module that is enabled for inspection must not silently change a shipped assistant. The replacement is derived from the base by spread, so the handler cannot fork into two implementations.src/modules/example/ai-tools.ts
ai.agent-override
File-tier AI agent override
aiAgentOverrides exported from ai-agents.ts, alongside the base aiAgents and the additive aiAgentExtensions in the same file – three mechanisms the generator reads separately. This one is keyed replace-or-disable: null deletes the agent from the registry, a definition replaces it wholesale, and a replacement whose id does not equal its key is skipped and the base entry survives. Reach for the override when you must change what an agent IS; reach for the extension when you only want to lend it something. Same tier position and the same self-targeting rationale as ai.tool-override.src/modules/example/ai-agents.ts

Notifications & Messages

For the normative rule behind these capabilities (not just one compiling example), see om-system-extension.

CapabilityDemonstratesSource
notifications.type
In-app notification type declaration
NotificationTypeDefinition with translation keys for title/body, severity, icon token, actions with variants and hrefs, a primary action id, and an expiry window.src/modules/example/notifications.ts
notifications.reactive-handler
Reactive notification handler
NotificationHandler bound to a notification type, feature-gated, raising a toast and re-emitting a DOM event so other client code can react.src/modules/example/notifications.handlers.ts
notifications.client-renderer
Client notification renderer (notifications.client.ts)
Client-side re-declaration of the module's server notification types with a custom Renderer attached. Maps over notifications.ts instead of restating literals, so the frozen notification id, translation keys, actions, and expiry stay single-sourced. The renderer's action-selection decision is exported as a pure function; the component itself is inline (and therefore built with React.createElement) rather than living in widgets/notifications/ – see the outstanding-notes list in surface-map.md.src/modules/example/notifications.client.ts
messages.object-type
Message object type registration and server-side preview
MessageObjectTypeDefinition binding an entity to the messages module, plus a server-only preview loader that uses findOneWithDecryption with explicit tenant/organization scope and translated fallbacks.src/modules/example/message-objects.ts
src/modules/example/lib/messageObjectPreviews.ts

Integrations & Workflows

For the normative rule behind these capabilities (not just one compiling example), see om-integration-builder, om-module-scaffold.

CapabilityDemonstratesSource
integrations.mock-adapters
Mock payment, shipping, and inbound-webhook adapters
Credential-free adapters implementing the gateway, carrier, and webhook-endpoint contracts, including signature verification. Use them to understand adapter shape; production providers live in their own npm workspace packages.src/modules/example/lib/mock-gateway-adapter.ts
src/modules/example/lib/mock-shipping-adapter.ts
src/modules/example/lib/mock-webhook-endpoint-adapter.ts
integrations.local-bundle
Credential-free local integration bundle
A discoverable integration bundle that reuses the module's payment and shipping mocks and adds a deterministic currency-rate provider. The provider is registered through DI and all three identities require neither credentials nor network access.src/modules/example/integration.ts
src/modules/example/di.ts
src/modules/example/lib/mock-currency-rate-provider.ts
workflows.code-definition
Event-triggered code workflow
A minimal code workflow whose trigger consumes the existing typed example.todo.created event, maps the Todo id into workflow context, and reaches an end node without activities, credentials, or external side effects.src/modules/example/workflows.ts

Unified Module Overrides

For the normative rule behind these capabilities (not just one compiling example), see om-system-extension.

CapabilityDemonstratesSource
overrides.unified-registry
Unified module overrides in the app registry
Typed, inactive entry.overrides examples for every wired override domain (routes, events, workers, widgets, notifications, interceptors, command interceptors, enrichers, guards, cli, setup, acl, di, encryption, nav). Lives in the app registry, not in the module.src/modules.ts
overrides.compileable-reference
Compileable entry.overrides reference inside the module
A typed, inert ModuleOverrides value covering all sixteen wired domains, kept in the module's own references/ folder. It exists because the app-registry copy does not survive scaffolding: applyStarterPreset rewrites src/modules.ts from a lean template for the empty and crm presets, and that template's ModuleEntry type does not even declare an overrides field – while this module's source ships in every preset. Compiling against the real ModuleOverrides interface is what makes it break the build instead of rotting when a domain is renamed or retyped. Nothing imports it into a ModuleEntry, so the dispatcher never sees it in a running app.src/modules/example/references/module-overrides.reference.ts

Testing Evidence (QA-only)

Caution · QA-only – not a copyable pattern

testing.integration-coverage – Repository-only Playwright and unit suites for the module. Standalone scaffolding filters __tests__/** and __integration__/** out of emitted apps, so these are evidence paths, never readable emitted source. Follow the testing guide for how to write your own.

These paths are repository-only evidence, not emitted source: standalone scaffolding filters __tests__/** and __integration__/** out of generated apps, so a fresh app never receives them and they must never be copied as if they were runtime code. For how to write your own coverage, see om-integration-tests.

Repository-only evidence paths:

See also

Previous: Push Notifications · Next: Routes and pages