Framework
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.
It is the canonical app-local teaching module. One minimal, real declaration per mechanism, kept in sync as the framework evolves.
Its source ships everywhere. The same tree exists in the monorepo (apps/mercato/src/modules/example/), in the create-mercato-app template, and in every built-in standalone preset (classic, empty, crm).
It is source-present but runtime-disabled by default – in every layout, including this monorepo. No route, page, migration, seed, ACL grant, event, widget, worker, or navigation entry loads until you explicitly enable it. To run it locally for inspection:
// src/modules.ts
export default [
{ id: 'example', from: '@app' },
]
Then regenerate the runtime registries and apply its committed migrations before starting the app:
yarn generate
yarn db:migrate
yarn generate never applies migrations on its own – skipping yarn db:migrate after enabling example on an already-initialized app leaves its routes active without their tables.
It is a reference for one compiling way to do something – not the production authority for everything. For provider internals (payment gateways, shipping carriers, webhook adapters), it demonstrates the integration seam only; the normative guide is om-integration-builder. For workflow orchestration beyond a minimal trigger, see the workflows framework guide. For mutation-capable AI (tools that write, not just read), see om-create-ai-agent. For portal/customer authentication, see the customer_accounts module guide.
Do not copy the whole tree. example is deliberately broad – it doubles as the platform's own QA surface, and it contains demo pages, probe routes, and mock adapters that must never appear in a product module. Copy one capability at a time, from the exact file this page names, and rename every example-scoped identifier (module id, entity id, table names, route paths, command/event ids, widget/ACL/i18n ids) before the code is yours – the module's own copy/adapt checklist has the exact 10-step list.
Every row below carries:
capabilityId from the module's machine-readable inventory (references/surface-inventory.json), so a row here and a row in that file are always the same thing.main branch. Read only these – not the surrounding directory.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.
For the normative rule behind these capabilities (not just one compiling example), see om-module-scaffold, om-integration-builder.
| Capability | Demonstrates | Source |
|---|---|---|
module.metadataModule 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-featuresACL 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-featuresTenant 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.tssrc/modules/example/lib/exampleSeeds.ts |
module.di-registrationModule 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.tssrc/modules/example/lib/todoSummaryService.ts |
module.cli-commandModule 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-catalogsModule 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.jsonsrc/modules/example/i18n/de.jsonsrc/modules/example/i18n/es.jsonsrc/modules/example/i18n/pl.json |
module.translatable-fieldsTranslatable 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-targetTenant 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-pluginDeterministic 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.tssrc/modules/example/reference-index.tssrc/modules/example/lib/module-reference-index.ts |
For the normative rule behind these capabilities (not just one compiling example), see om-data-model-design, om-system-extension.
| Capability | Demonstrates | Source |
|---|---|---|
data.entitiesMikroORM 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.validatorsZod 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-fieldsCustom 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.migrationsModule 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.tssrc/modules/example/migrations/Migration20260226161000_example.tssrc/modules/example/migrations/Migration20260804120546_example.tssrc/modules/example/migrations/.snapshot-open-mercato.json |
data.encryption-mapTenant 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.tssrc/modules/example/data/entities.tssrc/modules/example/commands/todos.ts |
data.entity-extensionsCross-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 |
For the normative rule behind these capabilities (not just one compiling example), see om-module-scaffold, om-system-extension, om-data-model-design.
| Capability | Demonstrates | Source |
|---|---|---|
api.crud-factoryCRUD 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-fieldsCRUD 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.openapiOpenAPI 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-routeHand-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-routesDynamic 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.tssrc/modules/example/api/assignees/route.tssrc/modules/example/api/notifications/route.ts |
api.interceptorsAPI 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.writeCommand-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-redoUndo, 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.interceptorsCommand 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 |
For the normative rule behind these capabilities (not just one compiling example), see om-system-extension, om-data-model-design, om-module-scaffold.
| Capability | Demonstrates | Source |
|---|---|---|
events.typed-definitionsTyped 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-bridgeCRUD 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-subscribersSynchronous 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.tssrc/modules/example/subscribers/prevent-uncomplete.tssrc/modules/example/subscribers/audit-delete.ts |
events.ephemeral-subscriberEphemeral (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-broadcastPortal 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.tssrc/modules/example/subscribers/announce-todo-to-portal.ts |
runtime.tenant-scoped-cacheDI-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.tssrc/modules/example/lib/todoSummaryService.tssrc/modules/example/api/todos/summary/route.tssrc/modules/example/subscribers/invalidate-todo-summary.ts |
runtime.bulk-operation-progressDurable 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.tssrc/modules/example/api/todos/bulk-complete/route.tssrc/modules/example/lib/todoBulkComplete.tssrc/modules/example/workers/todos-bulk-complete.tssrc/modules/example/workers/todos-bulk-dispatch.ts |
For the normative rule behind these capabilities (not just one compiling example), see om-backend-ui-design, om-system-extension.
| Capability | Demonstrates | Source |
|---|---|---|
ui.page-shellBackend 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.tsxsrc/modules/example/backend/todos/page.meta.tssrc/modules/example/backend/page.tsxsrc/modules/example/backend/page.meta.ts |
ui.datatableDataTable 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.tsxsrc/modules/example/types.ts |
ui.datatable-perspectives-filtersDataTable 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-createCrudForm 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.tsxsrc/modules/example/backend/todos/create/page.meta.tssrc/modules/example/components/TodoForm.tsx |
ui.form-editCrudForm 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.tsxsrc/modules/example/backend/todos/[id]/edit/page.meta.tssrc/modules/example/components/TodoForm.tsx |
ui.frontend-pagePublic (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-middlewareBackend 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-middlewareFrontend 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-widgetDashboard 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.tssrc/modules/example/widgets/dashboard/todos/config.ts |
For the normative rule behind these capabilities (not just one compiling example), see om-system-extension, om-backend-ui-design.
| Capability | Demonstrates | Source |
|---|---|---|
umes.mutation-guardMutation 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-enricherResponse 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-pointsDeclared 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-tableWidget 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-typesCustomers 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.tssrc/modules/example/di.tssrc/modules/example/components/VisitPanel.tsxsrc/modules/example/commands/interceptors.tssrc/modules/example/lib/visitAvailabilityGuard.ts |
umes.injection.crud-form-fieldHeadless 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-columnHeadless 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-filterHeadless 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-actionHeadless 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-actionHeadless 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-itemsMenu 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.tssrc/modules/example/widgets/injection/example-profile-menu/widget.ts |
umes.injection.rendered-widgetRendered 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.tssrc/modules/example/widgets/injection/customer-priority-detail/widget.client.tsx |
umes.component-replacementComponent 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.tssrc/modules/example/components/ComponentOverrideShowcase.tsxsrc/modules/example/backend/component-overrides/page.tsxsrc/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.
| Capability | Demonstrates | Source |
|---|---|---|
search.module-configModule 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-configDeterministic 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-filterList 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 |
For the normative rule behind these capabilities (not just one compiling example), see om-create-ai-agent.
| Capability | Demonstrates | Source |
|---|---|---|
ai.tool-packAI 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.agentAI 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-extensionAdditive 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-overrideFile-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-overrideFile-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 |
For the normative rule behind these capabilities (not just one compiling example), see om-system-extension.
| Capability | Demonstrates | Source |
|---|---|---|
notifications.typeIn-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-handlerReactive 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-rendererClient 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-typeMessage 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.tssrc/modules/example/lib/messageObjectPreviews.ts |
For the normative rule behind these capabilities (not just one compiling example), see om-integration-builder, om-module-scaffold.
| Capability | Demonstrates | Source |
|---|---|---|
integrations.mock-adaptersMock 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.tssrc/modules/example/lib/mock-shipping-adapter.tssrc/modules/example/lib/mock-webhook-endpoint-adapter.ts |
integrations.local-bundleCredential-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.tssrc/modules/example/di.tssrc/modules/example/lib/mock-currency-rate-provider.ts |
workflows.code-definitionEvent-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 |
For the normative rule behind these capabilities (not just one compiling example), see om-system-extension.
| Capability | Demonstrates | Source |
|---|---|---|
overrides.unified-registryUnified 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-referenceCompileable 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 |
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:
src/modules/example/__integration__/meta.tssrc/modules/example/__integration__/TC-EXAMPLE-001-todo-label-edit.spec.tssrc/modules/example/__integration__/TC-EXAMPLE-002-query-index-failure.spec.tssrc/modules/example/__integration__/TC-EXAMPLE-015-specialized-registries.spec.tssrc/modules/example/__integration__/TC-EXAMPLE-016-generator-plugin.spec.tssrc/modules/example/__integration__/TC-UMES-001.spec.tssrc/modules/example/__integration__/TC-UMES-002.spec.tssrc/modules/example/__integration__/TC-UMES-003.spec.tssrc/modules/example/__integration__/TC-UMES-004.spec.tssrc/modules/example/__integration__/TC-UMES-005.spec.tssrc/modules/example/__integration__/TC-UMES-006-mutation-lifecycle.spec.tssrc/modules/example/__integration__/TC-UMES-012.spec.tssrc/modules/example/__integration__/TC-UMES-022-overrides.spec.tssrc/modules/example/__integration__/todo-priority-validation.spec.tssrc/modules/example/__tests__/acl-dependencies.test.tssrc/modules/example/__tests__/extension-points.test.tssrc/modules/example/__tests__/notifications.client.test.tsxsrc/modules/example/__tests__/translations.test.tssrc/modules/example/commands/__tests__/todos.prepare-scope.test.tssrc/modules/example/widgets/__tests__/injection-table.test.tsce.ts contract behind data.custom-fields.umes.injection.* row.create-mercato-module and list it on modules.openmercato.com.