@open-mercato/shared 0.6.7-develop.6677.1.beabb7ca12 → 0.6.7-develop.6686.1.bdda5ed397

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.
@@ -1,5 +1,6 @@
1
1
  import { findAppRoot } from "./appResolver.js";
2
2
  import { registerEntityIds } from "../encryption/entityIds.js";
3
+ import { createLogger } from "../logger/index.js";
3
4
  import {
4
5
  ensureMikroOrmV7GeneratedCacheCompatibility,
5
6
  recoverMikroOrmV7GeneratedCacheFromImportError
@@ -7,13 +8,21 @@ import {
7
8
  import path from "node:path";
8
9
  import fs from "node:fs";
9
10
  import { pathToFileURL } from "node:url";
11
+ const logger = createLogger("shared").child({ component: "bootstrap" });
12
+ class GeneratedFileNotFoundError extends Error {
13
+ constructor(filePath) {
14
+ super(`Generated file not found: ${filePath}`);
15
+ this.name = "GeneratedFileNotFoundError";
16
+ this.filePath = filePath;
17
+ }
18
+ }
10
19
  async function compileAndImport(tsPath, allowRecovery = true) {
11
20
  const jsPath = tsPath.replace(/\.ts$/, ".mjs");
12
21
  const appRoot = path.dirname(path.dirname(path.dirname(tsPath)));
13
22
  const tsExists = fs.existsSync(tsPath);
14
23
  const jsExists = fs.existsSync(jsPath);
15
24
  if (!tsExists) {
16
- throw new Error(`Generated file not found: ${tsPath}`);
25
+ throw new GeneratedFileNotFoundError(tsPath);
17
26
  }
18
27
  const needsCompile = !jsExists || fs.statSync(tsPath).mtimeMs > fs.statSync(jsPath).mtimeMs;
19
28
  if (needsCompile) {
@@ -73,6 +82,24 @@ async function compileAndImport(tsPath, allowRecovery = true) {
73
82
  return compileAndImport(tsPath, false);
74
83
  }
75
84
  }
85
+ async function loadOptionalGeneratedModule(tsPath, fallback) {
86
+ try {
87
+ return await compileAndImport(tsPath);
88
+ } catch (error) {
89
+ if (error instanceof GeneratedFileNotFoundError) {
90
+ logger.debug("Optional generated registry not present, using empty fallback", {
91
+ file: path.basename(tsPath)
92
+ });
93
+ return fallback;
94
+ }
95
+ logger.error("Failed to load generated registry, continuing without its entries", {
96
+ file: path.basename(tsPath),
97
+ filePath: tsPath,
98
+ err: error
99
+ });
100
+ return fallback;
101
+ }
102
+ }
76
103
  async function loadBootstrapData(appRoot) {
77
104
  const resolved = appRoot ? {
78
105
  generatedDir: path.join(appRoot, ".mercato", "generated"),
@@ -100,10 +127,12 @@ async function loadBootstrapData(appRoot) {
100
127
  compileAndImport(path.join(generatedDir, "modules.cli.generated.ts")),
101
128
  compileAndImport(path.join(generatedDir, "entities.generated.ts")),
102
129
  compileAndImport(path.join(generatedDir, "di.generated.ts")),
103
- compileAndImport(path.join(generatedDir, "search.generated.ts")).catch(() => ({ searchModuleConfigs: [] })),
104
- compileAndImport(path.join(generatedDir, "command-loaders.generated.ts")).catch(() => ({ commandLoaderEntries: [] })),
105
- compileAndImport(path.join(generatedDir, "command-interceptors.generated.ts")).catch(() => ({ commandInterceptorEntries: [] })),
106
- compileAndImport(path.join(generatedDir, "workflows.generated.ts")).catch(() => ({ allCodeWorkflows: [] }))
130
+ loadOptionalGeneratedModule(path.join(generatedDir, "search.generated.ts"), { searchModuleConfigs: [] }),
131
+ loadOptionalGeneratedModule(path.join(generatedDir, "command-loaders.generated.ts"), { commandLoaderEntries: [] }),
132
+ loadOptionalGeneratedModule(path.join(generatedDir, "command-interceptors.generated.ts"), {
133
+ commandInterceptorEntries: []
134
+ }),
135
+ loadOptionalGeneratedModule(path.join(generatedDir, "workflows.generated.ts"), { allCodeWorkflows: [] })
107
136
  ]);
108
137
  return {
109
138
  modules: modulesModule.modules,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/bootstrap/dynamicLoader.ts"],
4
- "sourcesContent": ["import type { BootstrapData } from './types'\nimport { findAppRoot, type AppRoot } from './appResolver'\nimport { registerEntityIds } from '../encryption/entityIds'\nimport {\n ensureMikroOrmV7GeneratedCacheCompatibility,\n recoverMikroOrmV7GeneratedCacheFromImportError,\n} from './generatedCacheRecovery'\nimport path from 'node:path'\nimport fs from 'node:fs'\nimport { pathToFileURL } from 'node:url'\n\n/**\n * Compile a TypeScript file to JavaScript using esbuild bundler.\n * This bundles the file and all its dependencies, handling JSON imports properly.\n * The compiled file is written next to the source file with a .mjs extension.\n */\nasync function compileAndImport(tsPath: string, allowRecovery: boolean = true): Promise<Record<string, unknown>> {\n const jsPath = tsPath.replace(/\\.ts$/, '.mjs')\n const appRoot = path.dirname(path.dirname(path.dirname(tsPath)))\n\n // Check if we need to recompile (source newer than compiled)\n const tsExists = fs.existsSync(tsPath)\n const jsExists = fs.existsSync(jsPath)\n\n if (!tsExists) {\n throw new Error(`Generated file not found: ${tsPath}`)\n }\n\n const needsCompile = !jsExists ||\n fs.statSync(tsPath).mtimeMs > fs.statSync(jsPath).mtimeMs\n\n if (needsCompile) {\n // Dynamically import esbuild only when needed\n const esbuild = await import('esbuild')\n\n // Plugin to resolve @/ alias to app root (works for @app modules)\n const aliasPlugin: import('esbuild').Plugin = {\n name: 'alias-resolver',\n setup(build) {\n // Resolve @/ alias to app root\n build.onResolve({ filter: /^@\\// }, (args) => {\n const resolved = path.join(appRoot, args.path.slice(2))\n // Try with .ts extension if base path doesn't exist\n if (!fs.existsSync(resolved) && fs.existsSync(resolved + '.ts')) {\n return { path: resolved + '.ts' }\n }\n // Also check for /index.ts if it's a directory\n if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory() && fs.existsSync(path.join(resolved, 'index.ts'))) {\n return { path: path.join(resolved, 'index.ts') }\n }\n return { path: resolved }\n })\n },\n }\n\n // Plugin to mark non-JSON package imports as external\n const externalNonJsonPlugin: import('esbuild').Plugin = {\n name: 'external-non-json',\n setup(build) {\n // Mark all package imports as external EXCEPT JSON files\n // Filter matches paths that don't start with . or / (package imports like @open-mercato/shared)\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n // Skip Windows absolute paths (e.g., C:\\...) - they're local files, not packages\n if (/^[a-zA-Z]:/.test(args.path)) {\n return null // Let esbuild handle it\n }\n // If it's a JSON file, let esbuild bundle it\n if (args.path.endsWith('.json')) {\n return null // Let esbuild handle it\n }\n // Otherwise mark as external\n return { path: args.path, external: true }\n })\n },\n }\n\n // Use esbuild.build with bundling to handle JSON imports\n await esbuild.build({\n entryPoints: [tsPath],\n outfile: jsPath,\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n plugins: [aliasPlugin, externalNonJsonPlugin],\n // Allow JSON imports\n loader: { '.json': 'json' },\n })\n }\n\n // Import the compiled JavaScript\n try {\n const fileUrl = `${pathToFileURL(jsPath).href}?mtime=${fs.statSync(jsPath).mtimeMs}`\n return await import(fileUrl)\n } catch (error) {\n if (!allowRecovery) {\n throw error\n }\n\n const recovered = recoverMikroOrmV7GeneratedCacheFromImportError(appRoot, error)\n if (!recovered.applied) {\n throw error\n }\n\n return compileAndImport(tsPath, false)\n }\n}\n\n\n/**\n * Dynamically load bootstrap data from a resolved app directory.\n *\n * IMPORTANT: This only works in unbundled contexts (CLI, tsx).\n * Do NOT use this in Next.js bundled code - use static imports instead.\n *\n * For CLI context, we skip loading modules.generated.ts which has Next.js dependencies.\n * CLI commands are discovered separately via the CLI module system.\n *\n * @param appRoot - Optional explicit app root path. If not provided, will search from cwd.\n * @returns The loaded bootstrap data\n * @throws Error if app root cannot be found or generated files are missing\n */\nexport async function loadBootstrapData(appRoot?: string): Promise<BootstrapData> {\n const resolved: AppRoot | null = appRoot\n ? {\n generatedDir: path.join(appRoot, '.mercato', 'generated'),\n appDir: appRoot,\n mercatoDir: path.join(appRoot, '.mercato'),\n }\n : findAppRoot()\n\n if (!resolved) {\n throw new Error(\n 'Could not find app root with .mercato/generated directory. ' +\n 'Make sure you run this command from within a Next.js app directory, ' +\n 'or run \"yarn mercato generate\" first to create the generated files.',\n )\n }\n\n const { generatedDir } = resolved\n\n ensureMikroOrmV7GeneratedCacheCompatibility(resolved.appDir)\n\n // IMPORTANT: Load entity IDs FIRST and register them before loading modules.\n // This is because modules (e.g., ce.ts files) use E.xxx.xxx at module scope,\n // and they need entity IDs to be available when they're imported.\n const entityIdsModule = await compileAndImport(path.join(generatedDir, 'entities.ids.generated.ts'))\n registerEntityIds(entityIdsModule.E as BootstrapData['entityIds'])\n\n // Now load the rest of the generated files.\n // modules.cli.generated.ts excludes Next.js-dependent code (routes, APIs, widgets)\n const [\n modulesModule,\n entitiesModule,\n diModule,\n searchModule,\n commandLoadersModule,\n commandInterceptorsModule,\n workflowsModule,\n ] = await Promise.all([\n compileAndImport(path.join(generatedDir, 'modules.cli.generated.ts')),\n compileAndImport(path.join(generatedDir, 'entities.generated.ts')),\n compileAndImport(path.join(generatedDir, 'di.generated.ts')),\n compileAndImport(path.join(generatedDir, 'search.generated.ts')).catch(() => ({ searchModuleConfigs: [] })),\n compileAndImport(path.join(generatedDir, 'command-loaders.generated.ts')).catch(() => ({ commandLoaderEntries: [] })),\n compileAndImport(path.join(generatedDir, 'command-interceptors.generated.ts')).catch(() => ({ commandInterceptorEntries: [] })),\n compileAndImport(path.join(generatedDir, 'workflows.generated.ts')).catch(() => ({ allCodeWorkflows: [] })),\n ])\n\n return {\n modules: modulesModule.modules as BootstrapData['modules'],\n entities: entitiesModule.entities as BootstrapData['entities'],\n diRegistrars: diModule.diRegistrars as BootstrapData['diRegistrars'],\n entityIds: entityIdsModule.E as BootstrapData['entityIds'],\n // Search configs are needed by workers for indexing\n searchModuleConfigs: (searchModule.searchModuleConfigs ?? []) as BootstrapData['searchModuleConfigs'],\n commandLoaderEntries: (commandLoadersModule.commandLoaderEntries ?? []) as BootstrapData['commandLoaderEntries'],\n // Command interceptors must apply in worker/CLI processes too \u2014 the\n // interceptor registry is per-process, so relying on the Next.js runtime's\n // registration silently no-ops every interceptor for queued/CLI commands\n // (#4327).\n commandInterceptorEntries: (commandInterceptorsModule.commandInterceptorEntries ??\n []) as BootstrapData['commandInterceptorEntries'],\n // Code workflow definitions are needed by workers to resume code-defined instances\n codeWorkflows: (workflowsModule.allCodeWorkflows ?? []) as BootstrapData['codeWorkflows'],\n // Empty UI-related data - not needed for CLI\n dashboardWidgetEntries: [],\n injectionWidgetEntries: [],\n injectionTables: [],\n interceptorEntries: [],\n componentOverrideEntries: [],\n }\n}\n\n/**\n * Create and execute bootstrap in CLI context.\n *\n * This is a convenience function that finds the app root, loads the generated\n * data dynamically, and runs bootstrap. Use this in CLI entry points.\n *\n * Returns the loaded bootstrap data so the CLI can register modules directly\n * (avoids module resolution issues when importing @open-mercato/cli/mercato).\n *\n * @param appRoot - Optional explicit app root path\n * @returns The loaded bootstrap data (modules, entities, etc.)\n */\nexport async function bootstrapFromAppRoot(appRoot?: string): Promise<BootstrapData> {\n const { createBootstrap, waitForAsyncRegistration } = await import('./factory.js')\n const data = await loadBootstrapData(appRoot)\n const bootstrap = createBootstrap(data)\n bootstrap()\n // In CLI context, wait for async registrations (UI widgets, search configs, etc.)\n await waitForAsyncRegistration()\n\n return data\n}\n"],
5
- "mappings": "AACA,SAAS,mBAAiC;AAC1C,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAO9B,eAAe,iBAAiB,QAAgB,gBAAyB,MAAwC;AAC/G,QAAM,SAAS,OAAO,QAAQ,SAAS,MAAM;AAC7C,QAAM,UAAU,KAAK,QAAQ,KAAK,QAAQ,KAAK,QAAQ,MAAM,CAAC,CAAC;AAG/D,QAAM,WAAW,GAAG,WAAW,MAAM;AACrC,QAAM,WAAW,GAAG,WAAW,MAAM;AAErC,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,6BAA6B,MAAM,EAAE;AAAA,EACvD;AAEA,QAAM,eAAe,CAAC,YACpB,GAAG,SAAS,MAAM,EAAE,UAAU,GAAG,SAAS,MAAM,EAAE;AAEpD,MAAI,cAAc;AAEhB,UAAM,UAAU,MAAM,OAAO,SAAS;AAGtC,UAAM,cAAwC;AAAA,MAC5C,MAAM;AAAA,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AAE,EAAE;AAAA,IAC9H,iBAAiB,KAAK,KAAK,cAAc,wBAAwB,CAAC,EAAE,MAAM,OAAO,EAAE,kBAAkB,CAAC,EAAE,EAAE;AAAA,EAC5G,CAAC;AAED,SAAO;AAAA,IACL,SAAS,cAAc;AAAA,IACvB,UAAU,eAAe;AAAA,IACzB,cAAc,SAAS;AAAA,IACvB,WAAW,gBAAgB;AAAA;AAAA,IAE3B,qBAAsB,aAAa,uBAAuB,CAAC;AAAA,IAC3D,sBAAuB,qBAAqB,wBAAwB,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,IAKrE,2BAA4B,0BAA0B,6BACpD,CAAC;AAAA;AAAA,IAEH,eAAgB,gBAAgB,oBAAoB,CAAC;AAAA;AAAA,IAErD,wBAAwB,CAAC;AAAA,IACzB,wBAAwB,CAAC;AAAA,IACzB,iBAAiB,CAAC;AAAA,IAClB,oBAAoB,CAAC;AAAA,IACrB,0BAA0B,CAAC;AAAA,EAC7B;AACF;AAcA,eAAsB,qBAAqB,SAA0C;AACnF,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,cAAc;AACjF,QAAM,OAAO,MAAM,kBAAkB,OAAO;AAC5C,QAAM,YAAY,gBAAgB,IAAI;AACtC,YAAU;AAEV,QAAM,yBAAyB;AAE/B,SAAO;AACT;",
4
+ "sourcesContent": ["import type { BootstrapData } from './types'\nimport { findAppRoot, type AppRoot } from './appResolver'\nimport { registerEntityIds } from '../encryption/entityIds'\nimport { createLogger } from '../logger'\nimport {\n ensureMikroOrmV7GeneratedCacheCompatibility,\n recoverMikroOrmV7GeneratedCacheFromImportError,\n} from './generatedCacheRecovery'\nimport path from 'node:path'\nimport fs from 'node:fs'\nimport { pathToFileURL } from 'node:url'\n\nconst logger = createLogger('shared').child({ component: 'bootstrap' })\n\n/**\n * Thrown when an expected generated source file is absent.\n *\n * Optional registries treat this as the supported compatibility case (an app\n * that never generated the file), which is what makes it distinguishable from\n * a file that exists but fails to compile or import.\n */\nclass GeneratedFileNotFoundError extends Error {\n readonly filePath: string\n\n constructor(filePath: string) {\n super(`Generated file not found: ${filePath}`)\n this.name = 'GeneratedFileNotFoundError'\n this.filePath = filePath\n }\n}\n\n/**\n * Compile a TypeScript file to JavaScript using esbuild bundler.\n * This bundles the file and all its dependencies, handling JSON imports properly.\n * The compiled file is written next to the source file with a .mjs extension.\n */\nasync function compileAndImport(tsPath: string, allowRecovery: boolean = true): Promise<Record<string, unknown>> {\n const jsPath = tsPath.replace(/\\.ts$/, '.mjs')\n const appRoot = path.dirname(path.dirname(path.dirname(tsPath)))\n\n // Check if we need to recompile (source newer than compiled)\n const tsExists = fs.existsSync(tsPath)\n const jsExists = fs.existsSync(jsPath)\n\n if (!tsExists) {\n throw new GeneratedFileNotFoundError(tsPath)\n }\n\n const needsCompile = !jsExists ||\n fs.statSync(tsPath).mtimeMs > fs.statSync(jsPath).mtimeMs\n\n if (needsCompile) {\n // Dynamically import esbuild only when needed\n const esbuild = await import('esbuild')\n\n // Plugin to resolve @/ alias to app root (works for @app modules)\n const aliasPlugin: import('esbuild').Plugin = {\n name: 'alias-resolver',\n setup(build) {\n // Resolve @/ alias to app root\n build.onResolve({ filter: /^@\\// }, (args) => {\n const resolved = path.join(appRoot, args.path.slice(2))\n // Try with .ts extension if base path doesn't exist\n if (!fs.existsSync(resolved) && fs.existsSync(resolved + '.ts')) {\n return { path: resolved + '.ts' }\n }\n // Also check for /index.ts if it's a directory\n if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory() && fs.existsSync(path.join(resolved, 'index.ts'))) {\n return { path: path.join(resolved, 'index.ts') }\n }\n return { path: resolved }\n })\n },\n }\n\n // Plugin to mark non-JSON package imports as external\n const externalNonJsonPlugin: import('esbuild').Plugin = {\n name: 'external-non-json',\n setup(build) {\n // Mark all package imports as external EXCEPT JSON files\n // Filter matches paths that don't start with . or / (package imports like @open-mercato/shared)\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n // Skip Windows absolute paths (e.g., C:\\...) - they're local files, not packages\n if (/^[a-zA-Z]:/.test(args.path)) {\n return null // Let esbuild handle it\n }\n // If it's a JSON file, let esbuild bundle it\n if (args.path.endsWith('.json')) {\n return null // Let esbuild handle it\n }\n // Otherwise mark as external\n return { path: args.path, external: true }\n })\n },\n }\n\n // Use esbuild.build with bundling to handle JSON imports\n await esbuild.build({\n entryPoints: [tsPath],\n outfile: jsPath,\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n plugins: [aliasPlugin, externalNonJsonPlugin],\n // Allow JSON imports\n loader: { '.json': 'json' },\n })\n }\n\n // Import the compiled JavaScript\n try {\n const fileUrl = `${pathToFileURL(jsPath).href}?mtime=${fs.statSync(jsPath).mtimeMs}`\n return await import(fileUrl)\n } catch (error) {\n if (!allowRecovery) {\n throw error\n }\n\n const recovered = recoverMikroOrmV7GeneratedCacheFromImportError(appRoot, error)\n if (!recovered.applied) {\n throw error\n }\n\n return compileAndImport(tsPath, false)\n }\n}\n\n\n/**\n * Load a generated registry that older apps may not have generated yet.\n *\n * An absent source file is the supported compatibility case and resolves to\n * `fallback` quietly. Any other failure \u2014 a compile error, a broken import, a\n * runtime throw at module scope \u2014 still resolves to `fallback` so bootstrap\n * keeps working, but is reported at error level: a registry that silently\n * degrades to nothing is exactly how command interceptors stopped applying in\n * worker/CLI processes (#4327, #4491).\n */\nasync function loadOptionalGeneratedModule(\n tsPath: string,\n fallback: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n try {\n return await compileAndImport(tsPath)\n } catch (error) {\n if (error instanceof GeneratedFileNotFoundError) {\n logger.debug('Optional generated registry not present, using empty fallback', {\n file: path.basename(tsPath),\n })\n return fallback\n }\n\n logger.error('Failed to load generated registry, continuing without its entries', {\n file: path.basename(tsPath),\n filePath: tsPath,\n err: error,\n })\n return fallback\n }\n}\n\n/**\n * Dynamically load bootstrap data from a resolved app directory.\n *\n * IMPORTANT: This only works in unbundled contexts (CLI, tsx).\n * Do NOT use this in Next.js bundled code - use static imports instead.\n *\n * For CLI context, we skip loading modules.generated.ts which has Next.js dependencies.\n * CLI commands are discovered separately via the CLI module system.\n *\n * @param appRoot - Optional explicit app root path. If not provided, will search from cwd.\n * @returns The loaded bootstrap data\n * @throws Error if app root cannot be found or generated files are missing\n */\nexport async function loadBootstrapData(appRoot?: string): Promise<BootstrapData> {\n const resolved: AppRoot | null = appRoot\n ? {\n generatedDir: path.join(appRoot, '.mercato', 'generated'),\n appDir: appRoot,\n mercatoDir: path.join(appRoot, '.mercato'),\n }\n : findAppRoot()\n\n if (!resolved) {\n throw new Error(\n 'Could not find app root with .mercato/generated directory. ' +\n 'Make sure you run this command from within a Next.js app directory, ' +\n 'or run \"yarn mercato generate\" first to create the generated files.',\n )\n }\n\n const { generatedDir } = resolved\n\n ensureMikroOrmV7GeneratedCacheCompatibility(resolved.appDir)\n\n // IMPORTANT: Load entity IDs FIRST and register them before loading modules.\n // This is because modules (e.g., ce.ts files) use E.xxx.xxx at module scope,\n // and they need entity IDs to be available when they're imported.\n const entityIdsModule = await compileAndImport(path.join(generatedDir, 'entities.ids.generated.ts'))\n registerEntityIds(entityIdsModule.E as BootstrapData['entityIds'])\n\n // Now load the rest of the generated files.\n // modules.cli.generated.ts excludes Next.js-dependent code (routes, APIs, widgets)\n const [\n modulesModule,\n entitiesModule,\n diModule,\n searchModule,\n commandLoadersModule,\n commandInterceptorsModule,\n workflowsModule,\n ] = await Promise.all([\n compileAndImport(path.join(generatedDir, 'modules.cli.generated.ts')),\n compileAndImport(path.join(generatedDir, 'entities.generated.ts')),\n compileAndImport(path.join(generatedDir, 'di.generated.ts')),\n loadOptionalGeneratedModule(path.join(generatedDir, 'search.generated.ts'), { searchModuleConfigs: [] }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'command-loaders.generated.ts'), { commandLoaderEntries: [] }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'command-interceptors.generated.ts'), {\n commandInterceptorEntries: [],\n }),\n loadOptionalGeneratedModule(path.join(generatedDir, 'workflows.generated.ts'), { allCodeWorkflows: [] }),\n ])\n\n return {\n modules: modulesModule.modules as BootstrapData['modules'],\n entities: entitiesModule.entities as BootstrapData['entities'],\n diRegistrars: diModule.diRegistrars as BootstrapData['diRegistrars'],\n entityIds: entityIdsModule.E as BootstrapData['entityIds'],\n // Search configs are needed by workers for indexing\n searchModuleConfigs: (searchModule.searchModuleConfigs ?? []) as BootstrapData['searchModuleConfigs'],\n commandLoaderEntries: (commandLoadersModule.commandLoaderEntries ?? []) as BootstrapData['commandLoaderEntries'],\n // Command interceptors must apply in worker/CLI processes too \u2014 the\n // interceptor registry is per-process, so relying on the Next.js runtime's\n // registration silently no-ops every interceptor for queued/CLI commands\n // (#4327).\n commandInterceptorEntries: (commandInterceptorsModule.commandInterceptorEntries ??\n []) as BootstrapData['commandInterceptorEntries'],\n // Code workflow definitions are needed by workers to resume code-defined instances\n codeWorkflows: (workflowsModule.allCodeWorkflows ?? []) as BootstrapData['codeWorkflows'],\n // Empty UI-related data - not needed for CLI\n dashboardWidgetEntries: [],\n injectionWidgetEntries: [],\n injectionTables: [],\n interceptorEntries: [],\n componentOverrideEntries: [],\n }\n}\n\n/**\n * Create and execute bootstrap in CLI context.\n *\n * This is a convenience function that finds the app root, loads the generated\n * data dynamically, and runs bootstrap. Use this in CLI entry points.\n *\n * Returns the loaded bootstrap data so the CLI can register modules directly\n * (avoids module resolution issues when importing @open-mercato/cli/mercato).\n *\n * @param appRoot - Optional explicit app root path\n * @returns The loaded bootstrap data (modules, entities, etc.)\n */\nexport async function bootstrapFromAppRoot(appRoot?: string): Promise<BootstrapData> {\n const { createBootstrap, waitForAsyncRegistration } = await import('./factory.js')\n const data = await loadBootstrapData(appRoot)\n const bootstrap = createBootstrap(data)\n bootstrap()\n // In CLI context, wait for async registrations (UI widgets, search configs, etc.)\n await waitForAsyncRegistration()\n\n return data\n}\n"],
5
+ "mappings": "AACA,SAAS,mBAAiC;AAC1C,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B;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;AAED,SAAO;AAAA,IACL,SAAS,cAAc;AAAA,IACvB,UAAU,eAAe;AAAA,IACzB,cAAc,SAAS;AAAA,IACvB,WAAW,gBAAgB;AAAA;AAAA,IAE3B,qBAAsB,aAAa,uBAAuB,CAAC;AAAA,IAC3D,sBAAuB,qBAAqB,wBAAwB,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,IAKrE,2BAA4B,0BAA0B,6BACpD,CAAC;AAAA;AAAA,IAEH,eAAgB,gBAAgB,oBAAoB,CAAC;AAAA;AAAA,IAErD,wBAAwB,CAAC;AAAA,IACzB,wBAAwB,CAAC;AAAA,IACzB,iBAAiB,CAAC;AAAA,IAClB,oBAAoB,CAAC;AAAA,IACrB,0BAA0B,CAAC;AAAA,EAC7B;AACF;AAcA,eAAsB,qBAAqB,SAA0C;AACnF,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,cAAc;AACjF,QAAM,OAAO,MAAM,kBAAkB,OAAO;AAC5C,QAAM,YAAY,gBAAgB,IAAI;AACtC,YAAU;AAEV,QAAM,yBAAyB;AAE/B,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,4 @@
1
- const APP_VERSION = "0.6.7-develop.6677.1.beabb7ca12";
1
+ const APP_VERSION = "0.6.7-develop.6686.1.bdda5ed397";
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.6.7-develop.6677.1.beabb7ca12'\nexport const appVersion = APP_VERSION\n"],
4
+ "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.6.7-develop.6686.1.bdda5ed397'\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.6.7-develop.6677.1.beabb7ca12",
3
+ "version": "0.6.7-develop.6686.1.bdda5ed397",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -97,7 +97,7 @@
97
97
  "@mikro-orm/core": "^7.1.5",
98
98
  "@mikro-orm/decorators": "^7.1.5",
99
99
  "@mikro-orm/postgresql": "^7.1.5",
100
- "@open-mercato/cache": "0.6.7-develop.6677.1.beabb7ca12",
100
+ "@open-mercato/cache": "0.6.7-develop.6686.1.bdda5ed397",
101
101
  "@types/sanitize-html": "^2.16.1",
102
102
  "dotenv": "^17.4.2",
103
103
  "pino": "^10.3.1",
@@ -13,12 +13,33 @@
13
13
  * The .mjs stubs use module.exports because Jest's CJS runtime handles the
14
14
  * dynamic import() and does not transform .mjs files; the loader consumes the
15
15
  * named exports identically either way.
16
+ *
17
+ * The third case guards #4491: the compatibility fallback to an empty list must
18
+ * stay silent for an absent registry, but must report a registry that exists and
19
+ * fails to load — otherwise the #4327 condition can recur with no diagnostics.
16
20
  */
21
+ jest.mock('../../logger', () => {
22
+ const logger = {
23
+ debug: jest.fn(),
24
+ info: jest.fn(),
25
+ warn: jest.fn(),
26
+ error: jest.fn(),
27
+ child: () => logger,
28
+ }
29
+ return { createLogger: () => logger }
30
+ })
31
+
17
32
  import fs from 'node:fs'
18
33
  import os from 'node:os'
19
34
  import path from 'node:path'
35
+ import { createLogger } from '../../logger'
20
36
  import { loadBootstrapData } from '../dynamicLoader'
21
37
 
38
+ const mockedLogger = createLogger('shared') as unknown as {
39
+ debug: jest.Mock
40
+ error: jest.Mock
41
+ }
42
+
22
43
  const GENERATED_MODULES: Record<string, { ts: string; compiled: string }> = {
23
44
  'entities.ids.generated': { ts: 'export const E = {}', compiled: 'module.exports = { E: {} }' },
24
45
  'modules.cli.generated': { ts: 'export const modules = []', compiled: 'module.exports = { modules: [] }' },
@@ -39,20 +60,35 @@ function writeGeneratedModule(generatedDir: string, baseName: string, source: {
39
60
  fs.utimesSync(path.join(generatedDir, `${baseName}.mjs`), fresh, fresh)
40
61
  }
41
62
 
63
+ const createdAppRoots: string[] = []
64
+
65
+ function createAppRoot(overrides: Record<string, { ts: string; compiled: string }> = {}): string {
66
+ const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-bootstrap-4327-'))
67
+ const generatedDir = path.join(appRoot, '.mercato', 'generated')
68
+ fs.mkdirSync(generatedDir, { recursive: true })
69
+ for (const [baseName, source] of Object.entries({ ...GENERATED_MODULES, ...overrides })) {
70
+ writeGeneratedModule(generatedDir, baseName, source)
71
+ }
72
+ createdAppRoots.push(appRoot)
73
+ return appRoot
74
+ }
75
+
42
76
  describe('loadBootstrapData — command interceptors reach worker/CLI bootstrap (#4327)', () => {
43
77
  let appRoot: string
44
78
 
45
79
  beforeAll(() => {
46
- appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-bootstrap-4327-'))
47
- const generatedDir = path.join(appRoot, '.mercato', 'generated')
48
- fs.mkdirSync(generatedDir, { recursive: true })
49
- for (const [baseName, source] of Object.entries(GENERATED_MODULES)) {
50
- writeGeneratedModule(generatedDir, baseName, source)
51
- }
80
+ appRoot = createAppRoot()
52
81
  })
53
82
 
54
83
  afterAll(() => {
55
- fs.rmSync(appRoot, { recursive: true, force: true })
84
+ for (const root of createdAppRoots) {
85
+ fs.rmSync(root, { recursive: true, force: true })
86
+ }
87
+ })
88
+
89
+ beforeEach(() => {
90
+ mockedLogger.debug.mockClear()
91
+ mockedLogger.error.mockClear()
56
92
  })
57
93
 
58
94
  it('returns commandInterceptorEntries from command-interceptors.generated', async () => {
@@ -72,5 +108,24 @@ describe('loadBootstrapData — command interceptors reach worker/CLI bootstrap
72
108
 
73
109
  expect(data.commandInterceptorEntries).toEqual([])
74
110
  expect(data.commandLoaderEntries).toEqual([])
111
+ expect(mockedLogger.error).not.toHaveBeenCalled()
112
+ })
113
+
114
+ it('logs an error when the generated file exists but fails to import (#4491)', async () => {
115
+ const brokenAppRoot = createAppRoot({
116
+ 'command-interceptors.generated': {
117
+ ts: 'export const commandInterceptorEntries = []',
118
+ compiled: "throw new Error('command-interceptors.generated is broken')",
119
+ },
120
+ })
121
+
122
+ const data = await loadBootstrapData(brokenAppRoot)
123
+
124
+ expect(data.commandInterceptorEntries).toEqual([])
125
+ expect(mockedLogger.error).toHaveBeenCalledTimes(1)
126
+ const [message, fields] = mockedLogger.error.mock.calls[0] as [string, Record<string, unknown>]
127
+ expect(message).toContain('Failed to load generated registry')
128
+ expect(fields.file).toBe('command-interceptors.generated.ts')
129
+ expect((fields.err as Error).message).toContain('command-interceptors.generated is broken')
75
130
  })
76
131
  })
@@ -1,6 +1,7 @@
1
1
  import type { BootstrapData } from './types'
2
2
  import { findAppRoot, type AppRoot } from './appResolver'
3
3
  import { registerEntityIds } from '../encryption/entityIds'
4
+ import { createLogger } from '../logger'
4
5
  import {
5
6
  ensureMikroOrmV7GeneratedCacheCompatibility,
6
7
  recoverMikroOrmV7GeneratedCacheFromImportError,
@@ -9,6 +10,25 @@ import path from 'node:path'
9
10
  import fs from 'node:fs'
10
11
  import { pathToFileURL } from 'node:url'
11
12
 
13
+ const logger = createLogger('shared').child({ component: 'bootstrap' })
14
+
15
+ /**
16
+ * Thrown when an expected generated source file is absent.
17
+ *
18
+ * Optional registries treat this as the supported compatibility case (an app
19
+ * that never generated the file), which is what makes it distinguishable from
20
+ * a file that exists but fails to compile or import.
21
+ */
22
+ class GeneratedFileNotFoundError extends Error {
23
+ readonly filePath: string
24
+
25
+ constructor(filePath: string) {
26
+ super(`Generated file not found: ${filePath}`)
27
+ this.name = 'GeneratedFileNotFoundError'
28
+ this.filePath = filePath
29
+ }
30
+ }
31
+
12
32
  /**
13
33
  * Compile a TypeScript file to JavaScript using esbuild bundler.
14
34
  * This bundles the file and all its dependencies, handling JSON imports properly.
@@ -23,7 +43,7 @@ async function compileAndImport(tsPath: string, allowRecovery: boolean = true):
23
43
  const jsExists = fs.existsSync(jsPath)
24
44
 
25
45
  if (!tsExists) {
26
- throw new Error(`Generated file not found: ${tsPath}`)
46
+ throw new GeneratedFileNotFoundError(tsPath)
27
47
  }
28
48
 
29
49
  const needsCompile = !jsExists ||
@@ -107,6 +127,39 @@ async function compileAndImport(tsPath: string, allowRecovery: boolean = true):
107
127
  }
108
128
 
109
129
 
130
+ /**
131
+ * Load a generated registry that older apps may not have generated yet.
132
+ *
133
+ * An absent source file is the supported compatibility case and resolves to
134
+ * `fallback` quietly. Any other failure — a compile error, a broken import, a
135
+ * runtime throw at module scope — still resolves to `fallback` so bootstrap
136
+ * keeps working, but is reported at error level: a registry that silently
137
+ * degrades to nothing is exactly how command interceptors stopped applying in
138
+ * worker/CLI processes (#4327, #4491).
139
+ */
140
+ async function loadOptionalGeneratedModule(
141
+ tsPath: string,
142
+ fallback: Record<string, unknown>,
143
+ ): Promise<Record<string, unknown>> {
144
+ try {
145
+ return await compileAndImport(tsPath)
146
+ } catch (error) {
147
+ if (error instanceof GeneratedFileNotFoundError) {
148
+ logger.debug('Optional generated registry not present, using empty fallback', {
149
+ file: path.basename(tsPath),
150
+ })
151
+ return fallback
152
+ }
153
+
154
+ logger.error('Failed to load generated registry, continuing without its entries', {
155
+ file: path.basename(tsPath),
156
+ filePath: tsPath,
157
+ err: error,
158
+ })
159
+ return fallback
160
+ }
161
+ }
162
+
110
163
  /**
111
164
  * Dynamically load bootstrap data from a resolved app directory.
112
165
  *
@@ -161,10 +214,12 @@ export async function loadBootstrapData(appRoot?: string): Promise<BootstrapData
161
214
  compileAndImport(path.join(generatedDir, 'modules.cli.generated.ts')),
162
215
  compileAndImport(path.join(generatedDir, 'entities.generated.ts')),
163
216
  compileAndImport(path.join(generatedDir, 'di.generated.ts')),
164
- compileAndImport(path.join(generatedDir, 'search.generated.ts')).catch(() => ({ searchModuleConfigs: [] })),
165
- compileAndImport(path.join(generatedDir, 'command-loaders.generated.ts')).catch(() => ({ commandLoaderEntries: [] })),
166
- compileAndImport(path.join(generatedDir, 'command-interceptors.generated.ts')).catch(() => ({ commandInterceptorEntries: [] })),
167
- compileAndImport(path.join(generatedDir, 'workflows.generated.ts')).catch(() => ({ allCodeWorkflows: [] })),
217
+ loadOptionalGeneratedModule(path.join(generatedDir, 'search.generated.ts'), { searchModuleConfigs: [] }),
218
+ loadOptionalGeneratedModule(path.join(generatedDir, 'command-loaders.generated.ts'), { commandLoaderEntries: [] }),
219
+ loadOptionalGeneratedModule(path.join(generatedDir, 'command-interceptors.generated.ts'), {
220
+ commandInterceptorEntries: [],
221
+ }),
222
+ loadOptionalGeneratedModule(path.join(generatedDir, 'workflows.generated.ts'), { allCodeWorkflows: [] }),
168
223
  ])
169
224
 
170
225
  return {