Framework
Suppose a fleet module needs a service history for a customer-owned vehicle. Keep those records in the module that owns them and reference the existing entity. If the need is just one extra value on a record, consider a custom field first.
This doc outlines how modules extend each other’s data (without forking schemas) and how users add custom fields at runtime.
src/modules/<module>/data/extensions.ts using a small DSL (Medusa-like):import { defineLink, entityId, linkable } from '@/modules/dsl'
// Option A: refer using explicit entityId()
export default [
defineLink(
entityId('auth', 'user'),
entityId('my_module', 'user_profile'),
{ join: { baseKey: 'id', extensionKey: 'user_id' }, cardinality: 'one-to-one', description: 'Adds profile fields to users' }
)
]
// Option B: use linkable() helper (similar to Medusa’s Module.linkable)
const Auth = { linkable: linkable('auth', ['user']) }
const My = { linkable: linkable('my_module', ['user_profile']) }
export const extensions = [
defineLink(Auth.linkable.user, My.linkable.user_profile, { join: { baseKey: 'id', extensionKey: 'user_id' } })
]
data/entities.ts of your module, with a FK to the base entity id.entityExtensions in modules.generated.ts for discovery.entities ships two tables:
custom_field_defs – definitions (per entity id, organization, and tenant)custom_field_values – values (per entity record, organization, and tenant)– Declare initial field sets in module-level ce.ts by attaching a fields array to an entity entry. data/fields.ts is no longer supported.
// src/modules/<module>/ce.ts
export const entities = [
{
id: '<module>:<entity>',
label: 'My Entity',
showInSidebar: true, // optional: default sidebar visibility
fields: [
{ key: 'priority', kind: 'integer', label: 'Priority', defaultValue: 3, filterable: true, formEditable: true },
{ key: 'severity', kind: 'select', label: 'Severity', options: ['low','medium','high'], defaultValue: 'medium', filterable: true, formEditable: true },
],
},
]
Notes:
entities[].fields into Module.customFieldSets automatically, so yarn mercato entities install will seed them.export const entities = [
{ id: 'auth:user', fields: [ { key: 'nickname', kind: 'text', label: 'Nickname', formEditable: true } ] },
]
id matches a generated system entity (from generated/entities.ids.generated.ts), it only seeds or updates field definitions. The base entity stays marked as “system”.id is not a system entity, the installer automatically creates/updates a corresponding row in custom_entities so the entity shows up in the UI and can store records.global: true to install it once with tenant_id = null.Set encrypted: true to store a field's values encrypted with the tenant key, the same way required or listVisible are declared:
export const entities = [
{ id: 'crm:contact', fields: [ { key: 'national_id', kind: 'text', label: 'National ID', encrypted: true } ] },
]
The declaration is idempotent – re-running entities install keeps the flag. A field an administrator encrypted through the admin UI also keeps its flag when the declaration omits encrypted, because clearing it would leave stored ciphertext that the read path no longer decrypts. To turn encryption off, declare encrypted: false explicitly (existing values stay encrypted at rest and must be migrated separately).
import { defineFields, entityId, cf } from '@/modules/dsl'
export default [
defineFields(entityId('directory','organization'), [
cf.select('industry', ['SaaS','Retail','Agency'], { filterable: true }),
cf.boolean('vip', { filterable: true }),
], 'my_module')
]
Custom entity definitions and field sets declared in ce.ts are applied by the entities CLI. The command is idempotent and uses checksums to skip unchanged configurations.
yarn mercato entities install
Key flags:
| Flag | Description |
|---|---|
--tenant <id> | Restrict sync to a specific tenant. Without this flag, every tenant in the database is processed. |
--global | Only install global definitions (sets tenant_id = null). |
--no-global | Skip global scope (default is to include both global and tenant-specific). |
--force | Ignore cached checksums and reapply definitions even if nothing changed. |
--dry-run | Show what would change without writing to the database. |
The CLI runs quickly thanks to checksum caching stored under custom-entity:* cache tags. Use --force (or the reinstall subcommand) after editing ce.ts if you need to bypass the cache immediately.
Why not migrations? Migrations are module-scoped, run in isolation, and should alter schema deterministically. Field sets aggregate across all enabled modules at the app level and may target specific tenants; executing them in each module’s migration would cause duplication, ordering problems, and environment coupling. Use the CLI to seed or re-seed idempotently whenever modules change.
The integrations module provides a built-in entity and enricher for tracking external system IDs alongside internal records.
SyncExternalIdMapping (table: sync_external_id_mappings) stores the link between an internal entity record and its counterpart in an external system.
| Column | Type | Description |
|---|---|---|
id | UUID PK | Auto-generated |
integration_id | text | Identifies the integration (e.g. sync_shopify) |
internal_entity_type | text | Target entity type (e.g. catalog.product) |
internal_entity_id | UUID | Internal record ID |
external_id | text | ID in the external system |
sync_status | text | synced, pending, error, or not_synced |
last_synced_at | timestamp | Last successful sync time |
organization_id | UUID | Tenant-scoped |
tenant_id | UUID | Tenant-scoped |
Entity source: packages/core/src/modules/integrations/data/entities.ts
The externalIdMappingEnricher response enricher adds an _integrations namespace to any entity's API response. It targets all entities (targetEntity: '*') and uses batch queries via enrichMany to prevent N+1.
Enriched response shape:
{
"id": "abc-123",
"name": "Example Product",
"_integrations": {
"sync_shopify": {
"externalId": "shp_prod_123",
"externalUrl": "https://admin.shopify.com/store/demo/products/shp_prod_123",
"lastSyncedAt": "2026-02-28T10:00:00.000Z",
"syncStatus": "synced"
},
"gateway_stripe": {
"externalId": "cus_abc456",
"syncStatus": "pending"
}
}
}
The externalUrl field is populated when the integration registers a buildExternalUrl callback.
Register integration definitions at module bootstrap so the enricher and UI widgets can resolve metadata:
import { registerIntegration } from '@open-mercato/shared/modules/integrations/types'
registerIntegration({
id: 'sync_shopify',
title: 'Shopify',
icon: 'shopify',
buildExternalUrl: (externalId) =>
`https://admin.shopify.com/store/demo/products/${externalId}`,
})
Available helpers:
| Function | Description |
|---|---|
registerIntegration(def) | Register a single integration definition |
registerIntegrations(defs) | Register multiple definitions at once |
getIntegration(id) | Get definition by ID |
getAllIntegrations() | List all registered definitions |
getIntegrationTitle(id) | Get title, falling back to the raw ID |
Types: IntegrationDefinition, ExternalIdEnrichment, ExternalIdMapping from @open-mercato/shared/modules/integrations/types.
See also: Integration enhancements, Widget injection
tenant_id only. organization_id is not applied to custom field discovery or value joins.tenant_id and, when provided, additionally by organization_id.entities module migrations are generated like any other module.When you declare a new entity in ce.ts, yarn mercato entities install automatically ensures a matching row exists in custom_entities (unless the entity id is already part of the generated system enum). In advanced scenarios you may still register entities manually – for example, during a bespoke bootstrap flow or runtime provisioning. Use the helper provided by the core module:
import { upsertCustomEntity } from '@open-mercato/core/modules/entities/lib/register'
// inside a CLI command, module init, or DI registrar where you have an EM
await upsertCustomEntity(em, 'example:calendar_entity', {
label: 'Calendar Entity',
description: 'Events and availability',
// optional scope
organizationId: null,
tenantId: null,
})
If the entity exists, label/description are updated; if not, it is created. After registering, admins can define fields for it under Backend → Data designer → System/User Entities.
Registering from DI (on boot)
// src/modules/<module>/di.ts
import type { AppContainer } from '@/lib/di/container'
import { upsertCustomEntity } from '@open-mercato/core/modules/entities/lib/register'
let registered = false
export function register(container: AppContainer) {
if (registered) return
registered = true
;(async () => {
const em = container.resolve('em') as any
await upsertCustomEntity(em, '<module>:<entity>', {
label: 'My Entity',
description: 'Declared from DI on boot',
// Optionally scope to org/tenant
organizationId: null,
tenantId: null,
})
})().catch(() => {})
}
Note: DI registrars may run per request container; the helper is idempotent and safe to call multiple times.
Previous: Encrypted Data Seeding · Next: Entities and migrations