@open-mercato/shared 0.8.1-develop.7454.1.010095490f → 0.8.1-develop.7455.1.8f7e53badb
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/dist/lib/bootstrap/factory.js +4 -3
- package/dist/lib/bootstrap/factory.js.map +2 -2
- package/dist/lib/commands/command-bus.js +45 -13
- package/dist/lib/commands/command-bus.js.map +2 -2
- package/dist/lib/commands/types.js.map +2 -2
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/dist/modules/widgets/injection-loader.js +14 -3
- package/dist/modules/widgets/injection-loader.js.map +2 -2
- package/package.json +2 -2
- package/src/lib/bootstrap/__tests__/factory.test.ts +18 -6
- package/src/lib/bootstrap/factory.ts +8 -3
- package/src/lib/bootstrap/types.ts +5 -1
- package/src/lib/commands/__tests__/command-bus.test.ts +100 -1
- package/src/lib/commands/command-bus.ts +42 -10
- package/src/lib/commands/command-interceptor.ts +4 -0
- package/src/lib/commands/types.ts +14 -0
- package/src/lib/encryption/__tests__/tenantDataEncryptionService.test.ts +23 -0
- package/src/modules/widgets/__tests__/injection-loader.partitioned-registration.test.ts +78 -0
- package/src/modules/widgets/injection-loader.ts +33 -3
|
@@ -297,6 +297,8 @@ export class CommandBus {
|
|
|
297
297
|
auth: baseOptions.ctx.auth ?? null,
|
|
298
298
|
selectedOrganizationId: baseOptions.ctx.selectedOrganizationId ?? baseOptions.ctx.auth?.orgId ?? null,
|
|
299
299
|
container: baseOptions.ctx.container,
|
|
300
|
+
organizationScope: baseOptions.ctx.organizationScope ?? null,
|
|
301
|
+
request: baseOptions.ctx.request ?? null,
|
|
300
302
|
}
|
|
301
303
|
const beforeResult = await runCommandInterceptorsBefore(
|
|
302
304
|
allInterceptors, commandId, baseOptions.input, interceptorCtx, resolvedUserFeatures,
|
|
@@ -338,16 +340,40 @@ export class CommandBus {
|
|
|
338
340
|
}
|
|
339
341
|
|
|
340
342
|
const executeCore = async (coreOptions: CommandExecutionOptions<TInput>) => {
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
+
const snapshots: { before?: unknown } = {}
|
|
344
|
+
let executionOptions = coreOptions
|
|
345
|
+
if (handler.prepareSnapshotInsideTransaction && handler.prepare) {
|
|
346
|
+
const prepare = handler.prepare
|
|
347
|
+
const originalCtx = coreOptions.ctx
|
|
348
|
+
const originalBeforeTransactionalWrite = originalCtx.beforeTransactionalWrite
|
|
349
|
+
let prepared = false
|
|
350
|
+
let transactionalCtx: CommandRuntimeContext
|
|
351
|
+
transactionalCtx = {
|
|
352
|
+
...originalCtx,
|
|
353
|
+
beforeTransactionalWrite: async (em, input) => {
|
|
354
|
+
await originalBeforeTransactionalWrite?.(em, input)
|
|
355
|
+
if (prepared) return
|
|
356
|
+
Object.assign(
|
|
357
|
+
snapshots,
|
|
358
|
+
(await prepare(coreOptions.input, { ...transactionalCtx, transactionalEm: em })) ?? {},
|
|
359
|
+
)
|
|
360
|
+
prepared = true
|
|
361
|
+
},
|
|
362
|
+
}
|
|
363
|
+
executionOptions = { ...coreOptions, ctx: transactionalCtx }
|
|
364
|
+
} else {
|
|
365
|
+
Object.assign(snapshots, await this.prepareSnapshots(handler, coreOptions))
|
|
366
|
+
}
|
|
367
|
+
effectiveOptions = executionOptions
|
|
368
|
+
const sourceLog = executionOptions.redoLogEntry ?? null
|
|
343
369
|
const result =
|
|
344
370
|
sourceLog && typeof handler.redo === 'function'
|
|
345
|
-
? await handler.redo({ input:
|
|
346
|
-
: await handler.execute(
|
|
347
|
-
const afterSnapshot = await this.captureAfter(handler,
|
|
371
|
+
? await handler.redo({ input: executionOptions.input, ctx: executionOptions.ctx, logEntry: sourceLog })
|
|
372
|
+
: await handler.execute(executionOptions.input, executionOptions.ctx)
|
|
373
|
+
const afterSnapshot = await this.captureAfter(handler, executionOptions, result)
|
|
348
374
|
const snapshotsWithAfter = { ...snapshots, after: afterSnapshot }
|
|
349
|
-
const logMeta = await this.buildLog(handler,
|
|
350
|
-
let mergedMeta = this.mergeMetadata(
|
|
375
|
+
const logMeta = await this.buildLog(handler, executionOptions, result, snapshotsWithAfter)
|
|
376
|
+
let mergedMeta = this.mergeMetadata(executionOptions.metadata, logMeta)
|
|
351
377
|
// Interceptors opt into audit-log enrichment with a reserved `logContext` key rather
|
|
352
378
|
// than the generic `context` one, so the metadata an interceptor already passes to its
|
|
353
379
|
// own afterExecute hook is never silently promoted into audit storage.
|
|
@@ -362,7 +388,7 @@ export class CommandBus {
|
|
|
362
388
|
...logContextRecord,
|
|
363
389
|
}
|
|
364
390
|
}
|
|
365
|
-
const baseContext = asRecord(
|
|
391
|
+
const baseContext = asRecord(executionOptions.metadata?.context) ?? {}
|
|
366
392
|
const logMetaContext = asRecord(logMeta?.context) ?? {}
|
|
367
393
|
if (Object.keys(interceptorContextMerged).length > 0 || Object.keys(baseContext).length > 0 || Object.keys(logMetaContext).length > 0) {
|
|
368
394
|
mergedMeta = mergedMeta ?? {}
|
|
@@ -376,7 +402,7 @@ export class CommandBus {
|
|
|
376
402
|
if (undoable && mergedMeta?.replayable !== false) {
|
|
377
403
|
mergedMeta = mergedMeta ?? {}
|
|
378
404
|
if (!mergedMeta.undoToken) mergedMeta.undoToken = defaultUndoToken()
|
|
379
|
-
if (mergedMeta.actorUserId === undefined) mergedMeta.actorUserId =
|
|
405
|
+
if (mergedMeta.actorUserId === undefined) mergedMeta.actorUserId = executionOptions.ctx.auth?.sub ?? null
|
|
380
406
|
} else if (mergedMeta?.replayable === false) {
|
|
381
407
|
mergedMeta.undoToken = null
|
|
382
408
|
}
|
|
@@ -405,7 +431,7 @@ export class CommandBus {
|
|
|
405
431
|
if (inferred) mergedMeta.changes = inferred
|
|
406
432
|
}
|
|
407
433
|
}
|
|
408
|
-
const logEntry = await this.persistLog(commandId,
|
|
434
|
+
const logEntry = await this.persistLog(commandId, executionOptions, mergedMeta)
|
|
409
435
|
return { result, mergedMeta, logEntry }
|
|
410
436
|
}
|
|
411
437
|
|
|
@@ -474,6 +500,8 @@ export class CommandBus {
|
|
|
474
500
|
auth: effectiveOptions.ctx.auth ?? null,
|
|
475
501
|
selectedOrganizationId: effectiveOptions.ctx.selectedOrganizationId ?? effectiveOptions.ctx.auth?.orgId ?? null,
|
|
476
502
|
container: effectiveOptions.ctx.container,
|
|
503
|
+
organizationScope: effectiveOptions.ctx.organizationScope ?? null,
|
|
504
|
+
request: effectiveOptions.ctx.request ?? null,
|
|
477
505
|
}
|
|
478
506
|
const afterResult = await runCommandInterceptorsAfter(
|
|
479
507
|
allInterceptors, commandId, effectiveOptions.input, result, interceptorCtx,
|
|
@@ -545,6 +573,8 @@ export class CommandBus {
|
|
|
545
573
|
auth: replayCtx.auth ?? null,
|
|
546
574
|
selectedOrganizationId: replayCtx.selectedOrganizationId ?? replayCtx.auth?.orgId ?? null,
|
|
547
575
|
container: replayCtx.container,
|
|
576
|
+
organizationScope: replayCtx.organizationScope ?? null,
|
|
577
|
+
request: replayCtx.request ?? null,
|
|
548
578
|
}
|
|
549
579
|
const beforeResult = await runCommandInterceptorsBeforeUndo(
|
|
550
580
|
allInterceptors, log.commandId, undoCtx, interceptorCtx, resolvedUserFeatures,
|
|
@@ -659,6 +689,8 @@ export class CommandBus {
|
|
|
659
689
|
auth: ctx.auth ?? null,
|
|
660
690
|
selectedOrganizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,
|
|
661
691
|
container: ctx.container,
|
|
692
|
+
organizationScope: ctx.organizationScope ?? null,
|
|
693
|
+
request: ctx.request ?? null,
|
|
662
694
|
}
|
|
663
695
|
await runCommandInterceptorsAfterUndo(
|
|
664
696
|
allInterceptors, log.commandId, undoCtx, interceptorCtx,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AwilixContainer } from 'awilix'
|
|
2
|
+
import type { OrganizationScope } from '@open-mercato/shared/lib/auth/principal-service'
|
|
2
3
|
import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
|
|
3
4
|
|
|
4
5
|
export interface CommandInterceptor {
|
|
@@ -47,8 +48,11 @@ export interface CommandInterceptorContext {
|
|
|
47
48
|
auth: AuthContext | null
|
|
48
49
|
/** Selected organization ID */
|
|
49
50
|
selectedOrganizationId: string | null
|
|
51
|
+
organizationScope?: OrganizationScope | null
|
|
50
52
|
/** DI container (read-only usage recommended) */
|
|
51
53
|
container: AwilixContainer
|
|
54
|
+
/** Original request, when the command was called through HTTP. */
|
|
55
|
+
request?: Request | null
|
|
52
56
|
/** Metadata passthrough from beforeExecute to afterExecute (or beforeUndo to afterUndo) */
|
|
53
57
|
metadata?: Record<string, unknown>
|
|
54
58
|
}
|
|
@@ -67,6 +67,14 @@ export type CommandRuntimeContext = {
|
|
|
67
67
|
* surrounding work as a single atomic, single-locked operation.
|
|
68
68
|
*/
|
|
69
69
|
transactionalEm?: EntityManager
|
|
70
|
+
/**
|
|
71
|
+
* Optional server-side guard that supported command handlers invoke after
|
|
72
|
+
* opening their write transaction and before reading or mutating records.
|
|
73
|
+
* The guard receives that same transaction-bound EntityManager and, when the
|
|
74
|
+
* handler provides it, the final input after command interceptors. The input
|
|
75
|
+
* stays optional so existing handlers and callers remain source-compatible.
|
|
76
|
+
*/
|
|
77
|
+
beforeTransactionalWrite?: (em: EntityManager, input?: unknown) => Promise<void>
|
|
70
78
|
/**
|
|
71
79
|
* Identifies the owner of an already-active {@link transactionalEm} lifetime.
|
|
72
80
|
* Atomic replay accepts an ambient EntityManager only when this is the exact
|
|
@@ -243,6 +251,12 @@ export interface CommandHandler<TInput = unknown, TResult = unknown> {
|
|
|
243
251
|
*/
|
|
244
252
|
readonly outputSchema?: ZodTypeAny
|
|
245
253
|
prepare?(input: TInput, ctx: CommandRuntimeContext): Promise<{ before?: unknown } | null> | { before?: unknown } | null
|
|
254
|
+
/**
|
|
255
|
+
* Opt in to taking the undo snapshot inside the write transaction. The bus
|
|
256
|
+
* defers `prepare()` into `ctx.beforeTransactionalWrite`, after the handler's
|
|
257
|
+
* transaction guard and before its first read or mutation.
|
|
258
|
+
*/
|
|
259
|
+
readonly prepareSnapshotInsideTransaction?: boolean
|
|
246
260
|
execute(input: TInput, ctx: CommandRuntimeContext): Promise<TResult> | TResult
|
|
247
261
|
buildLog?(args: CommandLogBuilderArgs<TInput, TResult>): Promise<CommandLogMetadata | null | undefined> | CommandLogMetadata | null | undefined
|
|
248
262
|
captureAfter?(input: TInput, result: TResult, ctx: CommandRuntimeContext): Promise<unknown> | unknown
|
|
@@ -883,3 +883,26 @@ describe('TenantDataEncryptionService map read failures (issue #6334)', () => {
|
|
|
883
883
|
expect(execute).toHaveBeenCalledTimes(2)
|
|
884
884
|
})
|
|
885
885
|
})
|
|
886
|
+
|
|
887
|
+
describe('TenantDataEncryptionService transaction-aware map reads', () => {
|
|
888
|
+
it('prefers the EntityManager executor over the bare connection', async () => {
|
|
889
|
+
const entityId = 'test:transaction_aware_map_read'
|
|
890
|
+
const execute = jest.fn(async () => [{
|
|
891
|
+
entity_id: entityId,
|
|
892
|
+
fields_json: [{ field: 'display_name' }],
|
|
893
|
+
}])
|
|
894
|
+
const bareExecute = jest.fn(async () => {
|
|
895
|
+
throw new Error('bare connection must not be used')
|
|
896
|
+
})
|
|
897
|
+
const service = new TenantDataEncryptionService({
|
|
898
|
+
execute,
|
|
899
|
+
getConnection: () => ({ execute: bareExecute }),
|
|
900
|
+
} as never)
|
|
901
|
+
jest.spyOn(service, 'isEnabled').mockReturnValue(true)
|
|
902
|
+
|
|
903
|
+
await expect(service.getEncryptedFieldNames(entityId, 'tenant-transaction', 'org-transaction'))
|
|
904
|
+
.resolves.toEqual(['display_name'])
|
|
905
|
+
expect(execute).toHaveBeenCalled()
|
|
906
|
+
expect(bareExecute).not.toHaveBeenCalled()
|
|
907
|
+
})
|
|
908
|
+
})
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression coverage for the partitioned-bootstrap registry contract.
|
|
3
|
+
*
|
|
4
|
+
* A Node process can run more than one bootstrap partition: the API-only one
|
|
5
|
+
* (`skipCoreInjectionWidgets: true`) and the full page one. Two invariants have to hold
|
|
6
|
+
* together, and skipping registration outright only satisfied the first:
|
|
7
|
+
*
|
|
8
|
+
* 1. the partition that registers second must never shrink the registry the first published;
|
|
9
|
+
* 2. an API-only process must still be able to READ the registry, because module API routes
|
|
10
|
+
* resolve widget contributions on the request path.
|
|
11
|
+
*/
|
|
12
|
+
import { describe, it, expect, beforeEach, jest } from '@jest/globals'
|
|
13
|
+
import type { ModuleInjectionWidgetEntry } from '@open-mercato/shared/modules/registry'
|
|
14
|
+
|
|
15
|
+
const GLOBAL_INJECTION_WIDGETS_KEY = '__openMercatoCoreInjectionWidgetEntries__'
|
|
16
|
+
|
|
17
|
+
function entry(key: string): ModuleInjectionWidgetEntry {
|
|
18
|
+
return { moduleId: key.split(':')[0]!, key, source: 'package', widgetId: key, loader: async () => ({}) as never }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Loader = typeof import('@open-mercato/shared/modules/widgets/injection-loader')
|
|
22
|
+
|
|
23
|
+
function freshLoader(): Loader {
|
|
24
|
+
delete (globalThis as Record<string, unknown>)[GLOBAL_INJECTION_WIDGETS_KEY]
|
|
25
|
+
let loader!: Loader
|
|
26
|
+
jest.isolateModules(() => {
|
|
27
|
+
loader = require('@open-mercato/shared/modules/widgets/injection-loader') as Loader
|
|
28
|
+
})
|
|
29
|
+
return loader
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('core injection widget registration modes', () => {
|
|
33
|
+
beforeEach(() => {
|
|
34
|
+
delete (globalThis as Record<string, unknown>)[GLOBAL_INJECTION_WIDGETS_KEY]
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('replaces the registry by default', () => {
|
|
38
|
+
const loader = freshLoader()
|
|
39
|
+
loader.registerCoreInjectionWidgets([entry('a:one'), entry('b:two')])
|
|
40
|
+
loader.registerCoreInjectionWidgets([entry('a:one')])
|
|
41
|
+
|
|
42
|
+
expect(loader.getCoreInjectionWidgets().map((it) => it.key)).toEqual(['a:one'])
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('populates an unregistered registry in merge mode instead of leaving it throwing', () => {
|
|
46
|
+
const loader = freshLoader()
|
|
47
|
+
expect(() => loader.getCoreInjectionWidgets()).toThrow(/not registered/)
|
|
48
|
+
|
|
49
|
+
loader.registerCoreInjectionWidgets([entry('a:one')], { mode: 'merge' })
|
|
50
|
+
|
|
51
|
+
expect(loader.getCoreInjectionWidgets().map((it) => it.key)).toEqual(['a:one'])
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('never shrinks a registry a fuller partition already published', () => {
|
|
55
|
+
const loader = freshLoader()
|
|
56
|
+
loader.registerCoreInjectionWidgets([entry('a:one'), entry('b:two'), entry('c:three')])
|
|
57
|
+
loader.registerCoreInjectionWidgets([entry('a:one')], { mode: 'merge' })
|
|
58
|
+
|
|
59
|
+
expect(loader.getCoreInjectionWidgets().map((it) => it.key)).toEqual(['a:one', 'b:two', 'c:three'])
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('adds only the entries the registry does not already carry', () => {
|
|
63
|
+
const loader = freshLoader()
|
|
64
|
+
loader.registerCoreInjectionWidgets([entry('a:one')])
|
|
65
|
+
loader.registerCoreInjectionWidgets([entry('a:one'), entry('d:four')], { mode: 'merge' })
|
|
66
|
+
|
|
67
|
+
expect(loader.getCoreInjectionWidgets().map((it) => it.key)).toEqual(['a:one', 'd:four'])
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it('leaves an unregistered registry untouched when it has nothing to contribute', () => {
|
|
71
|
+
const loader = freshLoader()
|
|
72
|
+
loader.registerCoreInjectionWidgets([], { mode: 'merge' })
|
|
73
|
+
|
|
74
|
+
// Publishing an empty array here would turn the loud "not registered" bootstrap error into
|
|
75
|
+
// silently missing contributions on every request.
|
|
76
|
+
expect(() => loader.getCoreInjectionWidgets()).toThrow(/not registered/)
|
|
77
|
+
})
|
|
78
|
+
})
|
|
@@ -141,11 +141,41 @@ function notifyInjectionRegistryChanged() {
|
|
|
141
141
|
}))
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
export
|
|
145
|
-
|
|
144
|
+
export type RegisterCoreInjectionWidgetsOptions = {
|
|
145
|
+
/**
|
|
146
|
+
* `replace` (default) publishes `entries` as the whole registry.
|
|
147
|
+
*
|
|
148
|
+
* `merge` adds only the entries the registry does not already carry, keeping whatever a
|
|
149
|
+
* previous bootstrap published. A process may run more than one bootstrap partition (the
|
|
150
|
+
* API-only one and the full page one share a Node process in a mixed web host), and the
|
|
151
|
+
* partition that registers second must not shrink the registry the first one populated.
|
|
152
|
+
*/
|
|
153
|
+
mode?: 'replace' | 'merge'
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function registerCoreInjectionWidgets(
|
|
157
|
+
entries: ModuleInjectionWidgetEntry[],
|
|
158
|
+
options: RegisterCoreInjectionWidgetsOptions = {},
|
|
159
|
+
) {
|
|
160
|
+
if (_coreInjectionWidgetEntries !== null && process.env.NODE_ENV === 'development' && options.mode !== 'merge') {
|
|
146
161
|
logger.debug('Core injection widgets re-registered (this may occur during HMR)')
|
|
147
162
|
}
|
|
148
|
-
const
|
|
163
|
+
const incoming = applyInjectionWidgetOverridesToEntries(entries)
|
|
164
|
+
if (options.mode !== 'merge') {
|
|
165
|
+
_coreInjectionWidgetEntries = incoming
|
|
166
|
+
writeGlobalInjectionWidgets(incoming)
|
|
167
|
+
notifyInjectionRegistryChanged()
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const existing = readGlobalInjectionWidgets() ?? _coreInjectionWidgetEntries ?? []
|
|
172
|
+
const known = new Set(existing.map((entry) => entry.key))
|
|
173
|
+
const added = incoming.filter((entry) => !known.has(entry.key))
|
|
174
|
+
// Nothing to contribute: leave the registry exactly as it was. Publishing an empty array here
|
|
175
|
+
// would turn "never registered" into "registered with no widgets", which downgrades the loud
|
|
176
|
+
// bootstrap error into silently missing contributions.
|
|
177
|
+
if (!added.length) return
|
|
178
|
+
const finalEntries = [...existing, ...added]
|
|
149
179
|
_coreInjectionWidgetEntries = finalEntries
|
|
150
180
|
writeGlobalInjectionWidgets(finalEntries)
|
|
151
181
|
notifyInjectionRegistryChanged()
|