@open-mercato/shared 0.10.1-develop.8004.1.a8a79ee43f → 0.10.1-develop.8024.1.02dbc16b49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/lib/data/engine.js +40 -44
- package/dist/lib/data/engine.js.map +2 -2
- package/dist/lib/db/recordScope.js +72 -0
- package/dist/lib/db/recordScope.js.map +7 -0
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/package.json +2 -2
- package/src/lib/data/__tests__/engine.custom-entity-encryption-sort.integration.test.ts +4 -0
- package/src/lib/data/__tests__/engine.custom-entity-encryption.integration.test.ts +4 -0
- package/src/lib/data/__tests__/engine.custom-entity-encryption.test.ts +4 -0
- package/src/lib/data/__tests__/engine.custom-entity-require-active.test.ts +4 -0
- package/src/lib/data/__tests__/engine.custom-entity-storage-scope.test.ts +4 -0
- package/src/lib/data/__tests__/engine.custom-entity-storage-upsert.test.ts +138 -0
- package/src/lib/data/__tests__/engine.custom-entity-storage.pg.test.ts +152 -0
- package/src/lib/data/__tests__/engine.pin-organization-id.test.ts +4 -0
- package/src/lib/data/__tests__/engine.set-custom-fields-signal.test.ts +100 -0
- package/src/lib/data/__tests__/engine.table-exists-cache.test.ts +4 -0
- package/src/lib/data/engine.ts +63 -59
- package/src/lib/db/__tests__/recordScope.test.ts +116 -0
- package/src/lib/db/recordScope.ts +130 -0
package/.turbo/turbo-build.log
CHANGED
package/dist/lib/data/engine.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY
|
|
7
7
|
} from "../crud/types.js";
|
|
8
8
|
import { conflict, CrudHttpError, isUniqueViolation, notFound } from "../crud/errors.js";
|
|
9
|
-
import { withAdvisoryXactLock } from "../db/advisoryLock.js";
|
|
9
|
+
import { AdvisoryLockUnavailableError, withAdvisoryXactLock } from "../db/advisoryLock.js";
|
|
10
10
|
import { resolveRegisteredEntityTableName } from "../query/engine.js";
|
|
11
11
|
import { getEntityIds } from "../encryption/entityIds.js";
|
|
12
12
|
import { normalizeCustomFieldValues } from "../custom-fields/normalize.js";
|
|
@@ -128,7 +128,6 @@ class DefaultDataEngine {
|
|
|
128
128
|
const [mod, ent] = (entityId || "").split(":");
|
|
129
129
|
if (mod && ent) {
|
|
130
130
|
const eventName = `${mod}.${ent}.updated`;
|
|
131
|
-
warnIfUndeclaredEvent(eventName, "setCustomFields");
|
|
132
131
|
try {
|
|
133
132
|
await bus.emitEvent(eventName, { id: recordId, organizationId, tenantId }, {
|
|
134
133
|
persistent: true,
|
|
@@ -205,9 +204,44 @@ class DefaultDataEngine {
|
|
|
205
204
|
throw new CrudHttpError(400, { error: "Validation failed", fields: result.fieldErrors });
|
|
206
205
|
}
|
|
207
206
|
}
|
|
207
|
+
async withCustomEntityStorageLock(lockKey, work) {
|
|
208
|
+
if (!this.em.isInTransaction?.()) return withAdvisoryXactLock(this.em, lockKey, work);
|
|
209
|
+
const deadlineAt = Date.now() + 15e3;
|
|
210
|
+
while (true) {
|
|
211
|
+
const rows = await this.em.execute(
|
|
212
|
+
"select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked",
|
|
213
|
+
[lockKey]
|
|
214
|
+
);
|
|
215
|
+
if (rows[0]?.locked) return work(this.em);
|
|
216
|
+
const remainingMs = deadlineAt - Date.now();
|
|
217
|
+
if (remainingMs <= 0) throw new AdvisoryLockUnavailableError("deadline", lockKey);
|
|
218
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(50, remainingMs)));
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async writeCustomEntityStorageDoc(target) {
|
|
222
|
+
const lockKey = `custom_entity_create:${JSON.stringify([target.tenantId, target.organizationId, target.entityType, target.entityId.toLowerCase()])}`;
|
|
223
|
+
await this.withCustomEntityStorageLock(lockKey, async (txEm) => {
|
|
224
|
+
const db = txEm.getKysely();
|
|
225
|
+
const doc = sql`${JSON.stringify(target.doc)}::jsonb`;
|
|
226
|
+
let update = db.updateTable("custom_entities_storage").set({ doc, updated_at: sql`now()`, deleted_at: null }).where("entity_type", "=", target.entityType).where("entity_id", "=", target.entityId).where("organization_id", target.organizationId === null ? "is" : "=", target.organizationId).where("tenant_id", target.tenantId === null ? "is" : "=", target.tenantId);
|
|
227
|
+
if (target.requireActive) update = update.where("deleted_at", "is", null);
|
|
228
|
+
const updated = await update.executeTakeFirst();
|
|
229
|
+
if (Number(updated.numUpdatedRows) > 0) return;
|
|
230
|
+
if (target.requireActive) throw notFound();
|
|
231
|
+
await db.insertInto("custom_entities_storage").values({
|
|
232
|
+
entity_type: target.entityType,
|
|
233
|
+
entity_id: target.entityId,
|
|
234
|
+
organization_id: target.organizationId,
|
|
235
|
+
tenant_id: target.tenantId,
|
|
236
|
+
doc,
|
|
237
|
+
created_at: sql`now()`,
|
|
238
|
+
updated_at: sql`now()`,
|
|
239
|
+
deleted_at: null
|
|
240
|
+
}).execute();
|
|
241
|
+
});
|
|
242
|
+
}
|
|
208
243
|
async createCustomEntityRecord(opts) {
|
|
209
244
|
assertCustomEntityStorageEntityId(this.em, opts.entityId);
|
|
210
|
-
const db = this.getKysely();
|
|
211
245
|
await this.ensureStorageTableExists();
|
|
212
246
|
const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {
|
|
213
247
|
entityId: opts.entityId,
|
|
@@ -258,7 +292,7 @@ class DefaultDataEngine {
|
|
|
258
292
|
const lockKey = `custom_entity_create:${JSON.stringify([tenantId, orgId, opts.entityId, id.toLowerCase()])}`;
|
|
259
293
|
await withAdvisoryXactLock(this.em, lockKey, async (txEm) => {
|
|
260
294
|
const storage = txEm.getKysely();
|
|
261
|
-
const existing = await storage.selectFrom("custom_entities_storage").select("entity_id").where("entity_type", "=", opts.entityId).where(sql`lower(entity_id)`, "=", id.toLowerCase()).where("organization_id", orgId === null ? "is" : "=", orgId).where("tenant_id", tenantId === null ? "is" : "=", tenantId).executeTakeFirst();
|
|
295
|
+
const existing = await storage.selectFrom("custom_entities_storage").select("entity_id").where("entity_type", "=", opts.entityId).where(sql`lower(entity_id::text)`, "=", id.toLowerCase()).where("organization_id", orgId === null ? "is" : "=", orgId).where("tenant_id", tenantId === null ? "is" : "=", tenantId).executeTakeFirst();
|
|
262
296
|
if (existing) throw duplicateError();
|
|
263
297
|
try {
|
|
264
298
|
await storage.insertInto("custom_entities_storage").values(payload).execute();
|
|
@@ -268,22 +302,7 @@ class DefaultDataEngine {
|
|
|
268
302
|
}
|
|
269
303
|
});
|
|
270
304
|
} else {
|
|
271
|
-
|
|
272
|
-
await db.insertInto("custom_entities_storage").values(payload).onConflict((oc) => oc.columns(["entity_type", "entity_id", "organization_id"]).doUpdateSet({
|
|
273
|
-
doc: sql`${JSON.stringify(doc)}::jsonb`,
|
|
274
|
-
updated_at: sql`now()`,
|
|
275
|
-
deleted_at: null
|
|
276
|
-
})).execute();
|
|
277
|
-
} catch {
|
|
278
|
-
const updated = await db.updateTable("custom_entities_storage").set({
|
|
279
|
-
doc: sql`${JSON.stringify(doc)}::jsonb`,
|
|
280
|
-
updated_at: sql`now()`,
|
|
281
|
-
deleted_at: null
|
|
282
|
-
}).where("entity_type", "=", opts.entityId).where("entity_id", "=", id).where("organization_id", orgId === null ? "is" : "=", orgId).where("tenant_id", tenantId === null ? "is" : "=", tenantId).executeTakeFirst();
|
|
283
|
-
if (!updated || Number(updated.numUpdatedRows ?? 0) === 0) {
|
|
284
|
-
await db.insertInto("custom_entities_storage").values(payload).execute();
|
|
285
|
-
}
|
|
286
|
-
}
|
|
305
|
+
await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc });
|
|
287
306
|
}
|
|
288
307
|
if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {
|
|
289
308
|
await this.setCustomFields({
|
|
@@ -337,30 +356,7 @@ class DefaultDataEngine {
|
|
|
337
356
|
doc: { ...prevDoc, ...this.normalizeDocValues(sanitizedValues || {}), id },
|
|
338
357
|
encryptionService: this.resolveCustomEntityEncryptionService()
|
|
339
358
|
});
|
|
340
|
-
|
|
341
|
-
const updated = await applyScope(
|
|
342
|
-
db.updateTable("custom_entities_storage").set({
|
|
343
|
-
doc: sql`${JSON.stringify(nextDoc)}::jsonb`,
|
|
344
|
-
updated_at: sql`now()`,
|
|
345
|
-
deleted_at: null
|
|
346
|
-
})
|
|
347
|
-
).executeTakeFirst();
|
|
348
|
-
if (!updated || Number(updated.numUpdatedRows ?? 0) === 0) {
|
|
349
|
-
if (requireActive) throw notFound();
|
|
350
|
-
await db.insertInto("custom_entities_storage").values({
|
|
351
|
-
entity_type: opts.entityId,
|
|
352
|
-
entity_id: id,
|
|
353
|
-
organization_id: orgId,
|
|
354
|
-
tenant_id: tenantId,
|
|
355
|
-
doc: sql`${JSON.stringify(nextDoc)}::jsonb`,
|
|
356
|
-
created_at: sql`now()`,
|
|
357
|
-
updated_at: sql`now()`,
|
|
358
|
-
deleted_at: null
|
|
359
|
-
}).execute();
|
|
360
|
-
}
|
|
361
|
-
} catch (err) {
|
|
362
|
-
throw err;
|
|
363
|
-
}
|
|
359
|
+
await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc: nextDoc, requireActive });
|
|
364
360
|
if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {
|
|
365
361
|
await this.setCustomFields({
|
|
366
362
|
entityId: opts.entityId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/data/engine.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityData, EntityName, FilterQuery, RequiredEntityData } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { type Kysely, sql } from 'kysely'\nimport { encryptCustomEntityRecordDocument, setRecordCustomFields } from '@open-mercato/core/modules/entities/lib/helpers'\nimport { validateCustomFieldValuesServer } from '@open-mercato/core/modules/entities/lib/validation'\nimport { sanitizeCustomFieldHtmlRichTextValuesServer } from '@open-mercato/core/modules/entities/lib/htmlRichTextSanitizer'\nimport type { EventBus } from '@open-mercato/events/types'\nimport {\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n type CrudEventAction,\n type CrudEventsConfig,\n type CrudIndexerConfig,\n type CrudEntityIdentifiers,\n} from '../crud/types'\nimport type { BulkImportSuppression } from '../commands/types'\nimport { conflict, CrudHttpError, isUniqueViolation, notFound } from '../crud/errors'\nimport { withAdvisoryXactLock } from '../db/advisoryLock'\nimport { resolveRegisteredEntityTableName } from '../query/engine'\nimport { getEntityIds } from '../encryption/entityIds'\nimport { normalizeCustomFieldValues } from '../custom-fields/normalize'\nimport { parseBooleanToken } from '../boolean'\nimport { isReadProjectionAlwaysConsistent } from './consistency'\nimport { isEventDeclared } from '../../modules/events'\nimport { createLogger } from '../logger'\nimport { createBoundedTtlMemo } from '../query/bounded-ttl-memo'\nimport type { TenantDataEncryptionService } from '../encryption/tenantDataEncryptionService'\n\nconst logger = createLogger('shared').child({ component: 'data-engine' })\n\nconst undeclaredEventWarned = new Set<string>()\n\nfunction warnIfUndeclaredEvent(eventName: string, context: string): void {\n if (isEventDeclared(eventName)) return\n if (undeclaredEventWarned.has(eventName)) return\n undeclaredEventWarned.add(eventName)\n logger.warn('Emitting undeclared event \u2014 declare it in the owning module events.ts (createModuleEvents) so the event registry stays authoritative', { context, eventName })\n}\n\n/** Internal: clear the undeclared-event warning cache. Exposed for tests. */\nexport function __resetUndeclaredEventWarningsForTests(): void {\n undeclaredEventWarned.clear()\n}\n\n/** Only `true` is cached: a cached `false` would keep this failing after a migration creates the table. */\nconst tableExistsCache = createBoundedTtlMemo<true>({\n ttlEnv: 'OM_DATA_ENGINE_TABLE_EXISTS_CACHE_MS',\n defaultTtlMs: 3_600_000,\n defaultMaxEntries: 1_000,\n})\n\n/** Test-only: the module-scoped memo would otherwise leak state across specs. */\nexport function clearDataEngineTableExistsCache(): void {\n tableExistsCache.clear()\n}\n\nconst COVERAGE_REFRESH_INTERVAL_MS = 5 * 60 * 1000\nconst coverageRefreshTracker = new Map<string, number>()\n\nfunction shouldTriggerCoverageRefresh(entityType: string | undefined, tenantId: string | null): boolean {\n if (!entityType) return false\n const key = `${entityType}|${tenantId ?? '__null__'}`\n const now = Date.now()\n const last = coverageRefreshTracker.get(key) ?? 0\n if (now - last < COVERAGE_REFRESH_INTERVAL_MS) return false\n coverageRefreshTracker.set(key, now)\n return true\n}\n\ntype CustomEntityValues = Record<string, unknown>\n\ntype CustomEntityStorageDatabase = {\n custom_entities_storage: {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n doc: CustomEntityValues\n updated_at: Date\n created_at: Date\n deleted_at: Date | null\n }\n}\n\ntype QueuedCrudSideEffect = {\n action: CrudEventAction\n entity: unknown\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n events?: CrudEventsConfig<unknown>\n indexer?: CrudIndexerConfig<unknown>\n}\n\n/**\n * A `makeCrudRoute` route-level `indexer:` declaration, handed to the data engine for the\n * duration of one command-bus write. Command handlers own the side-effect mark on the\n * `actions.*` path, and most of them mark `events:` only \u2014 without this the route's\n * declaration would reach no code at all. `entityClass` scopes the default to the route's\n * own ORM entity so a handler that also marks a sibling entity in the same request (a tag\n * assignment alongside a tag, say) is never indexed under the route's `entityType`.\n */\nexport type DefaultCrudIndexerConfig = {\n indexer: CrudIndexerConfig<unknown>\n entityClass: abstract new (...args: never[]) => object\n}\n\nexport interface DataEngine {\n setCustomFields(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: Record<string, string | number | boolean | null | undefined | Array<string | number | boolean | null | undefined>>\n notify?: boolean // default true -> emit '<module>.<entity>.updated'\n // Forwarded to `setRecordCustomFields` \u2014 see its doc for when a caller must pass\n // true (a recordId that is not unique across organizations for this entityId).\n pinOrganizationId?: boolean\n }): Promise<void>\n\n // Storage for user-defined entities (doc-based)\n createCustomEntityRecord(opts: {\n entityId: string // '<module>:<entity>'\n recordId?: string // optional; auto-generate if not provided\n createOnly?: boolean\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n }): Promise<{ id: string }>\n\n updateCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n requireActive?: boolean\n }): Promise<void>\n\n deleteCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n soft?: boolean // default true: sets deleted_at\n notify?: boolean // keep event emitting as it is (no extra events here)\n }): Promise<void>\n\n // Generic ORM-backed entity operations used by CrudFactory\n createOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n data: EntityData<T>\n }): Promise<T>\n\n updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null>\n\n deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null>\n\n emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n /** Bulk-import deferral: skip the domain event and/or inline reindex for this emit. */\n suppress?: BulkImportSuppression\n }): Promise<void>\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void\n\n /**\n * Drain queued side effects. When `suppress` is passed (a bulk-import backfill), the\n * flagged per-record events / reindex are skipped for every drained entry; the caller\n * is responsible for rebuilding the `query_index` afterwards.\n */\n flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void>\n\n /**\n * Declare the indexer a CRUD route configured, for marks made during one command-bus\n * write that do not carry an indexer of their own. Pass `null` to clear it. Optional so\n * third-party `DataEngine` implementations stay valid; callers invoke it with `?.`.\n */\n setDefaultIndexerConfig?(config: DefaultCrudIndexerConfig | null): void\n\n /**\n * Whether any side effect drained since the current default was declared carried an\n * indexer for that default's entity class \u2014 false means the declared query-index\n * obligation was discharged by nobody. Optional for the same reason as the setter.\n */\n hasIndexedDefaultEntityClass?(): boolean\n}\n\nexport const SYSTEM_ENTITY_RECORDS_BLOCKED_CODE = 'system_entity_records_blocked'\n\n/**\n * A system entity for doc-storage purposes is an id that modules declare in the\n * generated entity-id registry AND that resolves to a registered ORM table. Both\n * conditions matter: `resolveRegisteredEntityTableName` matches class-name candidates\n * from the entity segment alone, so a runtime-registered custom entity whose name\n * happens to collide with some ORM class (e.g. `user:todo` vs the example module's\n * `Todo`) must never be classified as system. When the registry is not populated\n * (exotic bootstraps, unit harnesses) the check conservatively falls back to the\n * ORM-table match alone so the #2939 protection never switches off.\n */\nexport function isOrmBackedSystemEntityId(em: EntityManager, entityId: string): boolean {\n const registry = getEntityIds(false)\n const moduleIds = Object.values(registry).flatMap((moduleEntities) => Object.values(moduleEntities ?? {}))\n if (moduleIds.length > 0 && !moduleIds.includes(entityId)) return false\n return resolveRegisteredEntityTableName(em, entityId) !== null\n}\n\n/**\n * Doc storage (`custom_entities_storage`) is for custom entities only. A system\n * entity's records live in its own module tables/APIs \u2014 writing doc rows for it\n * poisons read-path classification (#2939) and must be rejected at the deepest\n * seam so no caller (API, AI tool, workflow) can do it.\n */\nexport function assertCustomEntityStorageEntityId(em: EntityManager, entityId: string): void {\n if (isOrmBackedSystemEntityId(em, entityId)) {\n throw new CrudHttpError(400, {\n error: 'Records are available for custom entities only',\n code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE,\n entityId,\n })\n }\n}\n\nexport class DefaultDataEngine implements DataEngine {\n private pendingSideEffects = new Map<string, QueuedCrudSideEffect>()\n private defaultIndexer: DefaultCrudIndexerConfig | null = null\n private indexedDefaultEntityClass = false\n constructor(private em: EntityManager, private container: AwilixContainer) {}\n\n /**\n * Per-command state, deliberately held on the engine instance rather than threaded through\n * `CommandRuntimeContext` the way the bulk-import flags are. That is sound only because\n * `createRequestContainer()` registers `dataEngine` per request (`lib/di/container.ts`), so\n * one engine instance never spans two requests, and no `makeCrudRoute` verb runs two commands\n * concurrently against it. An application that re-registers `dataEngine` as a transient would\n * break both assumptions: the command would mark on a different instance than the route\n * declared on, so nothing is indexed and every write logs the undischarged-declaration warning.\n */\n setDefaultIndexerConfig(config: DefaultCrudIndexerConfig | null): void {\n this.defaultIndexer = config\n this.indexedDefaultEntityClass = false\n }\n\n hasIndexedDefaultEntityClass(): boolean {\n return this.indexedDefaultEntityClass\n }\n\n private matchesDefaultEntityClass(entity: unknown): boolean {\n const declared = this.defaultIndexer?.entityClass\n // `OrmEntityConfig.entity` is `any` and this repository treats `EntitySchema` instances as a\n // first-class entity shape (`lib/bootstrap/types.ts`). An `EntitySchema` is an object rather\n // than a constructor, so `instanceof` against it throws \u2014 and it would throw inside\n // `markOrmEntityChange`, outside the best-effort try/catch that guards the flush, turning\n // every write on such a route into a 500.\n if (typeof declared !== 'function') return false\n return entity instanceof declared\n }\n\n private resolveDefaultIndexer(entity: unknown): CrudIndexerConfig<unknown> | undefined {\n return this.matchesDefaultEntityClass(entity) ? this.defaultIndexer?.indexer : undefined\n }\n\n async setCustomFields(opts: Parameters<DataEngine['setCustomFields']>[0]): Promise<void> {\n const { entityId, recordId, organizationId = null, tenantId = null, values } = opts\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values,\n })\n await this.validateCustomFieldValues(entityId, organizationId, tenantId, sanitizedValues as Record<string, unknown>)\n let encryptionService: any = null\n try {\n encryptionService = this.container.resolve('tenantEncryptionService') as any\n } catch {\n encryptionService = null\n }\n await setRecordCustomFields(this.em, {\n entityId,\n recordId,\n organizationId,\n tenantId,\n values: sanitizedValues,\n encryptionService,\n pinOrganizationId: opts.pinOrganizationId === true,\n })\n if (opts.notify !== false) {\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (bus) {\n const [mod, ent] = (entityId || '').split(':')\n if (mod && ent) {\n const eventName = `${mod}.${ent}.updated`\n warnIfUndeclaredEvent(eventName, 'setCustomFields')\n try {\n await bus.emitEvent(eventName, { id: recordId, organizationId, tenantId }, {\n persistent: true,\n tenantId,\n organizationId,\n emitterModuleId: mod,\n })\n } catch {\n // non-blocking\n }\n }\n }\n }\n }\n\n private normalizeDocValues(values: CustomEntityValues): CustomEntityValues {\n const out: CustomEntityValues = {}\n for (const [k, v] of Object.entries(values || {})) {\n // Never allow callers to override reserved identifiers in the doc\n if (k === 'id' || k === 'entity_id' || k === 'entityId') continue\n // Accept both 'cf_<key>' and 'cf:<key>' inputs and normalize to 'cf:<key>'\n if (k.startsWith('cf_')) out[`cf:${k.slice(3)}`] = v\n else out[k] = v\n }\n return out\n }\n\n private backcompatEavEnabled(): boolean {\n try {\n return parseBooleanToken(process.env.ENTITIES_BACKCOMPAT_EAV_FOR_CUSTOM ?? '') === true\n } catch { return false }\n }\n\n private resolveCustomEntityEncryptionService(): TenantDataEncryptionService | null {\n try {\n return this.container.resolve<TenantDataEncryptionService>('tenantEncryptionService')\n } catch {\n return null\n }\n }\n\n private getKysely(): Kysely<any> {\n return this.em.getKysely<any>()\n }\n\n private async ensureStorageTableExists(): Promise<void> {\n const cacheKey = 'custom_entities_storage'\n if (tableExistsCache.get(cacheKey)) return\n const db = this.getKysely()\n const exists = await db\n .selectFrom('information_schema.tables' as any)\n .select(sql`1`.as('present'))\n .where('table_name' as any, '=', 'custom_entities_storage')\n .executeTakeFirst()\n if (!exists) {\n throw new Error('custom_entities_storage table is missing. Run migrations (yarn db:migrate).')\n }\n tableExistsCache.set(cacheKey, true)\n }\n\n private normalizeValuesForValidation(values: Record<string, unknown> | undefined | null): Record<string, unknown> {\n if (!values) return {}\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n if (key.startsWith('cf_') || key.startsWith('cf:')) {\n const normalized = key.slice(3)\n if (normalized) out[normalized] = value\n continue\n }\n out[key] = value\n }\n return out\n }\n\n private async validateCustomFieldValues(\n entityId: string,\n organizationId: string | null,\n tenantId: string | null,\n values: Record<string, unknown> | undefined | null,\n ): Promise<void> {\n const prepared = this.normalizeValuesForValidation(values)\n if (!entityId || Object.keys(prepared).length === 0) return\n const result = await validateCustomFieldValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values: prepared,\n })\n if (!result.ok) {\n throw new CrudHttpError(400, { error: 'Validation failed', fields: result.fieldErrors })\n }\n }\n\n async createCustomEntityRecord(opts: Parameters<DataEngine['createCustomEntityRecord']>[0]): Promise<{ id: string }> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n await this.ensureStorageTableExists()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const rawId = String(opts.recordId ?? '').trim()\n const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(rawId)\n const sentinel = rawId.toLowerCase()\n const shouldGenerate = !rawId || !isUuid || sentinel === 'create' || sentinel === 'new' || sentinel === 'null' || sentinel === 'undefined'\n const id = shouldGenerate ? ((): string => {\n const g = globalThis as { crypto?: { randomUUID?: () => string } }\n if (g.crypto?.randomUUID) return g.crypto.randomUUID()\n // Fallback UUIDv4 generator\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0\n const v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16)\n })\n })() : rawId\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const doc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { id, ...this.normalizeDocValues(sanitizedValues || {}) },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n\n const now = sql<Date>`now()`\n const payload = {\n entity_type: opts.entityId,\n entity_id: id,\n organization_id: orgId,\n tenant_id: tenantId,\n doc: sql<CustomEntityValues>`${JSON.stringify(doc)}::jsonb`,\n updated_at: now,\n created_at: now,\n deleted_at: null,\n }\n\n if (opts.createOnly) {\n const duplicateError = () => {\n const error = conflict('[internal] Custom entity record already exists')\n error.body.code = 'custom_entity_record_exists'\n return error\n }\n const lockKey = `custom_entity_create:${JSON.stringify([tenantId, orgId, opts.entityId, id.toLowerCase()])}`\n await withAdvisoryXactLock(this.em, lockKey, async (txEm) => {\n const storage = txEm.getKysely<CustomEntityStorageDatabase>()\n const existing = await storage\n .selectFrom('custom_entities_storage')\n .select('entity_id')\n .where('entity_type', '=', opts.entityId)\n .where(sql<string>`lower(entity_id)`, '=', id.toLowerCase())\n .where('organization_id', orgId === null ? 'is' : '=', orgId)\n .where('tenant_id', tenantId === null ? 'is' : '=', tenantId)\n .executeTakeFirst()\n if (existing) throw duplicateError()\n try {\n await storage.insertInto('custom_entities_storage').values(payload).execute()\n } catch (error) {\n if (isUniqueViolation(error, 'custom_entities_storage_unique_idx')) throw duplicateError()\n throw error\n }\n })\n } else {\n try {\n await db\n .insertInto('custom_entities_storage' as any)\n .values(payload as any)\n .onConflict((oc) => oc\n .columns(['entity_type', 'entity_id', 'organization_id'])\n .doUpdateSet({\n doc: sql`${JSON.stringify(doc)}::jsonb`,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any))\n .execute()\n } catch {\n // Fallback for global scope uniqueness\n const updated = await db\n .updateTable('custom_entities_storage' as any)\n .set({\n doc: sql`${JSON.stringify(doc)}::jsonb`,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any)\n .where('entity_type' as any, '=', opts.entityId)\n .where('entity_id' as any, '=', id)\n .where('organization_id' as any, orgId === null ? 'is' : '=', orgId as any)\n .where('tenant_id' as any, tenantId === null ? 'is' : '=', tenantId as any)\n .executeTakeFirst()\n if (!updated || Number(updated.numUpdatedRows ?? 0) === 0) {\n await db.insertInto('custom_entities_storage' as any).values(payload as any).execute()\n }\n }\n }\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n\n return { id }\n }\n\n async updateCustomEntityRecord(opts: Parameters<DataEngine['updateCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const requireActive = opts.requireActive === true\n\n // Merge doc shallowly: load existing doc and overlay\n await this.ensureStorageTableExists()\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n if (requireActive) chain = chain.where('deleted_at', 'is', null)\n return chain\n }\n const row = await applyScope(\n db.selectFrom('custom_entities_storage' as any).select(['doc' as any])\n ).executeTakeFirst()\n if (requireActive && !row) throw notFound()\n const prevDoc: Record<string, unknown> = (row as any)?.doc || { id }\n const nextDoc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { ...prevDoc, ...this.normalizeDocValues(sanitizedValues || {}), id },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n try {\n const updated = await applyScope(\n db.updateTable('custom_entities_storage' as any).set({\n doc: sql`${JSON.stringify(nextDoc)}::jsonb`,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any) as any\n ).executeTakeFirst()\n if (!updated || Number((updated as any).numUpdatedRows ?? 0) === 0) {\n if (requireActive) throw notFound()\n await db.insertInto('custom_entities_storage' as any).values({\n entity_type: opts.entityId,\n entity_id: id,\n organization_id: orgId,\n tenant_id: tenantId,\n doc: sql`${JSON.stringify(nextDoc)}::jsonb`,\n created_at: sql`now()`,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any).execute()\n }\n } catch (err) {\n throw err\n }\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n }\n\n async deleteCustomEntityRecord(opts: Parameters<DataEngine['deleteCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const soft = opts.soft !== false\n\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n return chain\n }\n\n if (soft) {\n await applyScope(\n db.updateTable('custom_entities_storage' as any).set({\n deleted_at: sql`now()`,\n updated_at: sql`now()`,\n } as any) as any\n ).execute()\n } else {\n await applyScope(db.deleteFrom('custom_entities_storage' as any) as any).execute()\n }\n\n // Soft-delete EAV values to preserve current behavior\n try {\n const { CustomFieldValue } = await import('@open-mercato/core/modules/entities/data/entities')\n const values = await this.em.find(CustomFieldValue, {\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: opts.tenantId ?? null,\n })\n const now = new Date()\n const mutated = values.filter((record) => {\n if (record.deletedAt) return false\n record.deletedAt = now\n return true\n })\n if (mutated.length) {\n for (const record of values) this.em.persist(record)\n await this.em.flush()\n }\n } catch { /* non-blocking */ }\n }\n\n async createOrmEntity<T extends object>(opts: { entity: EntityName<T>; data: EntityData<T> }): Promise<T> {\n const entity = this.em.create(\n opts.entity as EntityName<T>,\n opts.data as unknown as RequiredEntityData<T>\n )\n await this.em.persist(entity).flush()\n return entity\n }\n\n async updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null> {\n const current = await this.em.findOne(opts.entity as EntityName<T>, opts.where as FilterQuery<NoInfer<T>>)\n if (!current) return null\n await opts.apply(current)\n await this.em.persist(current).flush()\n return current\n }\n\n async deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null> {\n const current = await this.em.findOne(opts.entity as EntityName<T>, opts.where as FilterQuery<NoInfer<T>>)\n if (!current) return null\n if (opts.soft !== false) {\n const field = opts.softDeleteField || ('deletedAt' as keyof T & string)\n if (typeof current === 'object' && current !== null) {\n ;(current as Record<string, unknown>)[field] = new Date()\n await this.em.persist(current).flush()\n }\n } else {\n await this.em.remove(current).flush()\n }\n return current\n }\n\n async emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n suppress?: BulkImportSuppression\n }): Promise<void> {\n const { action, entity, events, indexer, identifiers, syncOrigin, suppress } = opts\n // Bulk-import deferral: an entry may suppress its domain event and/or inline reindex. When both\n // the config is absent AND (for the present one) suppressed, there is nothing left to do.\n const emitEvents = !!events && !suppress?.skipEvents\n const runIndexer = !!indexer && !suppress?.skipReindex\n if (!emitEvents && !runIndexer) return\n if (!identifiers?.id) return\n\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (!bus) return\n\n const ctx = {\n action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n\n if (events && !suppress?.skipEvents) {\n const eventName = `${events.module}.${events.entity}.${action}`\n warnIfUndeclaredEvent(eventName, 'emitOrmEntityEvent')\n const builtPayload = events.buildPayload\n ? events.buildPayload(ctx)\n : {\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }\n // A configured indexer means this data-engine call owns the query-index\n // decision, including an explicit skipReindex suppression. Mark object\n // payloads so the legacy domain-event bridge does not enqueue the same\n // record a second time. Keep the marker non-enumerable so client broadcasts\n // and persisted domain payloads retain their existing public shape.\n // Primitive custom payloads cannot be bridged in any case because they do\n // not expose the record id.\n const payload = indexer && builtPayload && typeof builtPayload === 'object' && !Array.isArray(builtPayload)\n ? Object.defineProperty(\n { ...(builtPayload as Record<string, unknown>) },\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n { value: true, enumerable: false },\n )\n : builtPayload\n try {\n await bus.emitEvent(eventName, payload, {\n persistent: !!events.persistent,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: ctx.identifiers.organizationId ?? null,\n emitterModuleId: events.module,\n })\n } catch {\n // non-blocking\n }\n }\n\n if (indexer && !suppress?.skipReindex) {\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n const resolveCoverageBaseDelta = (): number | undefined => {\n if (action === 'created') return 1\n if (action === 'deleted') return -1\n return undefined\n }\n const coverageBaseDelta = resolveCoverageBaseDelta()\n\n if (action === 'deleted') {\n const payload = indexer.buildDeletePayload\n ? indexer.buildDeletePayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the index update so query-index reads (the `customValues`/scalar\n // projection that list endpoints serve) are consistent the moment the write\n // returns. The subscriber removes the projection row + tokens synchronously and\n // defers the coverage recompute + fulltext delete, so this stays bounded.\n // Errors are logged, not thrown \u2014 index drift never fails the originating write.\n // Always-consistent mode rethrows so drift is loud and retryable.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.delete_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.delete_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.delete_one emit failed', { err })\n })\n }\n } else {\n const payload = indexer.buildUpsertPayload\n ? indexer.buildUpsertPayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the projection upsert so list reads observe the new doc immediately\n // (see delete_one above). The subscriber updates `entity_indexes` synchronously\n // and defers the heavy token-reindex pipeline (build doc + encrypt + decrypt +\n // tokenize + DELETE + chunked INSERT) so write latency stays bounded.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.upsert_one emit failed', { err })\n })\n }\n }\n\n if (alwaysConsistent || shouldTriggerCoverageRefresh(indexer.entityType, ctx.identifiers.tenantId ?? null)) {\n const coveragePayload = {\n entityType: indexer.entityType,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: null,\n delayMs: 0,\n }\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.coverage.refresh', coveragePayload, { rethrowHandlerErrors: true })\n } else {\n void bus.emitEvent('query_index.coverage.refresh', coveragePayload).catch(() => undefined)\n }\n }\n }\n }\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void {\n const { entity, identifiers } = opts\n if (!entity) return\n if (!identifiers?.id) return\n // A command handler that marks `events:` only still discharges the route's declared\n // query-index obligation \u2014 the route hands its `indexer:` down as the default so the\n // handler's own entity and identifiers (the accurate ones) drive the projection write.\n const indexer = opts.indexer ?? this.resolveDefaultIndexer(entity)\n const key = this.buildSideEffectKey(opts.action, identifiers)\n const existing = this.pendingSideEffects.get(key)\n if (existing) {\n existing.entity = entity\n existing.identifiers = {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n }\n existing.syncOrigin = opts.syncOrigin ?? null\n existing.actorUserId = opts.actorUserId ?? null\n if (opts.events) existing.events = opts.events as CrudEventsConfig<unknown>\n // Explicit always wins, on the merge branch too: a second `events:`-only mark on the same\n // key must not let the route default overwrite the `indexer:` an earlier mark installed,\n // which would silently drop that handler's own `buildUpsertPayload`.\n if (opts.indexer) existing.indexer = opts.indexer as CrudIndexerConfig<unknown>\n else if (!existing.indexer && indexer) existing.indexer = indexer\n this.pendingSideEffects.set(key, existing)\n return\n }\n const entry: QueuedCrudSideEffect = {\n action: opts.action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: opts.syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n if (opts.events) entry.events = opts.events as CrudEventsConfig<unknown>\n if (indexer) entry.indexer = indexer\n this.pendingSideEffects.set(key, entry)\n }\n\n async flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void> {\n if (!this.pendingSideEffects.size) return\n const entries = Array.from(this.pendingSideEffects.values())\n this.pendingSideEffects.clear()\n for (const entry of entries) {\n if (entry.indexer && !suppress?.skipReindex && this.matchesDefaultEntityClass(entry.entity)) {\n this.indexedDefaultEntityClass = true\n }\n try {\n await this.emitOrmEntityEvent({\n action: entry.action,\n entity: entry.entity,\n identifiers: entry.identifiers,\n syncOrigin: entry.syncOrigin ?? null,\n actorUserId: entry.actorUserId ?? null,\n events: entry.events as CrudEventsConfig<unknown>,\n indexer: entry.indexer as CrudIndexerConfig<unknown>,\n suppress,\n })\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort; continue with remaining side effects\n }\n }\n }\n\n private buildSideEffectKey(action: CrudEventAction, identifiers: CrudEntityIdentifiers): string {\n const id = identifiers.id ?? ''\n const org = identifiers.organizationId ?? ''\n const tenant = identifiers.tenantId ?? ''\n return [action, id, org, tenant].join('|')\n }\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAsB,WAAW;AACjC,SAAS,mCAAmC,6BAA6B;AACzE,SAAS,uCAAuC;AAChD,SAAS,mDAAmD;AAE5D;AAAA,EACE;AAAA,OAKK;AAEP,SAAS,UAAU,eAAe,mBAAmB,gBAAgB;AACrE,SAAS,4BAA4B;AACrC,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAClC,SAAS,wCAAwC;AACjD,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAGrC,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAExE,MAAM,wBAAwB,oBAAI,IAAY;AAE9C,SAAS,sBAAsB,WAAmB,SAAuB;AACvE,MAAI,gBAAgB,SAAS,EAAG;AAChC,MAAI,sBAAsB,IAAI,SAAS,EAAG;AAC1C,wBAAsB,IAAI,SAAS;AACnC,SAAO,KAAK,6IAAwI,EAAE,SAAS,UAAU,CAAC;AAC5K;AAGO,SAAS,yCAA+C;AAC7D,wBAAsB,MAAM;AAC9B;AAGA,MAAM,mBAAmB,qBAA2B;AAAA,EAClD,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,mBAAmB;AACrB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mB,QAAyB,aAA4C;AAC9F,UAAM,KAAK,YAAY,MAAM;AAC7B,UAAM,MAAM,YAAY,kBAAkB;AAC1C,UAAM,SAAS,YAAY,YAAY;AACvC,WAAO,CAAC,QAAQ,IAAI,KAAK,MAAM,EAAE,KAAK,GAAG;AAAA,EAC3C;AACF;",
|
|
4
|
+
"sourcesContent": ["import type { EntityData, EntityName, FilterQuery, RequiredEntityData } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { type Kysely, sql } from 'kysely'\nimport { encryptCustomEntityRecordDocument, setRecordCustomFields } from '@open-mercato/core/modules/entities/lib/helpers'\nimport { validateCustomFieldValuesServer } from '@open-mercato/core/modules/entities/lib/validation'\nimport { sanitizeCustomFieldHtmlRichTextValuesServer } from '@open-mercato/core/modules/entities/lib/htmlRichTextSanitizer'\nimport type { EventBus } from '@open-mercato/events/types'\nimport {\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n type CrudEventAction,\n type CrudEventsConfig,\n type CrudIndexerConfig,\n type CrudEntityIdentifiers,\n} from '../crud/types'\nimport type { BulkImportSuppression } from '../commands/types'\nimport { conflict, CrudHttpError, isUniqueViolation, notFound } from '../crud/errors'\nimport { AdvisoryLockUnavailableError, withAdvisoryXactLock } from '../db/advisoryLock'\nimport { resolveRegisteredEntityTableName } from '../query/engine'\nimport { getEntityIds } from '../encryption/entityIds'\nimport { normalizeCustomFieldValues } from '../custom-fields/normalize'\nimport { parseBooleanToken } from '../boolean'\nimport { isReadProjectionAlwaysConsistent } from './consistency'\nimport { isEventDeclared } from '../../modules/events'\nimport { createLogger } from '../logger'\nimport { createBoundedTtlMemo } from '../query/bounded-ttl-memo'\nimport type { TenantDataEncryptionService } from '../encryption/tenantDataEncryptionService'\n\nconst logger = createLogger('shared').child({ component: 'data-engine' })\n\nconst undeclaredEventWarned = new Set<string>()\n\nfunction warnIfUndeclaredEvent(eventName: string, context: string): void {\n if (isEventDeclared(eventName)) return\n if (undeclaredEventWarned.has(eventName)) return\n undeclaredEventWarned.add(eventName)\n logger.warn('Emitting undeclared event \u2014 declare it in the owning module events.ts (createModuleEvents) so the event registry stays authoritative', { context, eventName })\n}\n\n/** Internal: clear the undeclared-event warning cache. Exposed for tests. */\nexport function __resetUndeclaredEventWarningsForTests(): void {\n undeclaredEventWarned.clear()\n}\n\n/** Only `true` is cached: a cached `false` would keep this failing after a migration creates the table. */\nconst tableExistsCache = createBoundedTtlMemo<true>({\n ttlEnv: 'OM_DATA_ENGINE_TABLE_EXISTS_CACHE_MS',\n defaultTtlMs: 3_600_000,\n defaultMaxEntries: 1_000,\n})\n\n/** Test-only: the module-scoped memo would otherwise leak state across specs. */\nexport function clearDataEngineTableExistsCache(): void {\n tableExistsCache.clear()\n}\n\nconst COVERAGE_REFRESH_INTERVAL_MS = 5 * 60 * 1000\nconst coverageRefreshTracker = new Map<string, number>()\n\nfunction shouldTriggerCoverageRefresh(entityType: string | undefined, tenantId: string | null): boolean {\n if (!entityType) return false\n const key = `${entityType}|${tenantId ?? '__null__'}`\n const now = Date.now()\n const last = coverageRefreshTracker.get(key) ?? 0\n if (now - last < COVERAGE_REFRESH_INTERVAL_MS) return false\n coverageRefreshTracker.set(key, now)\n return true\n}\n\ntype CustomEntityValues = Record<string, unknown>\n\ntype CustomEntityStorageDatabase = {\n custom_entities_storage: {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n doc: CustomEntityValues\n updated_at: Date\n created_at: Date\n deleted_at: Date | null\n }\n}\n\ntype QueuedCrudSideEffect = {\n action: CrudEventAction\n entity: unknown\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n events?: CrudEventsConfig<unknown>\n indexer?: CrudIndexerConfig<unknown>\n}\n\n/**\n * A `makeCrudRoute` route-level `indexer:` declaration, handed to the data engine for the\n * duration of one command-bus write. Command handlers own the side-effect mark on the\n * `actions.*` path, and most of them mark `events:` only \u2014 without this the route's\n * declaration would reach no code at all. `entityClass` scopes the default to the route's\n * own ORM entity so a handler that also marks a sibling entity in the same request (a tag\n * assignment alongside a tag, say) is never indexed under the route's `entityType`.\n */\nexport type DefaultCrudIndexerConfig = {\n indexer: CrudIndexerConfig<unknown>\n entityClass: abstract new (...args: never[]) => object\n}\n\nexport interface DataEngine {\n setCustomFields(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: Record<string, string | number | boolean | null | undefined | Array<string | number | boolean | null | undefined>>\n /**\n * Default true: emits the entity-keyed custom-field change signal `<module>.<entity>.updated`,\n * derived from `entityId` (e.g. `catalog:catalog_product` \u2192 `catalog.catalog_product.updated`).\n * It is not a module domain event \u2014 the query_index bridge subscribes to the same derivation for\n * every entity carrying custom fields, including runtime custom entities \u2014 so it is deliberately\n * not checked against the `events.ts` registry.\n */\n notify?: boolean\n // Forwarded to `setRecordCustomFields` \u2014 see its doc for when a caller must pass\n // true (a recordId that is not unique across organizations for this entityId).\n pinOrganizationId?: boolean\n }): Promise<void>\n\n // Storage for user-defined entities (doc-based)\n createCustomEntityRecord(opts: {\n entityId: string // '<module>:<entity>'\n recordId?: string // optional; auto-generate if not provided\n createOnly?: boolean\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n }): Promise<{ id: string }>\n\n updateCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n values: CustomEntityValues\n notify?: boolean // keep event emitting as it is via setCustomFields (updated)\n requireActive?: boolean\n }): Promise<void>\n\n deleteCustomEntityRecord(opts: {\n entityId: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n soft?: boolean // default true: sets deleted_at\n notify?: boolean // keep event emitting as it is (no extra events here)\n }): Promise<void>\n\n // Generic ORM-backed entity operations used by CrudFactory\n createOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n data: EntityData<T>\n }): Promise<T>\n\n updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null>\n\n deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null>\n\n emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n /** Bulk-import deferral: skip the domain event and/or inline reindex for this emit. */\n suppress?: BulkImportSuppression\n }): Promise<void>\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void\n\n /**\n * Drain queued side effects. When `suppress` is passed (a bulk-import backfill), the\n * flagged per-record events / reindex are skipped for every drained entry; the caller\n * is responsible for rebuilding the `query_index` afterwards.\n */\n flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void>\n\n /**\n * Declare the indexer a CRUD route configured, for marks made during one command-bus\n * write that do not carry an indexer of their own. Pass `null` to clear it. Optional so\n * third-party `DataEngine` implementations stay valid; callers invoke it with `?.`.\n */\n setDefaultIndexerConfig?(config: DefaultCrudIndexerConfig | null): void\n\n /**\n * Whether any side effect drained since the current default was declared carried an\n * indexer for that default's entity class \u2014 false means the declared query-index\n * obligation was discharged by nobody. Optional for the same reason as the setter.\n */\n hasIndexedDefaultEntityClass?(): boolean\n}\n\nexport const SYSTEM_ENTITY_RECORDS_BLOCKED_CODE = 'system_entity_records_blocked'\n\n/**\n * A system entity for doc-storage purposes is an id that modules declare in the\n * generated entity-id registry AND that resolves to a registered ORM table. Both\n * conditions matter: `resolveRegisteredEntityTableName` matches class-name candidates\n * from the entity segment alone, so a runtime-registered custom entity whose name\n * happens to collide with some ORM class (e.g. `user:todo` vs the example module's\n * `Todo`) must never be classified as system. When the registry is not populated\n * (exotic bootstraps, unit harnesses) the check conservatively falls back to the\n * ORM-table match alone so the #2939 protection never switches off.\n */\nexport function isOrmBackedSystemEntityId(em: EntityManager, entityId: string): boolean {\n const registry = getEntityIds(false)\n const moduleIds = Object.values(registry).flatMap((moduleEntities) => Object.values(moduleEntities ?? {}))\n if (moduleIds.length > 0 && !moduleIds.includes(entityId)) return false\n return resolveRegisteredEntityTableName(em, entityId) !== null\n}\n\n/**\n * Doc storage (`custom_entities_storage`) is for custom entities only. A system\n * entity's records live in its own module tables/APIs \u2014 writing doc rows for it\n * poisons read-path classification (#2939) and must be rejected at the deepest\n * seam so no caller (API, AI tool, workflow) can do it.\n */\nexport function assertCustomEntityStorageEntityId(em: EntityManager, entityId: string): void {\n if (isOrmBackedSystemEntityId(em, entityId)) {\n throw new CrudHttpError(400, {\n error: 'Records are available for custom entities only',\n code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE,\n entityId,\n })\n }\n}\n\nexport class DefaultDataEngine implements DataEngine {\n private pendingSideEffects = new Map<string, QueuedCrudSideEffect>()\n private defaultIndexer: DefaultCrudIndexerConfig | null = null\n private indexedDefaultEntityClass = false\n constructor(private em: EntityManager, private container: AwilixContainer) {}\n\n /**\n * Per-command state, deliberately held on the engine instance rather than threaded through\n * `CommandRuntimeContext` the way the bulk-import flags are. That is sound only because\n * `createRequestContainer()` registers `dataEngine` per request (`lib/di/container.ts`), so\n * one engine instance never spans two requests, and no `makeCrudRoute` verb runs two commands\n * concurrently against it. An application that re-registers `dataEngine` as a transient would\n * break both assumptions: the command would mark on a different instance than the route\n * declared on, so nothing is indexed and every write logs the undischarged-declaration warning.\n */\n setDefaultIndexerConfig(config: DefaultCrudIndexerConfig | null): void {\n this.defaultIndexer = config\n this.indexedDefaultEntityClass = false\n }\n\n hasIndexedDefaultEntityClass(): boolean {\n return this.indexedDefaultEntityClass\n }\n\n private matchesDefaultEntityClass(entity: unknown): boolean {\n const declared = this.defaultIndexer?.entityClass\n // `OrmEntityConfig.entity` is `any` and this repository treats `EntitySchema` instances as a\n // first-class entity shape (`lib/bootstrap/types.ts`). An `EntitySchema` is an object rather\n // than a constructor, so `instanceof` against it throws \u2014 and it would throw inside\n // `markOrmEntityChange`, outside the best-effort try/catch that guards the flush, turning\n // every write on such a route into a 500.\n if (typeof declared !== 'function') return false\n return entity instanceof declared\n }\n\n private resolveDefaultIndexer(entity: unknown): CrudIndexerConfig<unknown> | undefined {\n return this.matchesDefaultEntityClass(entity) ? this.defaultIndexer?.indexer : undefined\n }\n\n async setCustomFields(opts: Parameters<DataEngine['setCustomFields']>[0]): Promise<void> {\n const { entityId, recordId, organizationId = null, tenantId = null, values } = opts\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values,\n })\n await this.validateCustomFieldValues(entityId, organizationId, tenantId, sanitizedValues as Record<string, unknown>)\n let encryptionService: any = null\n try {\n encryptionService = this.container.resolve('tenantEncryptionService') as any\n } catch {\n encryptionService = null\n }\n await setRecordCustomFields(this.em, {\n entityId,\n recordId,\n organizationId,\n tenantId,\n values: sanitizedValues,\n encryptionService,\n pinOrganizationId: opts.pinOrganizationId === true,\n })\n if (opts.notify !== false) {\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (bus) {\n const [mod, ent] = (entityId || '').split(':')\n if (mod && ent) {\n const eventName = `${mod}.${ent}.updated`\n try {\n await bus.emitEvent(eventName, { id: recordId, organizationId, tenantId }, {\n persistent: true,\n tenantId,\n organizationId,\n emitterModuleId: mod,\n })\n } catch {\n // non-blocking\n }\n }\n }\n }\n }\n\n private normalizeDocValues(values: CustomEntityValues): CustomEntityValues {\n const out: CustomEntityValues = {}\n for (const [k, v] of Object.entries(values || {})) {\n // Never allow callers to override reserved identifiers in the doc\n if (k === 'id' || k === 'entity_id' || k === 'entityId') continue\n // Accept both 'cf_<key>' and 'cf:<key>' inputs and normalize to 'cf:<key>'\n if (k.startsWith('cf_')) out[`cf:${k.slice(3)}`] = v\n else out[k] = v\n }\n return out\n }\n\n private backcompatEavEnabled(): boolean {\n try {\n return parseBooleanToken(process.env.ENTITIES_BACKCOMPAT_EAV_FOR_CUSTOM ?? '') === true\n } catch { return false }\n }\n\n private resolveCustomEntityEncryptionService(): TenantDataEncryptionService | null {\n try {\n return this.container.resolve<TenantDataEncryptionService>('tenantEncryptionService')\n } catch {\n return null\n }\n }\n\n private getKysely(): Kysely<any> {\n return this.em.getKysely<any>()\n }\n\n private async ensureStorageTableExists(): Promise<void> {\n const cacheKey = 'custom_entities_storage'\n if (tableExistsCache.get(cacheKey)) return\n const db = this.getKysely()\n const exists = await db\n .selectFrom('information_schema.tables' as any)\n .select(sql`1`.as('present'))\n .where('table_name' as any, '=', 'custom_entities_storage')\n .executeTakeFirst()\n if (!exists) {\n throw new Error('custom_entities_storage table is missing. Run migrations (yarn db:migrate).')\n }\n tableExistsCache.set(cacheKey, true)\n }\n\n private normalizeValuesForValidation(values: Record<string, unknown> | undefined | null): Record<string, unknown> {\n if (!values) return {}\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n if (key.startsWith('cf_') || key.startsWith('cf:')) {\n const normalized = key.slice(3)\n if (normalized) out[normalized] = value\n continue\n }\n out[key] = value\n }\n return out\n }\n\n private async validateCustomFieldValues(\n entityId: string,\n organizationId: string | null,\n tenantId: string | null,\n values: Record<string, unknown> | undefined | null,\n ): Promise<void> {\n const prepared = this.normalizeValuesForValidation(values)\n if (!entityId || Object.keys(prepared).length === 0) return\n const result = await validateCustomFieldValuesServer(this.em, {\n entityId,\n organizationId,\n tenantId,\n values: prepared,\n })\n if (!result.ok) {\n throw new CrudHttpError(400, { error: 'Validation failed', fields: result.fieldErrors })\n }\n }\n\n private async withCustomEntityStorageLock<T>(lockKey: string, work: (txEm: EntityManager) => Promise<T>): Promise<T> {\n if (!this.em.isInTransaction?.()) return withAdvisoryXactLock(this.em, lockKey, work)\n const deadlineAt = Date.now() + 15_000\n while (true) {\n const rows = await this.em.execute<Array<{ locked: boolean }>>(\n 'select pg_try_advisory_xact_lock(hashtextextended(?, 0)) as locked',\n [lockKey],\n )\n if (rows[0]?.locked) return work(this.em)\n const remainingMs = deadlineAt - Date.now()\n if (remainingMs <= 0) throw new AdvisoryLockUnavailableError('deadline', lockKey)\n await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, remainingMs)))\n }\n }\n\n private async writeCustomEntityStorageDoc(target: {\n entityType: string\n entityId: string\n organizationId: string | null\n tenantId: string | null\n doc: Record<string, unknown>\n requireActive?: boolean\n }): Promise<void> {\n const lockKey = `custom_entity_create:${JSON.stringify([target.tenantId, target.organizationId, target.entityType, target.entityId.toLowerCase()])}`\n await this.withCustomEntityStorageLock(lockKey, async (txEm) => {\n const db = txEm.getKysely<CustomEntityStorageDatabase>()\n const doc = sql<CustomEntityValues>`${JSON.stringify(target.doc)}::jsonb`\n let update = db\n .updateTable('custom_entities_storage')\n .set({ doc, updated_at: sql<Date>`now()`, deleted_at: null })\n .where('entity_type', '=', target.entityType)\n .where('entity_id', '=', target.entityId)\n .where('organization_id', target.organizationId === null ? 'is' : '=', target.organizationId)\n .where('tenant_id', target.tenantId === null ? 'is' : '=', target.tenantId)\n if (target.requireActive) update = update.where('deleted_at', 'is', null)\n const updated = await update.executeTakeFirst()\n if (Number(updated.numUpdatedRows) > 0) return\n if (target.requireActive) throw notFound()\n await db.insertInto('custom_entities_storage').values({\n entity_type: target.entityType,\n entity_id: target.entityId,\n organization_id: target.organizationId,\n tenant_id: target.tenantId,\n doc,\n created_at: sql<Date>`now()`,\n updated_at: sql<Date>`now()`,\n deleted_at: null,\n }).execute()\n })\n }\n\n async createCustomEntityRecord(opts: Parameters<DataEngine['createCustomEntityRecord']>[0]): Promise<{ id: string }> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n await this.ensureStorageTableExists()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const rawId = String(opts.recordId ?? '').trim()\n const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(rawId)\n const sentinel = rawId.toLowerCase()\n const shouldGenerate = !rawId || !isUuid || sentinel === 'create' || sentinel === 'new' || sentinel === 'null' || sentinel === 'undefined'\n const id = shouldGenerate ? ((): string => {\n const g = globalThis as { crypto?: { randomUUID?: () => string } }\n if (g.crypto?.randomUUID) return g.crypto.randomUUID()\n // Fallback UUIDv4 generator\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0\n const v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16)\n })\n })() : rawId\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const doc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { id, ...this.normalizeDocValues(sanitizedValues || {}) },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n\n const now = sql<Date>`now()`\n const payload = {\n entity_type: opts.entityId,\n entity_id: id,\n organization_id: orgId,\n tenant_id: tenantId,\n doc: sql<CustomEntityValues>`${JSON.stringify(doc)}::jsonb`,\n updated_at: now,\n created_at: now,\n deleted_at: null,\n }\n\n if (opts.createOnly) {\n const duplicateError = () => {\n const error = conflict('[internal] Custom entity record already exists')\n error.body.code = 'custom_entity_record_exists'\n return error\n }\n const lockKey = `custom_entity_create:${JSON.stringify([tenantId, orgId, opts.entityId, id.toLowerCase()])}`\n await withAdvisoryXactLock(this.em, lockKey, async (txEm) => {\n const storage = txEm.getKysely<CustomEntityStorageDatabase>()\n const existing = await storage\n .selectFrom('custom_entities_storage')\n .select('entity_id')\n .where('entity_type', '=', opts.entityId)\n .where(sql<string>`lower(entity_id::text)`, '=', id.toLowerCase())\n .where('organization_id', orgId === null ? 'is' : '=', orgId)\n .where('tenant_id', tenantId === null ? 'is' : '=', tenantId)\n .executeTakeFirst()\n if (existing) throw duplicateError()\n try {\n await storage.insertInto('custom_entities_storage').values(payload).execute()\n } catch (error) {\n if (isUniqueViolation(error, 'custom_entities_storage_unique_idx')) throw duplicateError()\n throw error\n }\n })\n } else {\n await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc })\n }\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n\n return { id }\n }\n\n async updateCustomEntityRecord(opts: Parameters<DataEngine['updateCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const sanitizedValues = await sanitizeCustomFieldHtmlRichTextValuesServer(this.em, {\n entityId: opts.entityId,\n organizationId: opts.organizationId ?? null,\n tenantId: opts.tenantId ?? null,\n values: opts.values || {},\n })\n await this.validateCustomFieldValues(opts.entityId, opts.organizationId ?? null, opts.tenantId ?? null, sanitizedValues)\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const requireActive = opts.requireActive === true\n\n // Merge doc shallowly: load existing doc and overlay\n await this.ensureStorageTableExists()\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n if (requireActive) chain = chain.where('deleted_at', 'is', null)\n return chain\n }\n const row = await applyScope(\n db.selectFrom('custom_entities_storage' as any).select(['doc' as any])\n ).executeTakeFirst()\n if (requireActive && !row) throw notFound()\n const prevDoc: Record<string, unknown> = (row as any)?.doc || { id }\n const nextDoc = await encryptCustomEntityRecordDocument(this.em, {\n entityId: opts.entityId, organizationId: orgId, tenantId,\n doc: { ...prevDoc, ...this.normalizeDocValues(sanitizedValues || {}), id },\n encryptionService: this.resolveCustomEntityEncryptionService(),\n })\n await this.writeCustomEntityStorageDoc({ entityType: opts.entityId, entityId: id, organizationId: orgId, tenantId, doc: nextDoc, requireActive })\n\n // Optional EAV backward compatibility (disabled by default)\n if (this.backcompatEavEnabled() && sanitizedValues && Object.keys(sanitizedValues).length > 0) {\n await this.setCustomFields({\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: tenantId,\n values: normalizeCustomFieldValues(sanitizedValues),\n notify: opts.notify, // defaults to true\n // custom_entities_storage upserts on (entity_type, entity_id, organization_id),\n // so `id` is unique only within this organization, not across organizations \u2014\n // pin the reconciling delete/lookup to this organization (#6034 review).\n pinOrganizationId: true,\n })\n }\n }\n\n async deleteCustomEntityRecord(opts: Parameters<DataEngine['deleteCustomEntityRecord']>[0]): Promise<void> {\n assertCustomEntityStorageEntityId(this.em, opts.entityId)\n const db = this.getKysely()\n const id = String(opts.recordId)\n const orgId = opts.organizationId ?? null\n const tenantId = opts.tenantId ?? null\n const soft = opts.soft !== false\n\n const applyScope = <T extends { where: (col: any, op: any, val?: any) => T }>(q: T) => {\n let chain = q.where('entity_type' as any, '=', opts.entityId)\n chain = chain.where('entity_id' as any, '=', id)\n chain = orgId === null\n ? chain.where('organization_id' as any, 'is', null as any)\n : chain.where('organization_id' as any, '=', orgId)\n chain = tenantId === null\n ? chain.where('tenant_id' as any, 'is', null as any)\n : chain.where('tenant_id' as any, '=', tenantId)\n return chain\n }\n\n if (soft) {\n await applyScope(\n db.updateTable('custom_entities_storage' as any).set({\n deleted_at: sql`now()`,\n updated_at: sql`now()`,\n } as any) as any\n ).execute()\n } else {\n await applyScope(db.deleteFrom('custom_entities_storage' as any) as any).execute()\n }\n\n // Soft-delete EAV values to preserve current behavior\n try {\n const { CustomFieldValue } = await import('@open-mercato/core/modules/entities/data/entities')\n const values = await this.em.find(CustomFieldValue, {\n entityId: opts.entityId,\n recordId: id,\n organizationId: orgId,\n tenantId: opts.tenantId ?? null,\n })\n const now = new Date()\n const mutated = values.filter((record) => {\n if (record.deletedAt) return false\n record.deletedAt = now\n return true\n })\n if (mutated.length) {\n for (const record of values) this.em.persist(record)\n await this.em.flush()\n }\n } catch { /* non-blocking */ }\n }\n\n async createOrmEntity<T extends object>(opts: { entity: EntityName<T>; data: EntityData<T> }): Promise<T> {\n const entity = this.em.create(\n opts.entity as EntityName<T>,\n opts.data as unknown as RequiredEntityData<T>\n )\n await this.em.persist(entity).flush()\n return entity\n }\n\n async updateOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n apply: (current: T) => Promise<void> | void\n }): Promise<T | null> {\n const current = await this.em.findOne(opts.entity as EntityName<T>, opts.where as FilterQuery<NoInfer<T>>)\n if (!current) return null\n await opts.apply(current)\n await this.em.persist(current).flush()\n return current\n }\n\n async deleteOrmEntity<T extends object>(opts: {\n entity: EntityName<T>\n where: FilterQuery<T>\n soft?: boolean\n softDeleteField?: keyof T & string\n }): Promise<T | null> {\n const current = await this.em.findOne(opts.entity as EntityName<T>, opts.where as FilterQuery<NoInfer<T>>)\n if (!current) return null\n if (opts.soft !== false) {\n const field = opts.softDeleteField || ('deletedAt' as keyof T & string)\n if (typeof current === 'object' && current !== null) {\n ;(current as Record<string, unknown>)[field] = new Date()\n await this.em.persist(current).flush()\n }\n } else {\n await this.em.remove(current).flush()\n }\n return current\n }\n\n async emitOrmEntityEvent<T>(opts: {\n action: CrudEventAction\n entity: T\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n suppress?: BulkImportSuppression\n }): Promise<void> {\n const { action, entity, events, indexer, identifiers, syncOrigin, suppress } = opts\n // Bulk-import deferral: an entry may suppress its domain event and/or inline reindex. When both\n // the config is absent AND (for the present one) suppressed, there is nothing left to do.\n const emitEvents = !!events && !suppress?.skipEvents\n const runIndexer = !!indexer && !suppress?.skipReindex\n if (!emitEvents && !runIndexer) return\n if (!identifiers?.id) return\n\n let bus: EventBus | null = null\n try {\n bus = (this.container.resolve('eventBus') as EventBus)\n } catch {\n bus = null\n }\n if (!bus) return\n\n const ctx = {\n action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n\n if (events && !suppress?.skipEvents) {\n const eventName = `${events.module}.${events.entity}.${action}`\n warnIfUndeclaredEvent(eventName, 'emitOrmEntityEvent')\n const builtPayload = events.buildPayload\n ? events.buildPayload(ctx)\n : {\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }\n // A configured indexer means this data-engine call owns the query-index\n // decision, including an explicit skipReindex suppression. Mark object\n // payloads so the legacy domain-event bridge does not enqueue the same\n // record a second time. Keep the marker non-enumerable so client broadcasts\n // and persisted domain payloads retain their existing public shape.\n // Primitive custom payloads cannot be bridged in any case because they do\n // not expose the record id.\n const payload = indexer && builtPayload && typeof builtPayload === 'object' && !Array.isArray(builtPayload)\n ? Object.defineProperty(\n { ...(builtPayload as Record<string, unknown>) },\n CRUD_QUERY_INDEX_MANAGED_PAYLOAD_KEY,\n { value: true, enumerable: false },\n )\n : builtPayload\n try {\n await bus.emitEvent(eventName, payload, {\n persistent: !!events.persistent,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: ctx.identifiers.organizationId ?? null,\n emitterModuleId: events.module,\n })\n } catch {\n // non-blocking\n }\n }\n\n if (indexer && !suppress?.skipReindex) {\n const alwaysConsistent = isReadProjectionAlwaysConsistent()\n const resolveCoverageBaseDelta = (): number | undefined => {\n if (action === 'created') return 1\n if (action === 'deleted') return -1\n return undefined\n }\n const coverageBaseDelta = resolveCoverageBaseDelta()\n\n if (action === 'deleted') {\n const payload = indexer.buildDeletePayload\n ? indexer.buildDeletePayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the index update so query-index reads (the `customValues`/scalar\n // projection that list endpoints serve) are consistent the moment the write\n // returns. The subscriber removes the projection row + tokens synchronously and\n // defers the coverage recompute + fulltext delete, so this stays bounded.\n // Errors are logged, not thrown \u2014 index drift never fails the originating write.\n // Always-consistent mode rethrows so drift is loud and retryable.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.delete_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.delete_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.delete_one emit failed', { err })\n })\n }\n } else {\n const payload = indexer.buildUpsertPayload\n ? indexer.buildUpsertPayload(ctx)\n : {\n entityType: indexer.entityType,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }\n const enrichedPayload = payload as Record<string, unknown>\n enrichedPayload.crudAction = action\n if (coverageBaseDelta !== undefined) enrichedPayload.coverageBaseDelta = coverageBaseDelta\n if (ctx.syncOrigin) enrichedPayload.syncOrigin = ctx.syncOrigin\n // Await the projection upsert so list reads observe the new doc immediately\n // (see delete_one above). The subscriber updates `entity_indexes` synchronously\n // and defers the heavy token-reindex pipeline (build doc + encrypt + decrypt +\n // tokenize + DELETE + chunked INSERT) so write latency stays bounded.\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload, { rethrowHandlerErrors: true })\n } else {\n await bus.emitEvent('query_index.upsert_one', enrichedPayload).catch((err: unknown) => {\n logger.error('query_index.upsert_one emit failed', { err })\n })\n }\n }\n\n if (alwaysConsistent || shouldTriggerCoverageRefresh(indexer.entityType, ctx.identifiers.tenantId ?? null)) {\n const coveragePayload = {\n entityType: indexer.entityType,\n tenantId: ctx.identifiers.tenantId ?? null,\n organizationId: null,\n delayMs: 0,\n }\n if (alwaysConsistent) {\n await bus.emitEvent('query_index.coverage.refresh', coveragePayload, { rethrowHandlerErrors: true })\n } else {\n void bus.emitEvent('query_index.coverage.refresh', coveragePayload).catch(() => undefined)\n }\n }\n }\n }\n\n markOrmEntityChange<T>(opts: {\n action: CrudEventAction\n entity: T | null | undefined\n events?: CrudEventsConfig<T>\n indexer?: CrudIndexerConfig<T>\n identifiers: CrudEntityIdentifiers\n syncOrigin?: string | null\n actorUserId?: string | null\n }): void {\n const { entity, identifiers } = opts\n if (!entity) return\n if (!identifiers?.id) return\n // A command handler that marks `events:` only still discharges the route's declared\n // query-index obligation \u2014 the route hands its `indexer:` down as the default so the\n // handler's own entity and identifiers (the accurate ones) drive the projection write.\n const indexer = opts.indexer ?? this.resolveDefaultIndexer(entity)\n const key = this.buildSideEffectKey(opts.action, identifiers)\n const existing = this.pendingSideEffects.get(key)\n if (existing) {\n existing.entity = entity\n existing.identifiers = {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n }\n existing.syncOrigin = opts.syncOrigin ?? null\n existing.actorUserId = opts.actorUserId ?? null\n if (opts.events) existing.events = opts.events as CrudEventsConfig<unknown>\n // Explicit always wins, on the merge branch too: a second `events:`-only mark on the same\n // key must not let the route default overwrite the `indexer:` an earlier mark installed,\n // which would silently drop that handler's own `buildUpsertPayload`.\n if (opts.indexer) existing.indexer = opts.indexer as CrudIndexerConfig<unknown>\n else if (!existing.indexer && indexer) existing.indexer = indexer\n this.pendingSideEffects.set(key, existing)\n return\n }\n const entry: QueuedCrudSideEffect = {\n action: opts.action,\n entity,\n identifiers: {\n id: identifiers.id,\n organizationId: identifiers.organizationId ?? null,\n tenantId: identifiers.tenantId ?? null,\n },\n syncOrigin: opts.syncOrigin ?? null,\n actorUserId: opts.actorUserId ?? null,\n }\n if (opts.events) entry.events = opts.events as CrudEventsConfig<unknown>\n if (indexer) entry.indexer = indexer\n this.pendingSideEffects.set(key, entry)\n }\n\n async flushOrmEntityChanges(suppress?: BulkImportSuppression): Promise<void> {\n if (!this.pendingSideEffects.size) return\n const entries = Array.from(this.pendingSideEffects.values())\n this.pendingSideEffects.clear()\n for (const entry of entries) {\n if (entry.indexer && !suppress?.skipReindex && this.matchesDefaultEntityClass(entry.entity)) {\n this.indexedDefaultEntityClass = true\n }\n try {\n await this.emitOrmEntityEvent({\n action: entry.action,\n entity: entry.entity,\n identifiers: entry.identifiers,\n syncOrigin: entry.syncOrigin ?? null,\n actorUserId: entry.actorUserId ?? null,\n events: entry.events as CrudEventsConfig<unknown>,\n indexer: entry.indexer as CrudIndexerConfig<unknown>,\n suppress,\n })\n } catch (error) {\n if (isReadProjectionAlwaysConsistent()) {\n throw error\n }\n // best-effort; continue with remaining side effects\n }\n }\n }\n\n private buildSideEffectKey(action: CrudEventAction, identifiers: CrudEntityIdentifiers): string {\n const id = identifiers.id ?? ''\n const org = identifiers.organizationId ?? ''\n const tenant = identifiers.tenantId ?? ''\n return [action, id, org, tenant].join('|')\n }\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAsB,WAAW;AACjC,SAAS,mCAAmC,6BAA6B;AACzE,SAAS,uCAAuC;AAChD,SAAS,mDAAmD;AAE5D;AAAA,EACE;AAAA,OAKK;AAEP,SAAS,UAAU,eAAe,mBAAmB,gBAAgB;AACrE,SAAS,8BAA8B,4BAA4B;AACnE,SAAS,wCAAwC;AACjD,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAC3C,SAAS,yBAAyB;AAClC,SAAS,wCAAwC;AACjD,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAGrC,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAExE,MAAM,wBAAwB,oBAAI,IAAY;AAE9C,SAAS,sBAAsB,WAAmB,SAAuB;AACvE,MAAI,gBAAgB,SAAS,EAAG;AAChC,MAAI,sBAAsB,IAAI,SAAS,EAAG;AAC1C,wBAAsB,IAAI,SAAS;AACnC,SAAO,KAAK,6IAAwI,EAAE,SAAS,UAAU,CAAC;AAC5K;AAGO,SAAS,yCAA+C;AAC7D,wBAAsB,MAAM;AAC9B;AAGA,MAAM,mBAAmB,qBAA2B;AAAA,EAClD,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,mBAAmB;AACrB,CAAC;AAGM,SAAS,kCAAwC;AACtD,mBAAiB,MAAM;AACzB;AAEA,MAAM,+BAA+B,IAAI,KAAK;AAC9C,MAAM,yBAAyB,oBAAI,IAAoB;AAEvD,SAAS,6BAA6B,YAAgC,UAAkC;AACtG,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,MAAM,GAAG,UAAU,IAAI,YAAY,UAAU;AACnD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,OAAO,uBAAuB,IAAI,GAAG,KAAK;AAChD,MA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C9F,UAAM,KAAK,YAAY,MAAM;AAC7B,UAAM,MAAM,YAAY,kBAAkB;AAC1C,UAAM,SAAS,YAAY,YAAY;AACvC,WAAO,CAAC,QAAQ,IAAI,KAAK,MAAM,EAAE,KAAK,GAAG;AAAA,EAC3C;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { resolveEntityTableName } from "../query/engine.js";
|
|
3
|
+
import { listEntityMetadata } from "./entityMetadata.js";
|
|
4
|
+
const ORGANIZATION_COLUMN = "organization_id";
|
|
5
|
+
const TENANT_COLUMN = "tenant_id";
|
|
6
|
+
let probedColumnsCache = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
function readScopeFieldName(property) {
|
|
8
|
+
const fieldNames = property?.fieldNames;
|
|
9
|
+
if (!Array.isArray(fieldNames) || fieldNames.length !== 1) return null;
|
|
10
|
+
const [fieldName] = fieldNames;
|
|
11
|
+
return typeof fieldName === "string" && fieldName.length > 0 ? fieldName : null;
|
|
12
|
+
}
|
|
13
|
+
function resolveScopeColumnsFromMetadata(em, table) {
|
|
14
|
+
const matches = listEntityMetadata(em).filter((metadata) => metadata.tableName === table);
|
|
15
|
+
if (matches.length !== 1) return null;
|
|
16
|
+
const properties = matches[0].properties ?? {};
|
|
17
|
+
return {
|
|
18
|
+
organizationColumn: readScopeFieldName(properties.organizationId),
|
|
19
|
+
tenantColumn: readScopeFieldName(properties.tenantId)
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
async function probeScopeColumns(db, table) {
|
|
23
|
+
let cache = probedColumnsCache.get(db);
|
|
24
|
+
if (!cache) {
|
|
25
|
+
cache = /* @__PURE__ */ new Map();
|
|
26
|
+
probedColumnsCache.set(db, cache);
|
|
27
|
+
}
|
|
28
|
+
const cached = cache.get(table);
|
|
29
|
+
if (cached) return cached;
|
|
30
|
+
try {
|
|
31
|
+
const rows = await db.selectFrom("information_schema.columns").select(["column_name"]).where(sql`table_schema = current_schema()`).where("table_name", "=", table).where("column_name", "in", [ORGANIZATION_COLUMN, TENANT_COLUMN]).execute();
|
|
32
|
+
const columns = new Set(rows.map((row) => typeof row.column_name === "string" ? row.column_name.toLowerCase() : ""));
|
|
33
|
+
const resolved = {
|
|
34
|
+
organizationColumn: columns.has(ORGANIZATION_COLUMN) ? ORGANIZATION_COLUMN : null,
|
|
35
|
+
tenantColumn: columns.has(TENANT_COLUMN) ? TENANT_COLUMN : null
|
|
36
|
+
};
|
|
37
|
+
cache.set(table, resolved);
|
|
38
|
+
return resolved;
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function resolveEntityScopeColumns(em, entityType) {
|
|
44
|
+
const table = resolveEntityTableName(em, entityType);
|
|
45
|
+
if (!table) return null;
|
|
46
|
+
const columns = resolveScopeColumnsFromMetadata(em, table) ?? await probeScopeColumns(em.getKysely(), table);
|
|
47
|
+
if (!columns) return null;
|
|
48
|
+
return { table, ...columns };
|
|
49
|
+
}
|
|
50
|
+
async function loadEntityRecordScope(em, entityType, recordId) {
|
|
51
|
+
const columns = await resolveEntityScopeColumns(em, entityType);
|
|
52
|
+
if (!columns) return null;
|
|
53
|
+
const selected = [columns.organizationColumn, columns.tenantColumn].filter((column) => column !== null);
|
|
54
|
+
if (selected.length === 0) return null;
|
|
55
|
+
const row = await em.getKysely().selectFrom(columns.table).select(selected).where("id", "=", recordId).executeTakeFirst();
|
|
56
|
+
if (!row) return null;
|
|
57
|
+
const organizationId = columns.organizationColumn ? row[columns.organizationColumn] : null;
|
|
58
|
+
const tenantId = columns.tenantColumn ? row[columns.tenantColumn] : null;
|
|
59
|
+
return {
|
|
60
|
+
organizationId: typeof organizationId === "string" ? organizationId : null,
|
|
61
|
+
tenantId: typeof tenantId === "string" ? tenantId : null
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function resetEntityScopeColumnsCacheForTests() {
|
|
65
|
+
probedColumnsCache = /* @__PURE__ */ new WeakMap();
|
|
66
|
+
}
|
|
67
|
+
export {
|
|
68
|
+
loadEntityRecordScope,
|
|
69
|
+
resetEntityScopeColumnsCacheForTests,
|
|
70
|
+
resolveEntityScopeColumns
|
|
71
|
+
};
|
|
72
|
+
//# sourceMappingURL=recordScope.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/lib/db/recordScope.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\nimport { resolveEntityTableName } from '../query/engine'\nimport { listEntityMetadata } from './entityMetadata'\n\nexport type EntityScopeColumns = {\n table: string\n organizationColumn: string | null\n tenantColumn: string | null\n}\n\nexport type EntityRecordScope = {\n organizationId: string | null\n tenantId: string | null\n}\n\ntype ScopeLookupEntityManager = {\n getKysely: <T = unknown>() => Kysely<T>\n getMetadata?: () => unknown\n}\n\ntype ScopePropertyMetadata = { fieldNames?: unknown }\ntype ScopeDatabase = Record<string, Record<string, unknown>>\n\nconst ORGANIZATION_COLUMN = 'organization_id'\nconst TENANT_COLUMN = 'tenant_id'\n\nlet probedColumnsCache = new WeakMap<Kysely<ScopeDatabase>, Map<string, { organizationColumn: string | null; tenantColumn: string | null }>>()\n\nfunction readScopeFieldName(property: ScopePropertyMetadata | undefined): string | null {\n const fieldNames = property?.fieldNames\n if (!Array.isArray(fieldNames) || fieldNames.length !== 1) return null\n const [fieldName] = fieldNames\n return typeof fieldName === 'string' && fieldName.length > 0 ? fieldName : null\n}\n\nfunction resolveScopeColumnsFromMetadata(\n em: ScopeLookupEntityManager,\n table: string,\n): { organizationColumn: string | null; tenantColumn: string | null } | null {\n const matches = listEntityMetadata(em).filter((metadata) => metadata.tableName === table)\n if (matches.length !== 1) return null\n const properties = (matches[0].properties ?? {}) as Record<string, ScopePropertyMetadata | undefined>\n return {\n organizationColumn: readScopeFieldName(properties.organizationId),\n tenantColumn: readScopeFieldName(properties.tenantId),\n }\n}\n\nasync function probeScopeColumns(\n db: Kysely<ScopeDatabase>,\n table: string,\n): Promise<{ organizationColumn: string | null; tenantColumn: string | null } | null> {\n let cache = probedColumnsCache.get(db)\n if (!cache) {\n cache = new Map()\n probedColumnsCache.set(db, cache)\n }\n const cached = cache.get(table)\n if (cached) return cached\n try {\n const rows = await db\n .selectFrom('information_schema.columns')\n .select(['column_name'])\n .where(sql<boolean>`table_schema = current_schema()`)\n .where('table_name', '=', table)\n .where('column_name', 'in', [ORGANIZATION_COLUMN, TENANT_COLUMN])\n .execute()\n const columns = new Set(rows.map((row) => typeof row.column_name === 'string' ? row.column_name.toLowerCase() : ''))\n const resolved = {\n organizationColumn: columns.has(ORGANIZATION_COLUMN) ? ORGANIZATION_COLUMN : null,\n tenantColumn: columns.has(TENANT_COLUMN) ? TENANT_COLUMN : null,\n }\n cache.set(table, resolved)\n return resolved\n } catch {\n return null\n }\n}\n\n/**\n * Resolve which tenant/organization scope columns the table behind `entityType` actually has.\n * Uses ORM metadata when the table is registered; otherwise probes `information_schema.columns`.\n * Returns `null` when the columns cannot be determined, so callers skip the row lookup instead\n * of issuing a select that fails on global tables (e.g. `feature_toggles`).\n */\nexport async function resolveEntityScopeColumns(\n em: ScopeLookupEntityManager,\n entityType: string,\n): Promise<EntityScopeColumns | null> {\n const table = resolveEntityTableName(em as never, entityType)\n if (!table) return null\n const columns = resolveScopeColumnsFromMetadata(em, table)\n ?? await probeScopeColumns(em.getKysely<ScopeDatabase>(), table)\n if (!columns) return null\n return { table, ...columns }\n}\n\n/**\n * Read the tenant/organization scope of one record by id, selecting only the scope columns its\n * table has. Returns `null` when the table has no scope columns, the columns cannot be\n * determined, or the row does not exist.\n */\nexport async function loadEntityRecordScope(\n em: ScopeLookupEntityManager,\n entityType: string,\n recordId: string,\n): Promise<EntityRecordScope | null> {\n const columns = await resolveEntityScopeColumns(em, entityType)\n if (!columns) return null\n const selected = [columns.organizationColumn, columns.tenantColumn]\n .filter((column): column is string => column !== null)\n if (selected.length === 0) return null\n const row = await em.getKysely<ScopeDatabase>()\n .selectFrom(columns.table)\n .select(selected)\n .where('id', '=', recordId)\n .executeTakeFirst()\n if (!row) return null\n const organizationId = columns.organizationColumn ? row[columns.organizationColumn] : null\n const tenantId = columns.tenantColumn ? row[columns.tenantColumn] : null\n return {\n organizationId: typeof organizationId === 'string' ? organizationId : null,\n tenantId: typeof tenantId === 'string' ? tenantId : null,\n }\n}\n\nexport function resetEntityScopeColumnsCacheForTests(): void {\n probedColumnsCache = new WeakMap()\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAqBnC,MAAM,sBAAsB;AAC5B,MAAM,gBAAgB;AAEtB,IAAI,qBAAqB,oBAAI,QAAgH;AAE7I,SAAS,mBAAmB,UAA4D;AACtF,QAAM,aAAa,UAAU;AAC7B,MAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,WAAW,WAAW,EAAG,QAAO;AAClE,QAAM,CAAC,SAAS,IAAI;AACpB,SAAO,OAAO,cAAc,YAAY,UAAU,SAAS,IAAI,YAAY;AAC7E;AAEA,SAAS,gCACP,IACA,OAC2E;AAC3E,QAAM,UAAU,mBAAmB,EAAE,EAAE,OAAO,CAAC,aAAa,SAAS,cAAc,KAAK;AACxF,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,aAAc,QAAQ,CAAC,EAAE,cAAc,CAAC;AAC9C,SAAO;AAAA,IACL,oBAAoB,mBAAmB,WAAW,cAAc;AAAA,IAChE,cAAc,mBAAmB,WAAW,QAAQ;AAAA,EACtD;AACF;AAEA,eAAe,kBACb,IACA,OACoF;AACpF,MAAI,QAAQ,mBAAmB,IAAI,EAAE;AACrC,MAAI,CAAC,OAAO;AACV,YAAQ,oBAAI,IAAI;AAChB,uBAAmB,IAAI,IAAI,KAAK;AAAA,EAClC;AACA,QAAM,SAAS,MAAM,IAAI,KAA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AACjB,QAAM,iBAAiB,QAAQ,qBAAqB,IAAI,QAAQ,kBAAkB,IAAI;AACtF,QAAM,WAAW,QAAQ,eAAe,IAAI,QAAQ,YAAY,IAAI;AACpE,SAAO;AAAA,IACL,gBAAgB,OAAO,mBAAmB,WAAW,iBAAiB;AAAA,IACtE,UAAU,OAAO,aAAa,WAAW,WAAW;AAAA,EACtD;AACF;AAEO,SAAS,uCAA6C;AAC3D,uBAAqB,oBAAI,QAAQ;AACnC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/lib/version.js
CHANGED
package/dist/lib/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.
|
|
4
|
+
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8024.1.02dbc16b49';\nexport const appVersion = APP_VERSION;\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8024.1.02dbc16b49",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
"@mikro-orm/core": "^7.1.14",
|
|
131
131
|
"@mikro-orm/decorators": "^7.1.14",
|
|
132
132
|
"@mikro-orm/postgresql": "^7.1.14",
|
|
133
|
-
"@open-mercato/cache": "0.10.1-develop.
|
|
133
|
+
"@open-mercato/cache": "0.10.1-develop.8024.1.02dbc16b49",
|
|
134
134
|
"@types/html-to-text": "^9.0.4",
|
|
135
135
|
"@types/sanitize-html": "^2.16.1",
|
|
136
136
|
"dotenv": "^17.4.2",
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
jest.mock('../../db/advisoryLock', () => ({
|
|
2
|
+
withAdvisoryXactLock: async <T>(em: unknown, _key: string, work: (txEm: unknown) => Promise<T>): Promise<T> => work(em),
|
|
3
|
+
}))
|
|
4
|
+
|
|
1
5
|
import { randomUUID } from 'node:crypto'
|
|
2
6
|
import { Kysely, PostgresDialect, sql } from 'kysely'
|
|
3
7
|
import { Pool } from 'pg'
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
jest.mock('../../db/advisoryLock', () => ({
|
|
2
|
+
withAdvisoryXactLock: async <T>(em: unknown, _key: string, work: (txEm: unknown) => Promise<T>): Promise<T> => work(em),
|
|
3
|
+
}))
|
|
4
|
+
|
|
1
5
|
import { randomUUID } from 'node:crypto'
|
|
2
6
|
import { Kysely, PostgresDialect, sql } from 'kysely'
|
|
3
7
|
import { Pool } from 'pg'
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
jest.mock('../../db/advisoryLock', () => ({
|
|
2
|
+
withAdvisoryXactLock: async <T>(em: unknown, _key: string, work: (txEm: unknown) => Promise<T>): Promise<T> => work(em),
|
|
3
|
+
}))
|
|
4
|
+
|
|
1
5
|
import { CustomFieldDef } from '@open-mercato/core/modules/entities/data/entities'
|
|
2
6
|
import { DefaultDataEngine, clearDataEngineTableExistsCache } from '../engine'
|
|
3
7
|
import { decryptWithAesGcm, encryptWithAesGcm, isEncryptedPayloadShape, TenantDataEncryptionErrorCode } from '../../encryption/aes'
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
jest.mock('../../db/advisoryLock', () => ({
|
|
2
|
+
withAdvisoryXactLock: async <T>(em: unknown, _key: string, work: (txEm: unknown) => Promise<T>): Promise<T> => work(em),
|
|
3
|
+
}))
|
|
4
|
+
|
|
1
5
|
import { DefaultDataEngine, clearDataEngineTableExistsCache } from '../engine'
|
|
2
6
|
import { registerEntityIds } from '../../encryption/entityIds'
|
|
3
7
|
import { isCrudHttpError } from '../../crud/errors'
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
jest.mock('../../db/advisoryLock', () => ({
|
|
2
|
+
withAdvisoryXactLock: async <T>(em: unknown, _key: string, work: (txEm: unknown) => Promise<T>): Promise<T> => work(em),
|
|
3
|
+
}))
|
|
4
|
+
|
|
1
5
|
import { DefaultDataEngine, clearDataEngineTableExistsCache } from '../engine'
|
|
2
6
|
import { registerEntityIds } from '../../encryption/entityIds'
|
|
3
7
|
|