@open-mercato/shared 0.8.1-develop.7241.1.fad7b2ce2a → 0.8.1-develop.7254.1.ab24f26208

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.
@@ -157,12 +157,21 @@ async function createRequestContainer() {
157
157
  // registrations override this default via Awilix replace semantics —
158
158
  // see the enterprise `record_locks` module for the canonical override.
159
159
  // Spec: .ai/specs/implemented/2026-05-25-oss-optimistic-locking.md
160
+ // `.proxy()` is load-bearing, not stylistic. The container runs in CLASSIC
161
+ // injection mode, where Awilix resolves dependencies by parsing PARAMETER
162
+ // NAMES out of the function source. A bundler that renames `em` to `em2` —
163
+ // Turbopack does, on a scope collision — makes Awilix look up a registration
164
+ // that does not exist, and `resolveCrudMutationGuardService` swallows the
165
+ // AwilixResolutionError and returns null, so `bridgeLegacyGuard` silently
166
+ // drops the guard and every mutation runs with optimistic locking NOT
167
+ // enforced. Reading `cradle.em` resolves by property name, which survives
168
+ // mangling. Pinned by `di-injection-mode.test.ts`.
160
169
  crudMutationGuardService: asFunction(
161
- (em2) => createOptimisticLockGuardService({
162
- getEm: () => em2,
170
+ (cradle) => createOptimisticLockGuardService({
171
+ getEm: () => cradle.em,
163
172
  readers: getAllOptimisticLockReaders()
164
173
  })
165
- ).scoped(),
174
+ ).scoped().proxy(),
166
175
  // Default OSS command-level optimistic-lock guard, awaited by
167
176
  // `enforceCommandOptimisticLockWithGuards` for Command-pattern writes.
168
177
  // Header/explicit-token compare only (no `resolveExpected`), so it is
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/di/container.ts"],
4
- "sourcesContent": ["import { asFunction, createContainer, asValue, AwilixContainer, InjectionMode, type Resolver } from 'awilix'\nimport { RequestContext } from '@mikro-orm/core'\nimport { getOrm } from '@open-mercato/shared/lib/db/mikro'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { BasicQueryEngine } from '@open-mercato/shared/lib/query/engine'\nimport { DefaultDataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { commandRegistry, CommandBus } from '@open-mercato/shared/lib/commands'\nimport { applyDiOverridesToContainer } from '@open-mercato/shared/modules/overrides'\nimport { createOptimisticLockGuardService } from '@open-mercato/shared/lib/crud/optimistic-lock'\nimport { getAllOptimisticLockReaders } from '@open-mercato/shared/lib/crud/optimistic-lock-store'\nimport { createCommandOptimisticLockGuardService } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isTenantDataEncryptionEnabled } from '../encryption/toggles'\nimport { createLogger } from '../logger'\n\nconst logger = createLogger('shared').child({ component: 'di' })\n\ntype DynamicCradle = Record<string, any>\n\nexport type AppContainer = AwilixContainer<DynamicCradle>\nexport type DiRegistrar = (container: AppContainer) => void\nexport type AppDiRegistrar = (container: AppContainer) => void | Promise<void>\n\n// Registration pattern for publishable packages\n// Use globalThis to survive tsx/esbuild module duplication issue where the same\n// file can be loaded as multiple module instances when mixing dynamic and static imports\nconst GLOBAL_KEY = '__openMercatoDiRegistrars__'\nconst APP_DI_REGISTRAR_KEY = '__openMercatoAppDiRegistrar__'\nconst APP_DI_LOAD_WARNING_KEY = '__openMercatoAppDiLoadWarningEmitted__'\nconst APP_DI_REGISTER_WARNING_KEY = '__openMercatoAppDiRegisterWarningEmitted__'\n// Set once the legacy `@/di` fallback proves the specifier is unresolvable in this process.\n// Worker/CLI processes run against built package output where the app's `@/` alias does not\n// exist, so retrying the import per request container only repeats a failed module resolution\n// (and its log line) once per job.\nconst APP_DI_MODULE_UNRESOLVABLE_KEY = '__openMercatoAppDiModuleUnresolvable__'\n// Phase 5 \u2014 process-scoped bootstrap cache. The cache/event-bus/encryption\n// services bootstrap() creates are inherently process-scoped (they hold\n// state across requests). Caching them on globalThis after the first\n// successful bootstrap call lets every subsequent request skip the\n// `await bootstrap(container)` body and just re-register the cached\n// instances. Same globalThis pattern as registerDiRegistrars so HMR\n// keeps working.\nconst BOOTSTRAP_CACHE_KEY = '__openMercatoBootstrapCache__'\nconst ENCRYPTION_ENABLED_KEY = '__openMercatoEncryptionEnabledCache__'\n\nconst BOOTSTRAP_CACHE_KEYS = [\n 'cache',\n 'eventBus',\n 'kmsService',\n 'tenantEncryptionService',\n 'rateLimiterService',\n 'searchModuleConfigs',\n 'searchIndexer',\n] as const\n\ntype BootstrapCacheEntry = Partial<Record<(typeof BOOTSTRAP_CACHE_KEYS)[number], unknown>>\n\n// Phase 5 is opt-in. Some bootstrap services close over per-request state\n// (e.g. tenantEncryptionService captures the first request's `em.fork`, the\n// event-bus's resolver closes over the first container) so naively replaying\n// them on later requests yields stale references \u2014 observed as a 500 from\n// CRUD list endpoints in `next start`. Default OFF preserves develop's\n// per-request bootstrap. Set `OM_BOOTSTRAP_CACHE=1` to opt in once each\n// cached service is verified safe for cross-request reuse.\nfunction isBootstrapCacheEnabled(): boolean {\n const raw = process.env.OM_BOOTSTRAP_CACHE\n if (raw === undefined) return false\n const normalized = raw.trim().toLowerCase()\n if (!normalized.length) return false\n if (normalized === '0' || normalized === 'off' || normalized === 'false' || normalized === 'no') return false\n return true\n}\n\nfunction getBootstrapCache(): BootstrapCacheEntry | null {\n if (!isBootstrapCacheEnabled()) return null\n const existing = (globalThis as any)[BOOTSTRAP_CACHE_KEY]\n return existing && typeof existing === 'object' ? (existing as BootstrapCacheEntry) : null\n}\n\nfunction setBootstrapCache(entry: BootstrapCacheEntry): void {\n if (!isBootstrapCacheEnabled()) return\n ;(globalThis as any)[BOOTSTRAP_CACHE_KEY] = entry\n}\n\nfunction harvestBootstrapCache(container: AwilixContainer): BootstrapCacheEntry {\n const entry: BootstrapCacheEntry = {}\n for (const key of BOOTSTRAP_CACHE_KEYS) {\n try {\n const value: unknown = container.resolve(key as never)\n if (value !== undefined && value !== null) entry[key] = value\n } catch {\n // not registered \u2014 skip\n }\n }\n return entry\n}\n\n// Caches the STATIC config toggle only. It deliberately does not consult\n// `tenantEncryptionService.isEnabled()`, which ANDs the toggle with the\n// volatile `kms.isHealthy()` \u2014 memoizing that for the process lifetime pinned a\n// transient Vault outage into a permanent \"encryption off\" verdict, so the\n// subscriber was never registered again until a restart (#5948). KMS health is\n// re-checked by the subscriber on every read/write instead.\nfunction getCachedEncryptionConfigured(): boolean {\n const cached = (globalThis as Record<string, unknown>)[ENCRYPTION_ENABLED_KEY]\n if (typeof cached === 'boolean') return cached\n const result = isTenantDataEncryptionEnabled()\n ;(globalThis as Record<string, unknown>)[ENCRYPTION_ENABLED_KEY] = result\n return result\n}\n\nfunction getGlobalRegistrars(): DiRegistrar[] | null {\n return (globalThis as any)[GLOBAL_KEY] ?? null\n}\n\nfunction setGlobalRegistrars(registrars: DiRegistrar[]): void {\n (globalThis as any)[GLOBAL_KEY] = registrars\n}\n\nexport function registerDiRegistrars(registrars: DiRegistrar[]) {\n const existing = getGlobalRegistrars()\n if (existing !== null && process.env.NODE_ENV === 'development') {\n logger.debug('DI registrars re-registered (this may occur during HMR)')\n }\n setGlobalRegistrars(registrars)\n // Force re-bootstrap on HMR \u2014 module subscribers may have changed.\n ;(globalThis as any)[BOOTSTRAP_CACHE_KEY] = null\n ;(globalThis as any)[ENCRYPTION_ENABLED_KEY] = undefined\n // An app that gains a src/di.ts mid-session reloads through here, so the negative\n // resolution result must not outlive the reload.\n ;(globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] = undefined\n}\n\nexport function getDiRegistrars(): DiRegistrar[] {\n const registrars = getGlobalRegistrars()\n if (!registrars) {\n throw new Error('[Bootstrap] DI registrars not registered. Call registerDiRegistrars() at bootstrap.')\n }\n return registrars\n}\n\nfunction getAppDiRegistrar(): AppDiRegistrar | null {\n const registrar = (globalThis as Record<string, unknown>)[APP_DI_REGISTRAR_KEY]\n return typeof registrar === 'function' ? registrar as AppDiRegistrar : null\n}\n\nexport function registerAppDiRegistrar(registrar: AppDiRegistrar | null): void {\n ;(globalThis as Record<string, unknown>)[APP_DI_REGISTRAR_KEY] = registrar\n}\n\n/** Test-only helper to drop process-scoped request-container state. */\nexport function resetBootstrapCache(): void {\n (globalThis as any)[BOOTSTRAP_CACHE_KEY] = null\n ;(globalThis as any)[ENCRYPTION_ENABLED_KEY] = undefined\n ;(globalThis as Record<string, unknown>)[APP_DI_LOAD_WARNING_KEY] = undefined\n ;(globalThis as Record<string, unknown>)[APP_DI_REGISTER_WARNING_KEY] = undefined\n ;(globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] = undefined\n}\n\nfunction isAppDiModuleUnresolvable(): boolean {\n return (globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] === true\n}\n\nfunction markAppDiModuleUnresolvable(): void {\n ;(globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] = true\n}\n\nfunction isAppDiModuleNotFound(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const { code, message } = error as { code?: unknown; message?: unknown }\n const text = typeof message === 'string' ? message : ''\n const moduleNotFound =\n code === 'MODULE_NOT_FOUND'\n || code === 'ERR_MODULE_NOT_FOUND'\n || text.startsWith('Cannot find module')\n || text.startsWith('Cannot find package')\n return moduleNotFound && /(?:module|package) ['\"]@\\/di['\"]/.test(text)\n}\n\nfunction warnAppDiFailureOnce(\n key: typeof APP_DI_LOAD_WARNING_KEY | typeof APP_DI_REGISTER_WARNING_KEY,\n message: string,\n error: unknown,\n): void {\n const globalScope = globalThis as Record<string, unknown>\n if (globalScope[key] === true) return\n globalScope[key] = true\n logger.warn(message, { err: error })\n}\n\nfunction isAwilixResolver(value: unknown): value is Resolver<unknown> {\n return Boolean(value && typeof value === 'object' && typeof (value as { resolve?: unknown }).resolve === 'function')\n}\n\nfunction toAwilixRegistrations(registrations: Record<string, unknown>): Record<string, Resolver<any>> {\n return Object.fromEntries(\n Object.entries(registrations).map(([key, value]) => [\n key,\n isAwilixResolver(value) ? value : asValue(value),\n ]),\n )\n}\n\nexport async function createRequestContainer(): Promise<AppContainer> {\n const diRegistrars = getDiRegistrars()\n const orm = await getOrm()\n // Use a fresh event manager so request-level subscribers (e.g., encryption) don't pile up globally\n const baseEm = (RequestContext.getEntityManager() as any) ?? orm.em\n const em = baseEm.fork({ clear: true, freshEventManager: true, useContext: true }) as unknown as EntityManager\n const container = createContainer<DynamicCradle>({ injectionMode: InjectionMode.CLASSIC })\n // Core registrations\n container.register({\n em: asValue(em),\n queryEngine: asValue(new BasicQueryEngine(em, undefined, () => {\n try { return container.resolve('tenantEncryptionService') as any } catch { return null }\n })),\n dataEngine: asValue(new DefaultDataEngine(em, container as any)),\n commandRegistry: asValue(commandRegistry),\n commandBus: asValue(new CommandBus()),\n // Default OSS optimistic-lock guard. Reads from the global reader store\n // (populated by `makeCrudRoute` auto-registration + any module-DI\n // hand-wired calls to `registerOptimisticLockReaders`). Service is\n // strictly additive: when `OM_OPTIMISTIC_LOCK=off` (or no header is\n // sent) it short-circuits at validateMutation. Module-level di.ts\n // registrations override this default via Awilix replace semantics \u2014\n // see the enterprise `record_locks` module for the canonical override.\n // Spec: .ai/specs/implemented/2026-05-25-oss-optimistic-locking.md\n crudMutationGuardService: asFunction((em: EntityManager) =>\n createOptimisticLockGuardService({\n getEm: () => em,\n readers: getAllOptimisticLockReaders(),\n }),\n ).scoped(),\n // Default OSS command-level optimistic-lock guard, awaited by\n // `enforceCommandOptimisticLockWithGuards` for Command-pattern writes.\n // Header/explicit-token compare only (no `resolveExpected`), so it is\n // behaviourally identical to calling `enforceCommandOptimisticLock`\n // directly. The enterprise `record_locks` module overrides this DI key\n // with a lock-backed `resolveExpected` via Awilix replace semantics.\n // Spec: .ai/specs/enterprise/2026-06-09-record-locks-unified-coverage.md (Phase 0)\n commandOptimisticLockGuardService: asFunction(() =>\n createCommandOptimisticLockGuardService(),\n ).scoped(),\n })\n // Allow modules to override/extend. Fail-open by design (one broken module's\n // di.ts must not take down every request container), but never silently: the\n // module's services would otherwise vanish with no trace until an unrelated\n // Awilix resolution error surfaces much later.\n for (const [registrarIndex, reg] of diRegistrars.entries()) {\n try { reg?.(container) } catch (error) {\n logger.error('Module DI registrar failed', { registrarIndex, err: error })\n }\n }\n // Core bootstrap (cache, event bus, encryption subscriber/KMS, module subscribers)\n // Phase 5 \u2014 process-scoped once-guard. The first request runs the full\n // bootstrap() body; later requests re-register the cached services\n // directly on this request's container without re-importing or\n // re-initializing anything. HMR clears the cache (see\n // registerDiRegistrars). Skippable if a caller already wired eventBus.\n const alreadyBootstrappedOnThisContainer = !!container.registrations?.eventBus\n if (!alreadyBootstrappedOnThisContainer) {\n const cached = getBootstrapCache()\n if (cached) {\n const replay: Record<string, any> = {}\n for (const [key, value] of Object.entries(cached)) {\n if (value !== undefined && value !== null) replay[key] = asValue(value)\n }\n if (Object.keys(replay).length > 0) container.register(replay)\n } else {\n try {\n const { bootstrap } = await import('@open-mercato/core/bootstrap') as any\n if (bootstrap && typeof bootstrap === 'function') {\n await bootstrap(container)\n setBootstrapCache(harvestBootstrapCache(container))\n }\n } catch { /* optional */ }\n }\n }\n // App-level DI override. Scaffolded apps register this callback explicitly\n // from their own bootstrap module so app aliases resolve in app context.\n const appDiRegistrar = getAppDiRegistrar()\n if (appDiRegistrar) {\n try {\n await appDiRegistrar(container)\n } catch (error) {\n logger.error('App-level DI registrar failed', { err: error })\n }\n } else if (!isAppDiModuleUnresolvable()) {\n // Backward-compatible fallback for apps that have not adopted explicit wiring.\n try {\n // @ts-ignore - @/di only exists in app context, not in packages\n const appDi = await import('@/di') as any\n if (appDi?.register) {\n try {\n const maybe = appDi.register(container)\n if (maybe && typeof maybe.then === 'function') await maybe\n } catch (err) {\n warnAppDiFailureOnce(\n APP_DI_REGISTER_WARNING_KEY,\n 'App-level DI override (src/di.ts register()) threw; its registrations are skipped',\n err,\n )\n }\n }\n } catch (err) {\n if (isAppDiModuleNotFound(err)) {\n markAppDiModuleUnresolvable()\n logger.debug('App-level DI override module (@/di) not resolvable; skipping', { err })\n } else {\n warnAppDiFailureOnce(\n APP_DI_LOAD_WARNING_KEY,\n 'App-level DI override module (@/di) failed to load; its registrations are skipped',\n err,\n )\n }\n }\n }\n applyDiOverridesToContainer({\n register: (registrations) => container.register(toAwilixRegistrations(registrations)),\n unregister: (key) => container.register({ [key]: asValue(undefined) }),\n })\n // Ensure tenant encryption subscriber is always registered on the fresh request-scoped EM\n // Phase 5 \u2014 cache the tenant-encryption config toggle for the process\n // lifetime. That toggle does not change at runtime, so reading it once skips\n // a config lookup per request; KMS health is NOT part of this decision.\n try {\n const emForEnc = container.resolve('em') as any\n const tenantEncryptionService = container.hasRegistration('tenantEncryptionService')\n ? (container.resolve('tenantEncryptionService') as any)\n : null\n // The subscriber calls `service.isEnabled()` on every read/write, so a DI\n // override supplying a service without it would throw per operation. Keep\n // the shape check that the old health-probe helper performed.\n const serviceCanReportEnabled = typeof tenantEncryptionService?.isEnabled === 'function'\n if (emForEnc && serviceCanReportEnabled && getCachedEncryptionConfigured()) {\n const { registerTenantEncryptionSubscriber } = await import('@open-mercato/shared/lib/encryption/subscriber')\n registerTenantEncryptionSubscriber(emForEnc, tenantEncryptionService)\n }\n } catch {\n // best-effort; do not block container creation\n }\n return container\n}\ntry {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n require('server-only')\n} catch {\n // allow CLI/generator usage where Next server-only is not present\n}\n"],
5
- "mappings": "AAAA,SAAS,YAAY,iBAAiB,SAA0B,qBAAoC;AACpG,SAAS,sBAAsB;AAC/B,SAAS,cAAc;AAEvB,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,iBAAiB,kBAAkB;AAC5C,SAAS,mCAAmC;AAC5C,SAAS,wCAAwC;AACjD,SAAS,mCAAmC;AAC5C,SAAS,+CAA+C;AACxD,SAAS,qCAAqC;AAC9C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,QAAQ,EAAE,MAAM,EAAE,WAAW,KAAK,CAAC;AAW/D,MAAM,aAAa;AACnB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,8BAA8B;AAKpC,MAAM,iCAAi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SAAS,SAAS;AACtC,cAAI,SAAS,OAAO,MAAM,SAAS,WAAY,OAAM;AAAA,QACvD,SAAS,KAAK;AACZ;AAAA,YACE;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,sBAAsB,GAAG,GAAG;AAC9B,oCAA4B;AAC5B,eAAO,MAAM,gEAAgE,EAAE,IAAI,CAAC;AAAA,MACtF,OAAO;AACL;AAAA,UACE;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,8BAA4B;AAAA,IAC1B,UAAU,CAAC,kBAAkB,UAAU,SAAS,sBAAsB,aAAa,CAAC;AAAA,IACpF,YAAY,CAAC,QAAQ,UAAU,SAAS,EAAE,CAAC,GAAG,GAAG,QAAQ,MAAS,EAAE,CAAC;AAAA,EACvE,CAAC;AAKD,MAAI;AACF,UAAM,WAAW,UAAU,QAAQ,IAAI;AACvC,UAAM,0BAA0B,UAAU,gBAAgB,yBAAyB,IAC9E,UAAU,QAAQ,yBAAyB,IAC5C;AAIJ,UAAM,0BAA0B,OAAO,yBAAyB,cAAc;AAC9E,QAAI,YAAY,2BAA2B,8BAA8B,GAAG;AAC1E,YAAM,EAAE,mCAAmC,IAAI,MAAM,OAAO,gDAAgD;AAC5G,yCAAmC,UAAU,uBAAuB;AAAA,IACtE;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AACA,IAAI;AAEF,UAAQ,aAAa;AACvB,QAAQ;AAER;",
6
- "names": ["em"]
4
+ "sourcesContent": ["import { asFunction, createContainer, asValue, AwilixContainer, InjectionMode, type Resolver } from 'awilix'\nimport { RequestContext } from '@mikro-orm/core'\nimport { getOrm } from '@open-mercato/shared/lib/db/mikro'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { BasicQueryEngine } from '@open-mercato/shared/lib/query/engine'\nimport { DefaultDataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { commandRegistry, CommandBus } from '@open-mercato/shared/lib/commands'\nimport { applyDiOverridesToContainer } from '@open-mercato/shared/modules/overrides'\nimport { createOptimisticLockGuardService } from '@open-mercato/shared/lib/crud/optimistic-lock'\nimport { getAllOptimisticLockReaders } from '@open-mercato/shared/lib/crud/optimistic-lock-store'\nimport { createCommandOptimisticLockGuardService } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isTenantDataEncryptionEnabled } from '../encryption/toggles'\nimport { createLogger } from '../logger'\n\nconst logger = createLogger('shared').child({ component: 'di' })\n\ntype DynamicCradle = Record<string, any>\n\nexport type AppContainer = AwilixContainer<DynamicCradle>\nexport type DiRegistrar = (container: AppContainer) => void\nexport type AppDiRegistrar = (container: AppContainer) => void | Promise<void>\n\n// Registration pattern for publishable packages\n// Use globalThis to survive tsx/esbuild module duplication issue where the same\n// file can be loaded as multiple module instances when mixing dynamic and static imports\nconst GLOBAL_KEY = '__openMercatoDiRegistrars__'\nconst APP_DI_REGISTRAR_KEY = '__openMercatoAppDiRegistrar__'\nconst APP_DI_LOAD_WARNING_KEY = '__openMercatoAppDiLoadWarningEmitted__'\nconst APP_DI_REGISTER_WARNING_KEY = '__openMercatoAppDiRegisterWarningEmitted__'\n// Set once the legacy `@/di` fallback proves the specifier is unresolvable in this process.\n// Worker/CLI processes run against built package output where the app's `@/` alias does not\n// exist, so retrying the import per request container only repeats a failed module resolution\n// (and its log line) once per job.\nconst APP_DI_MODULE_UNRESOLVABLE_KEY = '__openMercatoAppDiModuleUnresolvable__'\n// Phase 5 \u2014 process-scoped bootstrap cache. The cache/event-bus/encryption\n// services bootstrap() creates are inherently process-scoped (they hold\n// state across requests). Caching them on globalThis after the first\n// successful bootstrap call lets every subsequent request skip the\n// `await bootstrap(container)` body and just re-register the cached\n// instances. Same globalThis pattern as registerDiRegistrars so HMR\n// keeps working.\nconst BOOTSTRAP_CACHE_KEY = '__openMercatoBootstrapCache__'\nconst ENCRYPTION_ENABLED_KEY = '__openMercatoEncryptionEnabledCache__'\n\nconst BOOTSTRAP_CACHE_KEYS = [\n 'cache',\n 'eventBus',\n 'kmsService',\n 'tenantEncryptionService',\n 'rateLimiterService',\n 'searchModuleConfigs',\n 'searchIndexer',\n] as const\n\ntype BootstrapCacheEntry = Partial<Record<(typeof BOOTSTRAP_CACHE_KEYS)[number], unknown>>\n\n// Phase 5 is opt-in. Some bootstrap services close over per-request state\n// (e.g. tenantEncryptionService captures the first request's `em.fork`, the\n// event-bus's resolver closes over the first container) so naively replaying\n// them on later requests yields stale references \u2014 observed as a 500 from\n// CRUD list endpoints in `next start`. Default OFF preserves develop's\n// per-request bootstrap. Set `OM_BOOTSTRAP_CACHE=1` to opt in once each\n// cached service is verified safe for cross-request reuse.\nfunction isBootstrapCacheEnabled(): boolean {\n const raw = process.env.OM_BOOTSTRAP_CACHE\n if (raw === undefined) return false\n const normalized = raw.trim().toLowerCase()\n if (!normalized.length) return false\n if (normalized === '0' || normalized === 'off' || normalized === 'false' || normalized === 'no') return false\n return true\n}\n\nfunction getBootstrapCache(): BootstrapCacheEntry | null {\n if (!isBootstrapCacheEnabled()) return null\n const existing = (globalThis as any)[BOOTSTRAP_CACHE_KEY]\n return existing && typeof existing === 'object' ? (existing as BootstrapCacheEntry) : null\n}\n\nfunction setBootstrapCache(entry: BootstrapCacheEntry): void {\n if (!isBootstrapCacheEnabled()) return\n ;(globalThis as any)[BOOTSTRAP_CACHE_KEY] = entry\n}\n\nfunction harvestBootstrapCache(container: AwilixContainer): BootstrapCacheEntry {\n const entry: BootstrapCacheEntry = {}\n for (const key of BOOTSTRAP_CACHE_KEYS) {\n try {\n const value: unknown = container.resolve(key as never)\n if (value !== undefined && value !== null) entry[key] = value\n } catch {\n // not registered \u2014 skip\n }\n }\n return entry\n}\n\n// Caches the STATIC config toggle only. It deliberately does not consult\n// `tenantEncryptionService.isEnabled()`, which ANDs the toggle with the\n// volatile `kms.isHealthy()` \u2014 memoizing that for the process lifetime pinned a\n// transient Vault outage into a permanent \"encryption off\" verdict, so the\n// subscriber was never registered again until a restart (#5948). KMS health is\n// re-checked by the subscriber on every read/write instead.\nfunction getCachedEncryptionConfigured(): boolean {\n const cached = (globalThis as Record<string, unknown>)[ENCRYPTION_ENABLED_KEY]\n if (typeof cached === 'boolean') return cached\n const result = isTenantDataEncryptionEnabled()\n ;(globalThis as Record<string, unknown>)[ENCRYPTION_ENABLED_KEY] = result\n return result\n}\n\nfunction getGlobalRegistrars(): DiRegistrar[] | null {\n return (globalThis as any)[GLOBAL_KEY] ?? null\n}\n\nfunction setGlobalRegistrars(registrars: DiRegistrar[]): void {\n (globalThis as any)[GLOBAL_KEY] = registrars\n}\n\nexport function registerDiRegistrars(registrars: DiRegistrar[]) {\n const existing = getGlobalRegistrars()\n if (existing !== null && process.env.NODE_ENV === 'development') {\n logger.debug('DI registrars re-registered (this may occur during HMR)')\n }\n setGlobalRegistrars(registrars)\n // Force re-bootstrap on HMR \u2014 module subscribers may have changed.\n ;(globalThis as any)[BOOTSTRAP_CACHE_KEY] = null\n ;(globalThis as any)[ENCRYPTION_ENABLED_KEY] = undefined\n // An app that gains a src/di.ts mid-session reloads through here, so the negative\n // resolution result must not outlive the reload.\n ;(globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] = undefined\n}\n\nexport function getDiRegistrars(): DiRegistrar[] {\n const registrars = getGlobalRegistrars()\n if (!registrars) {\n throw new Error('[Bootstrap] DI registrars not registered. Call registerDiRegistrars() at bootstrap.')\n }\n return registrars\n}\n\nfunction getAppDiRegistrar(): AppDiRegistrar | null {\n const registrar = (globalThis as Record<string, unknown>)[APP_DI_REGISTRAR_KEY]\n return typeof registrar === 'function' ? registrar as AppDiRegistrar : null\n}\n\nexport function registerAppDiRegistrar(registrar: AppDiRegistrar | null): void {\n ;(globalThis as Record<string, unknown>)[APP_DI_REGISTRAR_KEY] = registrar\n}\n\n/** Test-only helper to drop process-scoped request-container state. */\nexport function resetBootstrapCache(): void {\n (globalThis as any)[BOOTSTRAP_CACHE_KEY] = null\n ;(globalThis as any)[ENCRYPTION_ENABLED_KEY] = undefined\n ;(globalThis as Record<string, unknown>)[APP_DI_LOAD_WARNING_KEY] = undefined\n ;(globalThis as Record<string, unknown>)[APP_DI_REGISTER_WARNING_KEY] = undefined\n ;(globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] = undefined\n}\n\nfunction isAppDiModuleUnresolvable(): boolean {\n return (globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] === true\n}\n\nfunction markAppDiModuleUnresolvable(): void {\n ;(globalThis as Record<string, unknown>)[APP_DI_MODULE_UNRESOLVABLE_KEY] = true\n}\n\nfunction isAppDiModuleNotFound(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const { code, message } = error as { code?: unknown; message?: unknown }\n const text = typeof message === 'string' ? message : ''\n const moduleNotFound =\n code === 'MODULE_NOT_FOUND'\n || code === 'ERR_MODULE_NOT_FOUND'\n || text.startsWith('Cannot find module')\n || text.startsWith('Cannot find package')\n return moduleNotFound && /(?:module|package) ['\"]@\\/di['\"]/.test(text)\n}\n\nfunction warnAppDiFailureOnce(\n key: typeof APP_DI_LOAD_WARNING_KEY | typeof APP_DI_REGISTER_WARNING_KEY,\n message: string,\n error: unknown,\n): void {\n const globalScope = globalThis as Record<string, unknown>\n if (globalScope[key] === true) return\n globalScope[key] = true\n logger.warn(message, { err: error })\n}\n\nfunction isAwilixResolver(value: unknown): value is Resolver<unknown> {\n return Boolean(value && typeof value === 'object' && typeof (value as { resolve?: unknown }).resolve === 'function')\n}\n\nfunction toAwilixRegistrations(registrations: Record<string, unknown>): Record<string, Resolver<any>> {\n return Object.fromEntries(\n Object.entries(registrations).map(([key, value]) => [\n key,\n isAwilixResolver(value) ? value : asValue(value),\n ]),\n )\n}\n\nexport async function createRequestContainer(): Promise<AppContainer> {\n const diRegistrars = getDiRegistrars()\n const orm = await getOrm()\n // Use a fresh event manager so request-level subscribers (e.g., encryption) don't pile up globally\n const baseEm = (RequestContext.getEntityManager() as any) ?? orm.em\n const em = baseEm.fork({ clear: true, freshEventManager: true, useContext: true }) as unknown as EntityManager\n const container = createContainer<DynamicCradle>({ injectionMode: InjectionMode.CLASSIC })\n // Core registrations\n container.register({\n em: asValue(em),\n queryEngine: asValue(new BasicQueryEngine(em, undefined, () => {\n try { return container.resolve('tenantEncryptionService') as any } catch { return null }\n })),\n dataEngine: asValue(new DefaultDataEngine(em, container as any)),\n commandRegistry: asValue(commandRegistry),\n commandBus: asValue(new CommandBus()),\n // Default OSS optimistic-lock guard. Reads from the global reader store\n // (populated by `makeCrudRoute` auto-registration + any module-DI\n // hand-wired calls to `registerOptimisticLockReaders`). Service is\n // strictly additive: when `OM_OPTIMISTIC_LOCK=off` (or no header is\n // sent) it short-circuits at validateMutation. Module-level di.ts\n // registrations override this default via Awilix replace semantics \u2014\n // see the enterprise `record_locks` module for the canonical override.\n // Spec: .ai/specs/implemented/2026-05-25-oss-optimistic-locking.md\n // `.proxy()` is load-bearing, not stylistic. The container runs in CLASSIC\n // injection mode, where Awilix resolves dependencies by parsing PARAMETER\n // NAMES out of the function source. A bundler that renames `em` to `em2` \u2014\n // Turbopack does, on a scope collision \u2014 makes Awilix look up a registration\n // that does not exist, and `resolveCrudMutationGuardService` swallows the\n // AwilixResolutionError and returns null, so `bridgeLegacyGuard` silently\n // drops the guard and every mutation runs with optimistic locking NOT\n // enforced. Reading `cradle.em` resolves by property name, which survives\n // mangling. Pinned by `di-injection-mode.test.ts`.\n crudMutationGuardService: asFunction((cradle: { em: EntityManager }) =>\n createOptimisticLockGuardService({\n getEm: () => cradle.em,\n readers: getAllOptimisticLockReaders(),\n }),\n ).scoped().proxy(),\n // Default OSS command-level optimistic-lock guard, awaited by\n // `enforceCommandOptimisticLockWithGuards` for Command-pattern writes.\n // Header/explicit-token compare only (no `resolveExpected`), so it is\n // behaviourally identical to calling `enforceCommandOptimisticLock`\n // directly. The enterprise `record_locks` module overrides this DI key\n // with a lock-backed `resolveExpected` via Awilix replace semantics.\n // Spec: .ai/specs/enterprise/2026-06-09-record-locks-unified-coverage.md (Phase 0)\n commandOptimisticLockGuardService: asFunction(() =>\n createCommandOptimisticLockGuardService(),\n ).scoped(),\n })\n // Allow modules to override/extend. Fail-open by design (one broken module's\n // di.ts must not take down every request container), but never silently: the\n // module's services would otherwise vanish with no trace until an unrelated\n // Awilix resolution error surfaces much later.\n for (const [registrarIndex, reg] of diRegistrars.entries()) {\n try { reg?.(container) } catch (error) {\n logger.error('Module DI registrar failed', { registrarIndex, err: error })\n }\n }\n // Core bootstrap (cache, event bus, encryption subscriber/KMS, module subscribers)\n // Phase 5 \u2014 process-scoped once-guard. The first request runs the full\n // bootstrap() body; later requests re-register the cached services\n // directly on this request's container without re-importing or\n // re-initializing anything. HMR clears the cache (see\n // registerDiRegistrars). Skippable if a caller already wired eventBus.\n const alreadyBootstrappedOnThisContainer = !!container.registrations?.eventBus\n if (!alreadyBootstrappedOnThisContainer) {\n const cached = getBootstrapCache()\n if (cached) {\n const replay: Record<string, any> = {}\n for (const [key, value] of Object.entries(cached)) {\n if (value !== undefined && value !== null) replay[key] = asValue(value)\n }\n if (Object.keys(replay).length > 0) container.register(replay)\n } else {\n try {\n const { bootstrap } = await import('@open-mercato/core/bootstrap') as any\n if (bootstrap && typeof bootstrap === 'function') {\n await bootstrap(container)\n setBootstrapCache(harvestBootstrapCache(container))\n }\n } catch { /* optional */ }\n }\n }\n // App-level DI override. Scaffolded apps register this callback explicitly\n // from their own bootstrap module so app aliases resolve in app context.\n const appDiRegistrar = getAppDiRegistrar()\n if (appDiRegistrar) {\n try {\n await appDiRegistrar(container)\n } catch (error) {\n logger.error('App-level DI registrar failed', { err: error })\n }\n } else if (!isAppDiModuleUnresolvable()) {\n // Backward-compatible fallback for apps that have not adopted explicit wiring.\n try {\n // @ts-ignore - @/di only exists in app context, not in packages\n const appDi = await import('@/di') as any\n if (appDi?.register) {\n try {\n const maybe = appDi.register(container)\n if (maybe && typeof maybe.then === 'function') await maybe\n } catch (err) {\n warnAppDiFailureOnce(\n APP_DI_REGISTER_WARNING_KEY,\n 'App-level DI override (src/di.ts register()) threw; its registrations are skipped',\n err,\n )\n }\n }\n } catch (err) {\n if (isAppDiModuleNotFound(err)) {\n markAppDiModuleUnresolvable()\n logger.debug('App-level DI override module (@/di) not resolvable; skipping', { err })\n } else {\n warnAppDiFailureOnce(\n APP_DI_LOAD_WARNING_KEY,\n 'App-level DI override module (@/di) failed to load; its registrations are skipped',\n err,\n )\n }\n }\n }\n applyDiOverridesToContainer({\n register: (registrations) => container.register(toAwilixRegistrations(registrations)),\n unregister: (key) => container.register({ [key]: asValue(undefined) }),\n })\n // Ensure tenant encryption subscriber is always registered on the fresh request-scoped EM\n // Phase 5 \u2014 cache the tenant-encryption config toggle for the process\n // lifetime. That toggle does not change at runtime, so reading it once skips\n // a config lookup per request; KMS health is NOT part of this decision.\n try {\n const emForEnc = container.resolve('em') as any\n const tenantEncryptionService = container.hasRegistration('tenantEncryptionService')\n ? (container.resolve('tenantEncryptionService') as any)\n : null\n // The subscriber calls `service.isEnabled()` on every read/write, so a DI\n // override supplying a service without it would throw per operation. Keep\n // the shape check that the old health-probe helper performed.\n const serviceCanReportEnabled = typeof tenantEncryptionService?.isEnabled === 'function'\n if (emForEnc && serviceCanReportEnabled && getCachedEncryptionConfigured()) {\n const { registerTenantEncryptionSubscriber } = await import('@open-mercato/shared/lib/encryption/subscriber')\n registerTenantEncryptionSubscriber(emForEnc, tenantEncryptionService)\n }\n } catch {\n // best-effort; do not block container creation\n }\n return container\n}\ntry {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n require('server-only')\n} catch {\n // allow CLI/generator usage where Next server-only is not present\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY,iBAAiB,SAA0B,qBAAoC;AACpG,SAAS,sBAAsB;AAC/B,SAAS,cAAc;AAEvB,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,iBAAiB,kBAAk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AAAA,IACtE;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AACA,IAAI;AAEF,UAAQ,aAAa;AACvB,QAAQ;AAER;",
6
+ "names": []
7
7
  }
@@ -1,4 +1,4 @@
1
- const APP_VERSION = "0.8.1-develop.7241.1.fad7b2ce2a";
1
+ const APP_VERSION = "0.8.1-develop.7254.1.ab24f26208";
2
2
  const appVersion = APP_VERSION;
3
3
  export {
4
4
  APP_VERSION,
@@ -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.8.1-develop.7241.1.fad7b2ce2a';\nexport const appVersion = APP_VERSION;\n"],
4
+ "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.8.1-develop.7254.1.ab24f26208';\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.8.1-develop.7241.1.fad7b2ce2a",
3
+ "version": "0.8.1-develop.7254.1.ab24f26208",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -117,7 +117,7 @@
117
117
  "@mikro-orm/core": "^7.1.14",
118
118
  "@mikro-orm/decorators": "^7.1.14",
119
119
  "@mikro-orm/postgresql": "^7.1.14",
120
- "@open-mercato/cache": "0.8.1-develop.7241.1.fad7b2ce2a",
120
+ "@open-mercato/cache": "0.8.1-develop.7254.1.ab24f26208",
121
121
  "@types/html-to-text": "^9.0.4",
122
122
  "@types/sanitize-html": "^2.16.1",
123
123
  "dotenv": "^17.4.2",
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Awilix resolves CLASSIC-mode dependencies by parsing PARAMETER NAMES out of the
3
+ * function source (`packages/shared/src/lib/di/container.ts` creates the container
4
+ * with `InjectionMode.CLASSIC`). Any bundler that renames identifiers therefore
5
+ * breaks resolution: Turbopack renamed `em` to `em2` in a dev chunk and Awilix
6
+ * looked up a registration that does not exist.
7
+ *
8
+ * That failure is silent where it matters most. `resolveCrudMutationGuardService`
9
+ * catches the AwilixResolutionError and returns null, `bridgeLegacyGuard` returns
10
+ * null in turn, and the mutation proceeds with optimistic locking — and the
11
+ * enterprise record-lock 409 layered on top of it — NOT enforced. The write still
12
+ * answers 201, so nothing surfaces except a warning line.
13
+ *
14
+ * `.proxy()` makes a registration read its dependencies as PROPERTIES of the
15
+ * cradle (`cradle.em`), and property names survive mangling. This guard pins that
16
+ * every `asFunction` registration which takes an argument opts into it.
17
+ */
18
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
19
+ import path from 'node:path'
20
+
21
+ const repoRoot = path.resolve(__dirname, '../../../../../..')
22
+ const scanRoots = ['packages', 'apps'].map((dir) => path.join(repoRoot, dir))
23
+
24
+ function collectDiFiles(dir: string, out: string[]): void {
25
+ let entries: string[]
26
+ try {
27
+ entries = readdirSync(dir)
28
+ } catch {
29
+ return
30
+ }
31
+ for (const entry of entries) {
32
+ if (entry === 'node_modules' || entry === 'dist' || entry === '.next' || entry === '.mercato') continue
33
+ const full = path.join(dir, entry)
34
+ let isDir = false
35
+ try {
36
+ isDir = statSync(full).isDirectory()
37
+ } catch {
38
+ continue
39
+ }
40
+ if (isDir) {
41
+ collectDiFiles(full, out)
42
+ } else if (entry === 'di.ts' || entry === 'container.ts') {
43
+ out.push(full)
44
+ }
45
+ }
46
+ }
47
+
48
+ const diFiles: string[] = []
49
+ for (const root of scanRoots) collectDiFiles(root, diFiles)
50
+
51
+ const toRepoRelative = (file: string) => path.relative(repoRoot, file)
52
+
53
+ /**
54
+ * Does this `asFunction(...)` body declare a parameter?
55
+ *
56
+ * Only INLINE function expressions can be judged statically — an arrow or a
57
+ * `function` expression written at the registration. A bare reference
58
+ * (`asFunction(createThing)`) is deliberately skipped: its signature lives in
59
+ * another module, and guessing would produce exactly the false positive this
60
+ * comment replaced.
61
+ */
62
+ function declaresParameter(chunk: string): boolean {
63
+ const body = chunk.replace(/^\s*/, '')
64
+ if (body.startsWith('(')) {
65
+ return !/^\(\s*\)/.test(body)
66
+ }
67
+ const fn = body.match(/^(?:async\s+)?function\s*[A-Za-z0-9_$]*\s*\(([^)]*)\)/)
68
+ if (fn) return fn[1].trim().length > 0
69
+ return false
70
+ }
71
+
72
+ function stripComments(source: string): string {
73
+ return source.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/\/\/[^\n]*/g, ' ')
74
+ }
75
+
76
+ describe('Awilix registrations survive identifier mangling', () => {
77
+ it('scans the whole workspace, not a truncated slice of it', () => {
78
+ // A floor, because the readdir above swallows its errors: without one, a scan
79
+ // that collapsed to nothing would report green and the guard would pass vacuously.
80
+ expect(diFiles.length).toBeGreaterThan(20)
81
+ })
82
+
83
+ it('has no argument-taking asFunction registration that skips .proxy()', () => {
84
+ const offenders: string[] = []
85
+
86
+ for (const file of diFiles) {
87
+ const source = stripComments(readFileSync(file, 'utf8'))
88
+ // Split on the registration boundary so each `asFunction(...)` is checked
89
+ // against the `.proxy()` that belongs to it, not one later in the file.
90
+ const chunks = source.split(/asFunction\(/).slice(1)
91
+ for (const chunk of chunks) {
92
+ if (!declaresParameter(chunk)) continue
93
+ // Chunks are split at each `asFunction(`, so the only `.proxy()` a chunk
94
+ // can contain is the one chained onto its own registration.
95
+ if (!/\.proxy\(\)/.test(chunk)) {
96
+ offenders.push(toRepoRelative(file))
97
+ }
98
+ }
99
+ }
100
+
101
+ expect(Array.from(new Set(offenders))).toEqual([])
102
+ })
103
+ })
@@ -224,12 +224,21 @@ export async function createRequestContainer(): Promise<AppContainer> {
224
224
  // registrations override this default via Awilix replace semantics —
225
225
  // see the enterprise `record_locks` module for the canonical override.
226
226
  // Spec: .ai/specs/implemented/2026-05-25-oss-optimistic-locking.md
227
- crudMutationGuardService: asFunction((em: EntityManager) =>
227
+ // `.proxy()` is load-bearing, not stylistic. The container runs in CLASSIC
228
+ // injection mode, where Awilix resolves dependencies by parsing PARAMETER
229
+ // NAMES out of the function source. A bundler that renames `em` to `em2` —
230
+ // Turbopack does, on a scope collision — makes Awilix look up a registration
231
+ // that does not exist, and `resolveCrudMutationGuardService` swallows the
232
+ // AwilixResolutionError and returns null, so `bridgeLegacyGuard` silently
233
+ // drops the guard and every mutation runs with optimistic locking NOT
234
+ // enforced. Reading `cradle.em` resolves by property name, which survives
235
+ // mangling. Pinned by `di-injection-mode.test.ts`.
236
+ crudMutationGuardService: asFunction((cradle: { em: EntityManager }) =>
228
237
  createOptimisticLockGuardService({
229
- getEm: () => em,
238
+ getEm: () => cradle.em,
230
239
  readers: getAllOptimisticLockReaders(),
231
240
  }),
232
- ).scoped(),
241
+ ).scoped().proxy(),
233
242
  // Default OSS command-level optimistic-lock guard, awaited by
234
243
  // `enforceCommandOptimisticLockWithGuards` for Command-pattern writes.
235
244
  // Header/explicit-token compare only (no `resolveExpected`), so it is