@open-mercato/cli 0.6.4-canary.3992.1.0f76b3b18e → 0.6.4-develop.3921.1.8a42ddf4c8

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.6.4-canary.3992.1.0f76b3b18e",
3
+ "version": "0.6.4-develop.3921.1.8a42ddf4c8",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "exports": {
@@ -59,21 +59,21 @@
59
59
  "@mikro-orm/decorators": "^7.1.1",
60
60
  "@mikro-orm/migrations": "^7.1.1",
61
61
  "@mikro-orm/postgresql": "^7.1.1",
62
- "@open-mercato/queue": "0.6.4-canary.3992.1.0f76b3b18e",
63
- "@open-mercato/shared": "0.6.4-canary.3992.1.0f76b3b18e",
62
+ "@open-mercato/queue": "0.6.4-develop.3921.1.8a42ddf4c8",
63
+ "@open-mercato/shared": "0.6.4-develop.3921.1.8a42ddf4c8",
64
64
  "cross-spawn": "^7.0.6",
65
65
  "pg": "8.21.0",
66
66
  "semver": "^7.8.1",
67
- "testcontainers": "^12.0.1",
67
+ "testcontainers": "^12.0.0",
68
68
  "ts-morph": "^28.0.0",
69
69
  "tsx": "^4.22.3",
70
70
  "typescript": "^6.0.3"
71
71
  },
72
72
  "peerDependencies": {
73
- "@open-mercato/shared": "0.6.4-canary.3992.1.0f76b3b18e"
73
+ "@open-mercato/shared": "0.6.4-develop.3921.1.8a42ddf4c8"
74
74
  },
75
75
  "devDependencies": {
76
- "@open-mercato/shared": "0.6.4-canary.3992.1.0f76b3b18e",
76
+ "@open-mercato/shared": "0.6.4-develop.3921.1.8a42ddf4c8",
77
77
  "@types/jest": "^30.0.0",
78
78
  "jest": "^30.4.2",
79
79
  "ts-jest": "^29.4.11"
@@ -37,18 +37,9 @@ function buildMockChildProcessModule(routeAutoExit: MockChildSpawnRouter) {
37
37
  if (autoExit) {
38
38
  queueMicrotask(() => {
39
39
  if (child.exitCode !== null || child.signalCode !== null) return
40
- if (pathIncludes(spawnargs[1] ?? '', 'next/dist/bin/next') && spawnargs.includes('dev')) {
41
- child.stdout.emit('data', '✓ Ready in 1ms\n')
42
- }
43
- queueMicrotask(() => {
44
- child.exitCode = autoExit.code
45
- child.signalCode = autoExit.signal ?? null
46
- child.emit('exit', child.exitCode, child.signalCode)
47
- })
48
- })
49
- } else if (pathIncludes(spawnargs[1] ?? '', 'next/dist/bin/next') && spawnargs.includes('dev')) {
50
- queueMicrotask(() => {
51
- child.stdout.emit('data', '✓ Ready in 1ms\n')
40
+ child.exitCode = autoExit.code
41
+ child.signalCode = autoExit.signal ?? null
42
+ child.emit('exit', child.exitCode, child.signalCode)
52
43
  })
53
44
  }
54
45
 
@@ -61,23 +61,21 @@ describe('dev env reload helpers', () => {
61
61
  expect(environment.REMOVED_LATER).toBeUndefined()
62
62
  })
63
63
 
64
- it('watches generated runtime files when explicitly requested', async () => {
64
+ it('watches generated runtime files for dev restarts', async () => {
65
65
  const generatedDir = path.join(appDir, '.mercato', 'generated')
66
66
  fs.mkdirSync(generatedDir, { recursive: true })
67
67
  const generatedFile = path.join(generatedDir, 'backend-routes.generated.ts')
68
68
  fs.writeFileSync(generatedFile, 'export const routes = []\n')
69
69
 
70
- let stop = () => {}
71
70
  const seen = new Promise<string>((resolve) => {
72
- stop = watchDevRuntimeFiles(appDir, (filePath) => {
71
+ const stop = watchDevRuntimeFiles(appDir, (filePath) => {
73
72
  stop()
74
73
  resolve(filePath)
75
74
  }, { debounceMs: 10 })
76
75
  })
77
76
 
78
- await new Promise((resolve) => setTimeout(resolve, 25))
79
77
  fs.writeFileSync(generatedFile, 'export const routes = [1]\n')
80
78
 
81
- await expect(seen.finally(stop)).resolves.toBe(generatedFile)
79
+ await expect(seen).resolves.toBe(generatedFile)
82
80
  })
83
81
  })
@@ -2942,20 +2942,6 @@ export async function startEphemeralEnvironment(options: EphemeralRuntimeOptions
2942
2942
  TENANT_DATA_ENCRYPTION_FALLBACK_KEY: process.env.TENANT_DATA_ENCRYPTION_FALLBACK_KEY ?? 'om-ephemeral-integration-fallback-key',
2943
2943
  AUTO_SPAWN_WORKERS: process.env.AUTO_SPAWN_WORKERS ?? 'true',
2944
2944
  AUTO_SPAWN_SCHEDULER: 'false',
2945
- // Hide the demo feedback floating action button — it lives at
2946
- // `fixed bottom-6 right-6 z-banner` and consistently intercepts pointer
2947
- // events on row-action menus and other bottom-of-viewport UI elements
2948
- // (e.g. TC-WF-006 Delete menuitem click). The widget is already gated
2949
- // on `DEMO_MODE !== 'false'` in the backend layout, so opting out here
2950
- // only affects the integration test runtime — dev + prod stay unchanged.
2951
- DEMO_MODE: 'false',
2952
- // Disable the feature-toggle resolution cache. Tests flip overrides
2953
- // (e.g. example_customers_sync enabled/bidirectional) between cases; the
2954
- // 1-minute resolution cache can serve a stale value across set/clear
2955
- // under fast churn, which made the example.todo.* persistent subscribers
2956
- // skip enqueueing inbound sync jobs (TC-CRM-028 inbound trio flake).
2957
- // Fresh DB reads make flag-gated sync deterministic in tests only.
2958
- OM_FEATURE_TOGGLES_CACHE_DISABLED: '1',
2959
2945
  OM_CLI_QUIET: '1',
2960
2946
  MERCATO_QUIET: '1',
2961
2947
  QUEUE_BASE_DIR: EPHEMERAL_QUEUE_BASE_DIR,
package/src/mercato.ts CHANGED
@@ -32,7 +32,7 @@ import {
32
32
  import { parseModuleInstallArgs } from './lib/module-install-args'
33
33
  import { resolveNextBuildIdCandidate } from './lib/next-build-id'
34
34
  import { acquireServerStartLock } from './lib/server-start-lock'
35
- import { createDevEnvReloader, watchDevEnvFiles } from './lib/dev-env-reload'
35
+ import { createDevEnvReloader, watchDevEnvFiles, watchDevRuntimeFiles } from './lib/dev-env-reload'
36
36
  // Lazy-imported to avoid pulling in `testcontainers` (devDependency) at startup
37
37
  const lazyIntegration = () => import('./lib/testing/integration')
38
38
  import type { ChildProcess } from 'node:child_process'
@@ -341,122 +341,6 @@ type DevServerRestartResult = {
341
341
 
342
342
  type DevServerExitResult = ManagedProcessExitResult | DevServerRestartResult
343
343
 
344
- function resolveDevRuntimeBaseUrl(environment: NodeJS.ProcessEnv = process.env): string {
345
- const configured =
346
- environment.APP_URL
347
- ?? environment.NEXT_PUBLIC_APP_URL
348
- ?? environment.NEXTAUTH_URL
349
- if (configured?.trim()) {
350
- return configured.trim().replace(/\/+$/, '')
351
- }
352
- return `http://localhost:${environment.PORT?.trim() || '3000'}`
353
- }
354
-
355
- function writeDevSplashChildState(state: Record<string, unknown>): void {
356
- if (process.env.OM_DEV_SPLASH_RUNTIME_WRAPPER === '1') return
357
- const stateFile = process.env.OM_DEV_SPLASH_CHILD_STATE_FILE
358
- if (!stateFile?.trim()) return
359
-
360
- try {
361
- fs.mkdirSync(path.dirname(stateFile), { recursive: true })
362
- fs.writeFileSync(stateFile, `${JSON.stringify({
363
- mode: process.env.OM_DEV_SPLASH_MODE || 'dev',
364
- failed: false,
365
- failureLines: [],
366
- failureCommand: null,
367
- ...state,
368
- }, null, 2)}\n`)
369
- } catch {
370
- // Splash state is best-effort; terminal logs remain authoritative.
371
- }
372
- }
373
-
374
- function writeDevSplashRuntimeStarting(detail = 'Starting Next.js dev server'): void {
375
- writeDevSplashChildState({
376
- phase: 'Preparing app runtime',
377
- detail,
378
- ready: false,
379
- readyUrl: null,
380
- loginUrl: null,
381
- progressLabel: 'Launching app runtime',
382
- activity: detail,
383
- })
384
- }
385
-
386
- function resolveSplashProgressFallback(): { current: number; total: number } {
387
- const current = Number.parseInt(process.env.OM_DEV_SPLASH_STAGE_CURRENT ?? '', 10)
388
- const total = Number.parseInt(process.env.OM_DEV_SPLASH_STAGE_TOTAL ?? '', 10)
389
- if (Number.isFinite(current) && Number.isFinite(total) && total > 0) {
390
- return { current, total }
391
- }
392
- if (process.env.OM_DEV_SPLASH_MODE === 'greenfield' || process.env.OM_DEV_SPLASH_MODE === 'setup') {
393
- return { current: 5, total: 5 }
394
- }
395
- return { current: 3, total: 3 }
396
- }
397
-
398
- function writeDevSplashRuntimeRestarting(reason: string): void {
399
- const progress = resolveSplashProgressFallback()
400
- writeDevSplashChildState({
401
- phase: 'App runtime is restarting',
402
- detail: `Reason: ${reason}`,
403
- ready: false,
404
- readyUrl: null,
405
- loginUrl: null,
406
- progressCurrent: progress.current,
407
- progressTotal: progress.total,
408
- progressLabel: 'Restarting app runtime',
409
- activity: `App runtime restart: ${reason}`,
410
- })
411
- }
412
-
413
- function writeDevSplashRuntimeReady(reason?: string): void {
414
- const readyUrl = resolveDevRuntimeBaseUrl()
415
- const progress = resolveSplashProgressFallback()
416
- writeDevSplashChildState({
417
- phase: 'App is ready',
418
- detail: reason ? `Restart completed after ${reason}` : 'Next.js dev server is ready',
419
- ready: true,
420
- readyUrl,
421
- loginUrl: `${readyUrl}/login`,
422
- progressCurrent: progress.current,
423
- progressTotal: progress.total,
424
- progressPercent: 100,
425
- progressLabel: 'App is ready',
426
- activity: reason ? `Restart completed after ${reason}` : 'App runtime is ready',
427
- })
428
- }
429
-
430
- function resolveDevWarmupReadyTimeoutMs(environment: NodeJS.ProcessEnv = process.env): number {
431
- const parsed = Number.parseInt(environment.OM_DEV_WARMUP_READY_TIMEOUT_MS ?? '', 10)
432
- if (Number.isFinite(parsed) && parsed >= 0) return parsed
433
- return 300_000
434
- }
435
-
436
- async function waitForDevWarmupReadyFile(
437
- filePath: string | undefined,
438
- options: {
439
- timeoutMs?: number
440
- signal?: AbortSignal
441
- } = {},
442
- ): Promise<'ready' | 'timeout' | 'aborted'> {
443
- const normalized = filePath?.trim()
444
- if (!normalized) return 'ready'
445
- const timeoutMs = options.timeoutMs ?? resolveDevWarmupReadyTimeoutMs()
446
- const startedAt = Date.now()
447
-
448
- while (true) {
449
- if (options.signal?.aborted) return 'aborted'
450
- try {
451
- if (fs.existsSync(normalized)) return 'ready'
452
- } catch {
453
- // Keep polling; the runtime wrapper owns this best-effort marker.
454
- }
455
- if (timeoutMs >= 0 && Date.now() - startedAt >= timeoutMs) return 'timeout'
456
- await new Promise((resolve) => setTimeout(resolve, 250))
457
- }
458
- }
459
-
460
344
  type ModuleCommandLookupResult =
461
345
  | {
462
346
  status: 'ok'
@@ -717,17 +601,18 @@ async function runGeneratorSuite(quiet: boolean): Promise<void> {
717
601
  function createGenerateWatchChecksumFn(): () => Promise<string> {
718
602
  return async () => {
719
603
  const { createResolver } = await import('./lib/resolver')
720
- const { calculateGenerateWatchStructureChecksum } = await import('./lib/generate-watch-structure')
604
+ const { calculateStructureChecksum } = await import('./lib/utils')
721
605
  const resolver = createResolver()
722
- const moduleRoots = []
606
+ const tracked = new Set<string>([
607
+ path.join(resolver.getAppDir(), 'src', 'modules.ts'),
608
+ path.join(resolver.getAppDir(), 'src', 'modules'),
609
+ ])
723
610
  for (const entry of resolver.loadEnabledModules()) {
724
611
  const roots = resolver.getModulePaths(entry)
725
- moduleRoots.push({ appBase: roots.appBase, pkgBase: roots.pkgBase })
612
+ tracked.add(roots.appBase)
613
+ tracked.add(roots.pkgBase)
726
614
  }
727
- return calculateGenerateWatchStructureChecksum({
728
- modulesFile: path.join(resolver.getAppDir(), 'src', 'modules.ts'),
729
- moduleRoots,
730
- })
615
+ return calculateStructureChecksum(Array.from(tracked))
731
616
  }
732
617
  }
733
618
 
@@ -1809,7 +1694,6 @@ export async function run(argv = process.argv) {
1809
1694
  let activeLazySupervisor: ReturnType<typeof startLazyWorkerSupervisor> | null = null
1810
1695
  let activeLazySchedulerSupervisor: ReturnType<typeof startLazySchedulerSupervisor> | null = null
1811
1696
  let activeGenerateWatcher: GenerateWatcherHandle | null = null
1812
- let lastRestartReason: string | null = null
1813
1697
  const generateWatcherMode: GenerateWatcherMode = resolveGenerateWatcherMode(process.env)
1814
1698
  const envReloader = createDevEnvReloader(appDir, process.env, initialProcessEnvironmentEntries)
1815
1699
 
@@ -1903,25 +1787,21 @@ export async function run(argv = process.argv) {
1903
1787
  filePath,
1904
1788
  })
1905
1789
  })
1790
+ const stopRuntimeWatcher = watchDevRuntimeFiles(appDir, (filePath) => {
1791
+ devRestartPromiseResolve?.({
1792
+ label: 'Runtime graph change',
1793
+ restart: true,
1794
+ filePath,
1795
+ })
1796
+ })
1797
+
1906
1798
  const waitForDevRestart = (): Promise<DevServerRestartResult> =>
1907
1799
  new Promise((resolve) => {
1908
1800
  devRestartPromiseResolve = resolve
1909
1801
  })
1910
1802
 
1911
- const startNextDev = (runtimeEnv: NodeJS.ProcessEnv): {
1912
- exitPromise: Promise<ManagedProcessExitResult>
1913
- readyPromise: Promise<void>
1914
- } => {
1915
- let readyResolve: () => void = () => undefined
1916
- const readyPromise = new Promise<void>((resolve) => {
1917
- readyResolve = resolve
1918
- })
1919
- const exitPromise = new Promise<ManagedProcessExitResult>((resolve) => {
1920
- writeDevSplashRuntimeStarting(
1921
- lastRestartReason
1922
- ? `Restarting Next.js dev server. Reason: ${lastRestartReason}`
1923
- : 'Starting Next.js dev server',
1924
- )
1803
+ const startNextDev = (runtimeEnv: NodeJS.ProcessEnv): Promise<ManagedProcessExitResult> =>
1804
+ new Promise((resolve) => {
1925
1805
  const nextProcess = spawn('node', [nextBin, 'dev', '--turbopack'], {
1926
1806
  stdio: ['inherit', 'pipe', 'pipe'],
1927
1807
  env: runtimeEnv,
@@ -1930,18 +1810,11 @@ export async function run(argv = process.argv) {
1930
1810
  processes.push(nextProcess)
1931
1811
 
1932
1812
  let combinedOutput = ''
1933
- let reportedReady = false
1934
1813
  const appendOutput = (chunk: string) => {
1935
1814
  combinedOutput += chunk
1936
1815
  if (combinedOutput.length > 32_768) {
1937
1816
  combinedOutput = combinedOutput.slice(-32_768)
1938
1817
  }
1939
- if (!reportedReady && /\bready in\b/i.test(chunk)) {
1940
- reportedReady = true
1941
- writeDevSplashRuntimeReady(lastRestartReason ?? undefined)
1942
- lastRestartReason = null
1943
- readyResolve()
1944
- }
1945
1818
  }
1946
1819
 
1947
1820
  nextProcess.stdout?.on('data', (chunk: Buffer | string) => {
@@ -1958,13 +1831,9 @@ export async function run(argv = process.argv) {
1958
1831
  nextProcess.on('exit', async (code, signal) => {
1959
1832
  if (!didRetryCorruptedTurbopackCache && isTurbopackCacheCorruption(combinedOutput)) {
1960
1833
  didRetryCorruptedTurbopackCache = true
1961
- lastRestartReason = 'corrupted Turbopack dev cache'
1962
- writeDevSplashRuntimeRestarting(lastRestartReason)
1963
1834
  console.log('[server] Detected corrupted Turbopack dev cache. Clearing .mercato/next/dev and restarting Next.js once...')
1964
1835
  removeTurbopackDevCache(appDir)
1965
- const restarted = startNextDev(runtimeEnv)
1966
- restarted.readyPromise.then(readyResolve)
1967
- return resolve(await restarted.exitPromise)
1836
+ return resolve(await startNextDev(runtimeEnv))
1968
1837
  }
1969
1838
  resolve({
1970
1839
  label: 'Next.js dev server',
@@ -1973,8 +1842,6 @@ export async function run(argv = process.argv) {
1973
1842
  })
1974
1843
  })
1975
1844
  })
1976
- return { exitPromise, readyPromise }
1977
- }
1978
1845
 
1979
1846
  try {
1980
1847
  while (!stopping) {
@@ -1984,92 +1851,62 @@ export async function run(argv = process.argv) {
1984
1851
  const autoSpawnSchedulerMode = resolveAutoSpawnSchedulerMode(process.env)
1985
1852
  const queueStrategy = process.env.QUEUE_STRATEGY || 'local'
1986
1853
  const schedulerCommand = lookupModuleCommand(getCliModules(), 'scheduler', 'start')
1987
- const nextRuntime = startNextDev(runtimeEnv)
1988
- const restartPromise = waitForDevRestart()
1989
- const backgroundStartAbort = new AbortController()
1990
- const cancelBackgroundStart = () => backgroundStartAbort.abort()
1991
- nextRuntime.exitPromise.finally(cancelBackgroundStart)
1992
- restartPromise.then(cancelBackgroundStart)
1993
- let backgroundExitResolve: (result: ManagedProcessExitResult) => void = () => undefined
1994
- const backgroundExitPromise = new Promise<ManagedProcessExitResult>((resolve) => {
1995
- backgroundExitResolve = resolve
1996
- })
1997
1854
  const managedExitPromises: Promise<DevServerExitResult>[] = [
1998
- nextRuntime.exitPromise,
1999
- restartPromise,
2000
- backgroundExitPromise,
1855
+ startNextDev(runtimeEnv),
1856
+ waitForDevRestart(),
2001
1857
  ]
2002
1858
 
2003
- const startBackgroundServices = async () => {
2004
- if (stopping || backgroundStartAbort.signal.aborted) return
2005
-
2006
- // Keep first-route compilation responsive: greenfield setup can
2007
- // leave vector/fulltext jobs ready. When the dev wrapper is
2008
- // active, wait for its /login + /backend warmup marker before
2009
- // workers and scheduler begin consuming CPU and database I/O.
2010
- const warmupReady = await waitForDevWarmupReadyFile(process.env.OM_DEV_WARMUP_READY_FILE, {
2011
- timeoutMs: resolveDevWarmupReadyTimeoutMs(process.env),
2012
- signal: backgroundStartAbort.signal,
2013
- })
2014
- if (warmupReady === 'aborted' || stopping || backgroundStartAbort.signal.aborted) return
2015
- if (warmupReady === 'timeout') {
2016
- console.warn('[server] Timed out waiting for dev warmup marker; starting background services anyway.')
2017
- }
2018
-
2019
- if (autoSpawnWorkersMode !== 'off') {
2020
- const discoveredWorkers = getRegisteredCliWorkers()
2021
- const discoveredWorkerQueues = [...new Set(discoveredWorkers.map((worker) => worker.queue))]
2022
- if (discoveredWorkerQueues.length === 0) {
2023
- console.error('[server] AUTO_SPAWN_WORKERS is enabled, but no queues were discovered from CLI modules. Run `yarn generate` and verify `.mercato/generated/modules.cli.generated.ts` contains worker entries. Continuing without auto-spawned workers.')
2024
- } else if (autoSpawnWorkersMode === 'lazy') {
2025
- console.log(`[server] Lazy worker auto-spawn enabled — workers will start on first job (${discoveredWorkerQueues.length} queue(s) watched).`)
2026
- activeLazySupervisor = startLazyWorkerSupervisor({
2027
- mercatoBin,
2028
- appDir,
2029
- runtimeEnv,
2030
- workers: discoveredWorkers,
2031
- pollMs: resolveLazyPollMs(process.env),
2032
- restartOnUnexpectedExit: resolveLazyRestart(process.env),
2033
- })
2034
- } else {
2035
- console.log('[server] Eager worker auto-spawn enabled - starting workers for all queues...')
2036
- const workerProcess = spawn('node', [mercatoBin, 'queue', 'worker', '--all'], {
2037
- stdio: 'inherit',
2038
- env: runtimeEnv,
2039
- cwd: appDir,
2040
- })
2041
- processes.push(workerProcess)
2042
- waitForManagedProcessExit(workerProcess, formatQueueWorkerLabel(discoveredWorkerQueues)).then(backgroundExitResolve)
2043
- }
1859
+ // Start workers if enabled
1860
+ if (autoSpawnWorkersMode !== 'off') {
1861
+ const discoveredWorkers = getRegisteredCliWorkers()
1862
+ const discoveredWorkerQueues = [...new Set(discoveredWorkers.map((worker) => worker.queue))]
1863
+ if (discoveredWorkerQueues.length === 0) {
1864
+ console.error('[server] AUTO_SPAWN_WORKERS is enabled, but no queues were discovered from CLI modules. Run `yarn generate` and verify `.mercato/generated/modules.cli.generated.ts` contains worker entries. Continuing without auto-spawned workers.')
1865
+ } else if (autoSpawnWorkersMode === 'lazy') {
1866
+ console.log(`[server] Lazy worker auto-spawn enabled — workers will start on first job (${discoveredWorkerQueues.length} queue(s) watched).`)
1867
+ activeLazySupervisor = startLazyWorkerSupervisor({
1868
+ mercatoBin,
1869
+ appDir,
1870
+ runtimeEnv,
1871
+ workers: discoveredWorkers,
1872
+ pollMs: resolveLazyPollMs(process.env),
1873
+ restartOnUnexpectedExit: resolveLazyRestart(process.env),
1874
+ })
1875
+ } else {
1876
+ console.log('[server] Eager worker auto-spawn enabled - starting workers for all queues...')
1877
+ const workerProcess = spawn('node', [mercatoBin, 'queue', 'worker', '--all'], {
1878
+ stdio: 'inherit',
1879
+ env: runtimeEnv,
1880
+ cwd: appDir,
1881
+ })
1882
+ processes.push(workerProcess)
1883
+ managedExitPromises.push(waitForManagedProcessExit(workerProcess, formatQueueWorkerLabel(discoveredWorkerQueues)))
2044
1884
  }
1885
+ }
2045
1886
 
2046
- if (autoSpawnSchedulerMode !== 'off' && queueStrategy === 'local') {
2047
- if (schedulerCommand.status !== 'ok') {
2048
- console.log(`[server] Skipping scheduler auto-start — ${describeMissingModuleCommand(schedulerCommand)}`)
2049
- } else if (autoSpawnSchedulerMode === 'lazy') {
2050
- console.log('[server] Lazy scheduler auto-spawn enabled - scheduler will start when an enabled schedule exists.')
2051
- activeLazySchedulerSupervisor = startLazySchedulerSupervisor({
2052
- mercatoBin,
2053
- appDir,
2054
- runtimeEnv,
2055
- pollMs: resolveLazySchedulerPollMs(process.env),
2056
- restartOnUnexpectedExit: resolveLazySchedulerRestart(process.env),
2057
- })
2058
- } else {
2059
- console.log('[server] Eager scheduler auto-spawn enabled - starting scheduler polling engine...')
2060
- const schedulerProcess = spawn('node', [mercatoBin, 'scheduler', 'start'], {
2061
- stdio: 'inherit',
2062
- env: runtimeEnv,
2063
- cwd: appDir,
2064
- })
2065
- processes.push(schedulerProcess)
2066
- waitForManagedProcessExit(schedulerProcess, 'Scheduler polling engine').then(backgroundExitResolve)
2067
- }
1887
+ if (autoSpawnSchedulerMode !== 'off' && queueStrategy === 'local') {
1888
+ if (schedulerCommand.status !== 'ok') {
1889
+ console.log(`[server] Skipping scheduler auto-start — ${describeMissingModuleCommand(schedulerCommand)}`)
1890
+ } else if (autoSpawnSchedulerMode === 'lazy') {
1891
+ console.log('[server] Lazy scheduler auto-spawn enabled - scheduler will start when an enabled schedule exists.')
1892
+ activeLazySchedulerSupervisor = startLazySchedulerSupervisor({
1893
+ mercatoBin,
1894
+ appDir,
1895
+ runtimeEnv,
1896
+ pollMs: resolveLazySchedulerPollMs(process.env),
1897
+ restartOnUnexpectedExit: resolveLazySchedulerRestart(process.env),
1898
+ })
1899
+ } else {
1900
+ console.log('[server] Eager scheduler auto-spawn enabled - starting scheduler polling engine...')
1901
+ const schedulerProcess = spawn('node', [mercatoBin, 'scheduler', 'start'], {
1902
+ stdio: 'inherit',
1903
+ env: runtimeEnv,
1904
+ cwd: appDir,
1905
+ })
1906
+ processes.push(schedulerProcess)
1907
+ managedExitPromises.push(waitForManagedProcessExit(schedulerProcess, 'Scheduler polling engine'))
2068
1908
  }
2069
1909
  }
2070
- nextRuntime.readyPromise.then(() => {
2071
- void startBackgroundServices()
2072
- })
2073
1910
 
2074
1911
  if (generateWatcherMode === 'in-process') {
2075
1912
  // Run the structural regeneration watcher inside this process
@@ -2097,10 +1934,6 @@ export async function run(argv = process.argv) {
2097
1934
  }
2098
1935
 
2099
1936
  const firstExit = await Promise.race(managedExitPromises)
2100
- if (isDevServerRestartResult(firstExit)) {
2101
- lastRestartReason = `${firstExit.label.toLowerCase()} (${path.basename(firstExit.filePath)})`
2102
- writeDevSplashRuntimeRestarting(lastRestartReason)
2103
- }
2104
1937
  await cleanupAndWait()
2105
1938
  devRestartPromiseResolve = null
2106
1939
 
@@ -2117,6 +1950,7 @@ export async function run(argv = process.argv) {
2117
1950
  }
2118
1951
  } finally {
2119
1952
  stopEnvWatcher()
1953
+ stopRuntimeWatcher()
2120
1954
  }
2121
1955
  },
2122
1956
  },
@@ -1,153 +0,0 @@
1
- import crypto from "node:crypto";
2
- import fs from "node:fs";
3
- import path from "node:path";
4
- import {
5
- MODULE_CODE_EXTENSIONS,
6
- SCAN_CONFIGS,
7
- scanModuleDir,
8
- stripModuleCodeExtension
9
- } from "./generators/scanner.js";
10
- const STRUCTURAL_CONVENTION_FILES = [
11
- "index.ts",
12
- "cli.ts",
13
- "di.ts",
14
- "acl.ts",
15
- "setup.ts",
16
- "encryption.ts",
17
- "ce.ts",
18
- "search.ts",
19
- "events.ts",
20
- "notifications.ts",
21
- "notifications.client.ts",
22
- "notifications.handlers.ts",
23
- "translations.ts",
24
- "generators.ts",
25
- "ai-tools.ts",
26
- "ai-agents.ts",
27
- "analytics.ts",
28
- "workflows.ts",
29
- "inbox-actions.ts",
30
- "message-types.ts",
31
- "message-objects.ts",
32
- "integration.ts",
33
- "security.mfa-providers.ts",
34
- "security.sudo.ts",
35
- "data/entities.ts",
36
- "data/extensions.ts",
37
- "data/fields.ts",
38
- "data/enrichers.ts",
39
- "data/guards.ts",
40
- "api/interceptors.ts",
41
- "commands/interceptors.ts",
42
- "widgets/components.ts",
43
- "widgets/injection-table.ts",
44
- "frontend/middleware.ts",
45
- "backend/middleware.ts"
46
- ];
47
- const CONTENT_SENSITIVE_SCAN_CONFIGS = [
48
- SCAN_CONFIGS.apiRoutes,
49
- SCAN_CONFIGS.apiPlainFiles,
50
- SCAN_CONFIGS.subscribers,
51
- SCAN_CONFIGS.workers,
52
- SCAN_CONFIGS.dashboardWidgets,
53
- SCAN_CONFIGS.injectionWidgets
54
- ];
55
- const ROUTE_SHAPE_SCAN_CONFIGS = [
56
- SCAN_CONFIGS.frontendPages,
57
- SCAN_CONFIGS.backendPages
58
- ];
59
- function checksum(value) {
60
- return crypto.createHash("md5").update(value).digest("hex");
61
- }
62
- function fileRecord(filePath, base, mode) {
63
- if (!fs.existsSync(filePath)) return null;
64
- let stat;
65
- try {
66
- stat = fs.statSync(filePath);
67
- } catch {
68
- return null;
69
- }
70
- if (!stat.isFile()) return null;
71
- const rel = path.relative(base, filePath).replace(/\\/g, "/");
72
- if (mode === "shape") {
73
- return `file:${rel}`;
74
- }
75
- try {
76
- return `file:${rel}:${stat.size}:${checksum(fs.readFileSync(filePath, "utf8"))}`;
77
- } catch {
78
- return `file:${rel}:unreadable`;
79
- }
80
- }
81
- function resolveCodeFile(base, relativePath) {
82
- const stripped = stripModuleCodeExtension(relativePath);
83
- const candidates = MODULE_CODE_EXTENSIONS.map((extension) => `${stripped}${extension}`);
84
- for (const candidate of candidates) {
85
- const filePath = path.join(base, ...candidate.split("/"));
86
- if (fs.existsSync(filePath)) return filePath;
87
- }
88
- return null;
89
- }
90
- function hasInlinePageMetadata(filePath) {
91
- try {
92
- const source = fs.readFileSync(filePath, "utf8");
93
- return /\bexport\s+(?:const|let|var|function|class)\s+metadata\b/.test(source) || /\bexport\s+\{[^}]*\bmetadata\b[^}]*\}/.test(source);
94
- } catch {
95
- return false;
96
- }
97
- }
98
- function addConventionRecords(records, roots) {
99
- for (const base of [roots.pkgBase, roots.appBase]) {
100
- records.push(`module-root:${base}:${fs.existsSync(base) ? "present" : "missing"}`);
101
- for (const relativePath of STRUCTURAL_CONVENTION_FILES) {
102
- const filePath = resolveCodeFile(base, relativePath);
103
- if (!filePath) {
104
- records.push(`missing:${base}:${relativePath}`);
105
- continue;
106
- }
107
- const record = fileRecord(filePath, base, "content");
108
- if (record) records.push(record);
109
- }
110
- }
111
- }
112
- function addScannedRecords(records, roots) {
113
- for (const config of CONTENT_SENSITIVE_SCAN_CONFIGS) {
114
- for (const scanned of scanModuleDir(roots, config)) {
115
- const base = scanned.fromApp ? roots.appBase : roots.pkgBase;
116
- const filePath = path.join(base, ...config.folder.split("/"), ...scanned.relPath.split("/"));
117
- const record = fileRecord(filePath, base, "content");
118
- if (record) records.push(`${config.folder}:${record}`);
119
- }
120
- }
121
- for (const config of ROUTE_SHAPE_SCAN_CONFIGS) {
122
- for (const scanned of scanModuleDir(roots, config)) {
123
- const base = scanned.fromApp ? roots.appBase : roots.pkgBase;
124
- const folderPath = path.join(base, ...config.folder.split("/"));
125
- const filePath = path.join(folderPath, ...scanned.relPath.split("/"));
126
- const pageRecord = fileRecord(filePath, base, hasInlinePageMetadata(filePath) ? "content" : "shape");
127
- if (pageRecord) records.push(`${config.folder}:${pageRecord}`);
128
- const dir = path.dirname(filePath);
129
- const stem = stripModuleCodeExtension(path.basename(filePath));
130
- const metaCandidates = stem === "page" ? ["page.meta", "meta"] : [`${stem}.meta`, "meta"];
131
- for (const candidate of metaCandidates) {
132
- const metaPath = resolveCodeFile(dir, candidate);
133
- if (!metaPath) continue;
134
- const record = fileRecord(metaPath, base, "content");
135
- if (record) records.push(`${config.folder}:meta:${record}`);
136
- }
137
- }
138
- }
139
- }
140
- function calculateGenerateWatchStructureChecksum(options) {
141
- const records = [];
142
- const modulesRecord = fileRecord(options.modulesFile, path.dirname(options.modulesFile), "content");
143
- records.push(modulesRecord ?? `missing:${options.modulesFile}`);
144
- for (const roots of options.moduleRoots) {
145
- addConventionRecords(records, roots);
146
- addScannedRecords(records, roots);
147
- }
148
- return checksum(records.sort((a, b) => a.localeCompare(b)).join("\n"));
149
- }
150
- export {
151
- calculateGenerateWatchStructureChecksum
152
- };
153
- //# sourceMappingURL=generate-watch-structure.js.map