@open-mercato/shared 0.10.1-develop.7961.1.d65694a8e6 → 0.10.1-develop.7972.1.03f813eaaf

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.
@@ -855,20 +855,34 @@ export async function loadBootstrapData(appRoot?: string): Promise<BootstrapData
855
855
  export async function bootstrapFromAppRoot(appRoot?: string): Promise<BootstrapData> {
856
856
  const { createBootstrap, waitForAsyncRegistration } = await import('./factory.js')
857
857
  const resolved = resolveAppRootOrThrow(appRoot)
858
- // All three loads compile through esbuild, so they share one lifecycle scope: without it
859
- // `loadBootstrapData` releases the esbuild helper process and `loadAppDiRegistrar`
860
- // silently starts a second one that nothing ever stops.
861
- const { data, appDiRegistrar } = await withEsbuildLifecycle(async () => {
858
+ // All generated and app-source loads compile through esbuild, so they share one lifecycle
859
+ // scope: without it `loadBootstrapData` releases the helper process and each later load silently
860
+ // starts a new one that nothing ever stops.
861
+ const {
862
+ data,
863
+ appDiRegistrar,
864
+ runBootstrapRegistrations,
865
+ } = await withEsbuildLifecycle(async () => {
862
866
  // Dispatch the app's `entry.overrides` (src/modules.ts) BEFORE any registry
863
867
  // first-loads — the `bootstrap()` call below runs `registerModules(data.modules)`,
864
868
  // and `registerCliModules` in the mercato bin right after this function returns;
865
869
  // both read the override side-registry this populates.
866
870
  await loadAppModuleOverrides(resolved.appDir)
871
+ const data = await loadBootstrapData(resolved.appDir)
872
+ const [appDiRegistrar, bootstrapRegistrationsModule] = await Promise.all([
873
+ loadAppDiRegistrar(resolved.appDir),
874
+ loadOptionalGeneratedModule(
875
+ path.join(resolved.generatedDir, 'bootstrap-registrations.generated.ts'),
876
+ { runBootstrapRegistrations: () => undefined },
877
+ ),
878
+ ])
867
879
  return {
868
- data: await loadBootstrapData(resolved.appDir),
869
- appDiRegistrar: await loadAppDiRegistrar(resolved.appDir),
880
+ data,
881
+ appDiRegistrar,
882
+ runBootstrapRegistrations: bootstrapRegistrationsModule.runBootstrapRegistrations as () => void,
870
883
  }
871
884
  })
885
+ runBootstrapRegistrations()
872
886
  const bootstrap = createBootstrap(data, appDiRegistrar ? { appDiRegistrar } : {})
873
887
  bootstrap()
874
888
  // In CLI context, wait for async registrations (UI widgets, search configs, etc.)
@@ -2,6 +2,7 @@ import {
2
2
  clearModuleResourceUsageData,
3
3
  getModuleResourceUsageReport,
4
4
  resetModuleResourceUsage,
5
+ waitForModuleResourceUsageSnapshotIoForTests,
5
6
  withModuleResourceUsage,
6
7
  } from '../resource-usage'
7
8
  import fs from 'node:fs'
@@ -24,7 +25,9 @@ describe('module resource usage tracker', () => {
24
25
  delete process.env.OM_MODULE_RESOURCE_HEAVY_CPU_MS
25
26
  })
26
27
 
27
- afterEach(() => {
28
+ afterEach(async () => {
29
+ await waitForModuleResourceUsageSnapshotIoForTests()
30
+ jest.restoreAllMocks()
28
31
  resetModuleResourceUsage()
29
32
  if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true })
30
33
  tempDir = null
@@ -272,12 +275,8 @@ describe('module resource usage tracker', () => {
272
275
 
273
276
  // The flush is fire-and-forget (no fs.*Sync calls on the hot path), so wait for the async
274
277
  // write to land instead of asserting on it synchronously.
278
+ await waitForModuleResourceUsageSnapshotIoForTests()
275
279
  const ownSnapshotPath = path.join(tempDir!, `process-${process.pid}.json`)
276
- const start = Date.now()
277
- while (!fs.existsSync(ownSnapshotPath)) {
278
- if (Date.now() - start > 2000) throw new Error('Timed out waiting for async snapshot flush')
279
- await new Promise((resolve) => setTimeout(resolve, 10))
280
- }
281
280
  const ownPayload = JSON.parse(fs.readFileSync(ownSnapshotPath, 'utf8'))
282
281
  expect(ownPayload.entries.some((entry: { moduleId: string }) => entry.moduleId === 'customers')).toBe(true)
283
282
 
@@ -339,13 +338,72 @@ describe('module resource usage tracker', () => {
339
338
  )
340
339
 
341
340
  // readSnapshotPayloads() runs as part of building the report; the prune it triggers is
342
- // fire-and-forget, so poll for the file to disappear instead of asserting synchronously.
341
+ // fire-and-forget, so wait for it instead of asserting synchronously.
343
342
  getModuleResourceUsageReport()
344
- const start = Date.now()
345
- while (fs.existsSync(stalePath)) {
346
- if (Date.now() - start > 2000) throw new Error('Timed out waiting for stale snapshot to be pruned')
347
- await new Promise((resolve) => setTimeout(resolve, 10))
348
- }
343
+ await waitForModuleResourceUsageSnapshotIoForTests()
349
344
  expect(fs.existsSync(stalePath)).toBe(false)
350
345
  })
346
+
347
+ it('waits for the report\'s in-flight snapshot write and leaves no temp file behind', async () => {
348
+ process.env.OM_MODULE_RESOURCE_USAGE_SNAPSHOT = 'on'
349
+ const ownSnapshotPath = path.join(tempDir!, `process-${process.pid}.json`)
350
+
351
+ getModuleResourceUsageReport()
352
+ expect(fs.existsSync(ownSnapshotPath)).toBe(false)
353
+
354
+ await waitForModuleResourceUsageSnapshotIoForTests()
355
+ expect(fs.readdirSync(tempDir!)).toEqual([`process-${process.pid}.json`])
356
+ expect(JSON.parse(fs.readFileSync(ownSnapshotPath, 'utf8')).pid).toBe(process.pid)
357
+ })
358
+
359
+ it('waits for snapshot I/O started while it is already waiting', async () => {
360
+ process.env.OM_MODULE_RESOURCE_USAGE_SNAPSHOT = 'on'
361
+ const realRename = fs.promises.rename.bind(fs.promises)
362
+ const renameSpy = jest.spyOn(fs.promises, 'rename').mockImplementationOnce(async (from, to) => {
363
+ getModuleResourceUsageReport()
364
+ return realRename(from, to)
365
+ })
366
+
367
+ getModuleResourceUsageReport()
368
+ await waitForModuleResourceUsageSnapshotIoForTests()
369
+
370
+ expect(renameSpy).toHaveBeenCalledTimes(2)
371
+ })
372
+
373
+ it('waits for a stale snapshot prune', async () => {
374
+ process.env.OM_MODULE_RESOURCE_USAGE_SNAPSHOT = 'on'
375
+ const stalePid = process.pid + 2
376
+ const stalePath = path.join(tempDir!, `process-${stalePid}.json`)
377
+ fs.writeFileSync(stalePath, JSON.stringify({ pid: stalePid, generatedAt: new Date(0).toISOString(), entries: [] }))
378
+ const realUnlink = fs.promises.unlink.bind(fs.promises)
379
+ let pruned = false
380
+ jest.spyOn(fs.promises, 'unlink').mockImplementationOnce(async (target) => {
381
+ await new Promise((resolve) => setTimeout(resolve, 100))
382
+ await realUnlink(target)
383
+ pruned = true
384
+ })
385
+
386
+ getModuleResourceUsageReport()
387
+ await waitForModuleResourceUsageSnapshotIoForTests()
388
+
389
+ expect(pruned).toBe(true)
390
+ })
391
+
392
+ it('waits for the temp-file cleanup of a failed write', async () => {
393
+ process.env.OM_MODULE_RESOURCE_USAGE_SNAPSHOT = 'on'
394
+ jest.spyOn(fs.promises, 'rename').mockRejectedValueOnce(new Error('[internal] rename failed'))
395
+ const realUnlink = fs.promises.unlink.bind(fs.promises)
396
+ let cleaned = false
397
+ jest.spyOn(fs.promises, 'unlink').mockImplementationOnce(async (target) => {
398
+ await new Promise((resolve) => setTimeout(resolve, 100))
399
+ await realUnlink(target)
400
+ cleaned = true
401
+ })
402
+
403
+ getModuleResourceUsageReport()
404
+ await waitForModuleResourceUsageSnapshotIoForTests()
405
+
406
+ expect(cleaned).toBe(true)
407
+ expect(fs.readdirSync(tempDir!)).toEqual([])
408
+ })
351
409
  })
@@ -4,6 +4,7 @@ import { parseBooleanWithDefault } from '../boolean'
4
4
  import { parseNumberWithDefault } from '../number'
5
5
 
6
6
  const GLOBAL_KEY = '__openMercatoModuleResourceUsage__'
7
+ const PENDING_SNAPSHOT_IO_KEY = '__openMercatoModuleResourceUsagePendingSnapshotIo__'
7
8
  const NS_PER_MS = 1_000_000
8
9
  const MICROS_PER_MS = 1000
9
10
  const DEFAULT_RECENT_SAMPLE_LIMIT = 128
@@ -791,6 +792,37 @@ function registerSnapshotShutdownHook(state: ResourceUsageState): void {
791
792
  state.shutdownHookRegistered = true
792
793
  }
793
794
 
795
+ // Kept on globalThis under its own key, like the usage state, so every module instance (dev hot
796
+ // reload, standalone server chunks) sees the same in-flight I/O; resetModuleResourceUsage() replaces
797
+ // the usage state and must not drop I/O that is still running.
798
+ function getPendingSnapshotIo(): Set<Promise<void>> {
799
+ const globalRecord = globalThis as Record<string, unknown>
800
+ const existing = globalRecord[PENDING_SNAPSHOT_IO_KEY]
801
+ if (existing instanceof Set) return existing as Set<Promise<void>>
802
+ const created = new Set<Promise<void>>()
803
+ globalRecord[PENDING_SNAPSHOT_IO_KEY] = created
804
+ return created
805
+ }
806
+
807
+ function trackSnapshotIo(operation: Promise<void>): void {
808
+ const pending = getPendingSnapshotIo()
809
+ const settle = () => {
810
+ pending.delete(operation)
811
+ }
812
+ pending.add(operation)
813
+ operation.then(settle, settle)
814
+ }
815
+
816
+ // Test-only: resolves once no snapshot write or stale-snapshot prune is in flight, including work
817
+ // started while waiting. The tracked call path never waits on this; tests use it before they read
818
+ // or remove their temporary snapshot directory.
819
+ export async function waitForModuleResourceUsageSnapshotIoForTests(): Promise<void> {
820
+ const pending = getPendingSnapshotIo()
821
+ while (pending.size > 0) {
822
+ await Promise.allSettled(Array.from(pending))
823
+ }
824
+ }
825
+
794
826
  // Fire-and-forget: nothing in this process depends on the write completing (readers always
795
827
  // skip their own pid's file — see readSnapshotPayloads), so there's no reason for the write to
796
828
  // block the tracked call, event dispatch, or report request that triggered it. This mirrors the
@@ -806,14 +838,16 @@ let snapshotWriteSequence = 0
806
838
  // empty/partial content window that a direct writeFile to snapshotPath would briefly expose.
807
839
  function writeSnapshotFileAsync(dir: string, snapshotPath: string, payload: unknown): void {
808
840
  const tempPath = `${snapshotPath}.${process.pid}.${snapshotWriteSequence++}.tmp`
809
- fs.promises.mkdir(dir, { recursive: true })
810
- .then(() => fs.promises.writeFile(tempPath, JSON.stringify(payload, null, 2)))
811
- .then(() => fs.promises.rename(tempPath, snapshotPath))
812
- .catch(() => {
813
- // Snapshot files are diagnostic only; in-memory reporting still works. Best-effort cleanup of
814
- // the temp file if the rename never happened; ignore if it is already gone.
815
- fs.promises.unlink(tempPath).catch(() => {})
816
- })
841
+ trackSnapshotIo(
842
+ fs.promises.mkdir(dir, { recursive: true })
843
+ .then(() => fs.promises.writeFile(tempPath, JSON.stringify(payload, null, 2)))
844
+ .then(() => fs.promises.rename(tempPath, snapshotPath))
845
+ .catch(() =>
846
+ // Snapshot files are diagnostic only; in-memory reporting still works. Best-effort cleanup of
847
+ // the temp file if the rename never happened; ignore if it is already gone.
848
+ fs.promises.unlink(tempPath).catch(() => {}),
849
+ ),
850
+ )
817
851
  }
818
852
 
819
853
  function flushModuleResourceUsageSnapshot(force: boolean): void {
@@ -858,9 +892,11 @@ function isFreshSnapshot(payload: SnapshotPayload): boolean {
858
892
  // stale ones opportunistically here (best-effort, never blocks the read) so the directory doesn't
859
893
  // grow without bound in a long-running deployment.
860
894
  function pruneStaleSnapshotFile(filePath: string): void {
861
- fs.promises.unlink(filePath).catch(() => {
862
- // Snapshot files are diagnostic only; leave it for a later pass if it can't be removed now.
863
- })
895
+ trackSnapshotIo(
896
+ fs.promises.unlink(filePath).catch(() => {
897
+ // Snapshot files are diagnostic only; leave it for a later pass if it can't be removed now.
898
+ }),
899
+ )
864
900
  }
865
901
 
866
902
  function readSnapshotPayloads(): SnapshotPayload[] {
@@ -55,6 +55,7 @@ describe('module contract override helpers', () => {
55
55
  seedDefaults: false,
56
56
  seedExamples: false,
57
57
  onTenantCreated: false,
58
+ onOrganizationCreated: false,
58
59
  },
59
60
  acl: {
60
61
  features: {
@@ -84,6 +85,7 @@ describe('module contract override helpers', () => {
84
85
  ],
85
86
  setup: {
86
87
  onTenantCreated: jest.fn(),
88
+ onOrganizationCreated: jest.fn(),
87
89
  seedDefaults: jest.fn(),
88
90
  seedExamples: jest.fn(),
89
91
  defaultRoleFeatures: { admin: ['example.manage'] },
@@ -113,6 +115,7 @@ describe('module contract override helpers', () => {
113
115
  expect(overridden.setup?.seedDefaults).toBeUndefined()
114
116
  expect(overridden.setup?.seedExamples).toBeUndefined()
115
117
  expect(overridden.setup?.onTenantCreated).toBeUndefined()
118
+ expect(overridden.setup?.onOrganizationCreated).toBeUndefined()
116
119
  })
117
120
 
118
121
  it('applies registry-entry overrides for widgets, notifications, interceptors, enrichers and guards', () => {
@@ -104,6 +104,7 @@ export interface SetupOverridesShape {
104
104
  seedDefaults?: false
105
105
  seedExamples?: false
106
106
  onTenantCreated?: false
107
+ onOrganizationCreated?: false
107
108
  }
108
109
 
109
110
  /** Phase 16 — ACL features (per-feature override). */
@@ -1496,6 +1497,7 @@ function applySetupOverride(setup: ModuleSetupConfig | undefined, override: Setu
1496
1497
  if (override.seedDefaults === false) delete next.seedDefaults
1497
1498
  if (override.seedExamples === false) delete next.seedExamples
1498
1499
  if (override.onTenantCreated === false) delete next.onTenantCreated
1500
+ if (override.onOrganizationCreated === false) delete next.onOrganizationCreated
1499
1501
  return next
1500
1502
  }
1501
1503
 
@@ -36,6 +36,14 @@ export type ModuleSetupConfig = {
36
36
  */
37
37
  onTenantCreated?: (ctx: TenantSetupContext) => Promise<void>
38
38
 
39
+ /**
40
+ * Called after an organization is created in an existing tenant.
41
+ * For organization-scoped structural defaults that must exist for every
42
+ * organization, including organizations added after `mercato init`.
43
+ * Must be idempotent. Runs from a persistent organization-created subscriber.
44
+ */
45
+ onOrganizationCreated?: (ctx: InitSetupContext) => Promise<void>
46
+
39
47
  /**
40
48
  * Called during `mercato init` after tenant exists.
41
49
  * For reference/structural data: dictionaries, tax rates, statuses, units,