@open-mercato/cli 0.6.6-develop.6493.1.333455a884 → 0.6.6-develop.6505.1.6f6b83559f

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.
Files changed (85) hide show
  1. package/.turbo/turbo-build.log +1 -2
  2. package/build.mjs +6 -29
  3. package/dist/agentic/guides/module-facts.json +53 -53
  4. package/dist/agentic/guides/modules/ai_assistant.md +1 -1
  5. package/dist/agentic/guides/modules/api_docs.md +1 -1
  6. package/dist/agentic/guides/modules/api_keys.md +1 -1
  7. package/dist/agentic/guides/modules/attachments.md +1 -1
  8. package/dist/agentic/guides/modules/audit_logs.md +1 -1
  9. package/dist/agentic/guides/modules/auth.md +1 -1
  10. package/dist/agentic/guides/modules/business_rules.md +1 -1
  11. package/dist/agentic/guides/modules/catalog.md +1 -1
  12. package/dist/agentic/guides/modules/channel_gmail.md +1 -1
  13. package/dist/agentic/guides/modules/channel_imap.md +1 -1
  14. package/dist/agentic/guides/modules/checkout.md +1 -1
  15. package/dist/agentic/guides/modules/communication_channels.md +1 -1
  16. package/dist/agentic/guides/modules/configs.md +1 -1
  17. package/dist/agentic/guides/modules/content.md +1 -1
  18. package/dist/agentic/guides/modules/currencies.md +1 -1
  19. package/dist/agentic/guides/modules/customer_accounts.md +1 -1
  20. package/dist/agentic/guides/modules/customers.md +1 -1
  21. package/dist/agentic/guides/modules/dashboards.md +1 -1
  22. package/dist/agentic/guides/modules/data_sync.md +1 -1
  23. package/dist/agentic/guides/modules/dictionaries.md +1 -1
  24. package/dist/agentic/guides/modules/directory.md +1 -1
  25. package/dist/agentic/guides/modules/entities.md +1 -1
  26. package/dist/agentic/guides/modules/events.md +1 -1
  27. package/dist/agentic/guides/modules/feature_toggles.md +1 -1
  28. package/dist/agentic/guides/modules/gateway_stripe.md +1 -1
  29. package/dist/agentic/guides/modules/generators.md +1 -1
  30. package/dist/agentic/guides/modules/inbox_ops.md +1 -1
  31. package/dist/agentic/guides/modules/integrations.md +1 -1
  32. package/dist/agentic/guides/modules/messages.md +1 -1
  33. package/dist/agentic/guides/modules/notifications.md +1 -1
  34. package/dist/agentic/guides/modules/onboarding.md +1 -1
  35. package/dist/agentic/guides/modules/payment_gateways.md +1 -1
  36. package/dist/agentic/guides/modules/perspectives.md +1 -1
  37. package/dist/agentic/guides/modules/planner.md +1 -1
  38. package/dist/agentic/guides/modules/portal.md +1 -1
  39. package/dist/agentic/guides/modules/progress.md +1 -1
  40. package/dist/agentic/guides/modules/query_index.md +1 -1
  41. package/dist/agentic/guides/modules/record_locks.md +1 -1
  42. package/dist/agentic/guides/modules/resources.md +1 -1
  43. package/dist/agentic/guides/modules/sales.md +1 -1
  44. package/dist/agentic/guides/modules/scheduler.md +1 -1
  45. package/dist/agentic/guides/modules/search.md +1 -1
  46. package/dist/agentic/guides/modules/security.md +1 -1
  47. package/dist/agentic/guides/modules/shipping_carriers.md +1 -1
  48. package/dist/agentic/guides/modules/sso.md +1 -1
  49. package/dist/agentic/guides/modules/staff.md +1 -1
  50. package/dist/agentic/guides/modules/storage_s3.md +1 -1
  51. package/dist/agentic/guides/modules/sync_akeneo.md +1 -1
  52. package/dist/agentic/guides/modules/sync_excel.md +1 -1
  53. package/dist/agentic/guides/modules/system_status_overlays.md +1 -1
  54. package/dist/agentic/guides/modules/translations.md +1 -1
  55. package/dist/agentic/guides/modules/webhooks.md +1 -1
  56. package/dist/agentic/guides/modules/workflows.md +1 -1
  57. package/dist/agentic/shared/AGENTS.md.template +3 -2
  58. package/dist/agentic/shared/ai/skills/om-prepare-test-env/SKILL.md +29 -3
  59. package/dist/lib/__integration__/TC-INT-008.spec.js +0 -7
  60. package/dist/lib/__integration__/TC-INT-008.spec.js.map +2 -2
  61. package/dist/lib/db/commands.js +2 -1
  62. package/dist/lib/db/commands.js.map +2 -2
  63. package/dist/lib/db/identifiers.js +7 -0
  64. package/dist/lib/db/identifiers.js.map +7 -0
  65. package/dist/lib/generators/module-facts.js +1 -13
  66. package/dist/lib/generators/module-facts.js.map +2 -2
  67. package/dist/mercato.js +2 -1
  68. package/dist/mercato.js.map +2 -2
  69. package/package.json +5 -5
  70. package/src/lib/__integration__/TC-INT-008.spec.ts +3 -10
  71. package/src/lib/db/__tests__/commands.test.ts +51 -0
  72. package/src/lib/db/commands.ts +2 -1
  73. package/src/lib/db/identifiers.ts +3 -0
  74. package/src/lib/generators/__tests__/example-public-route-safety.test.ts +16 -0
  75. package/src/lib/generators/module-facts.ts +2 -22
  76. package/src/mercato.ts +2 -1
  77. package/dist/agentic/guides/core.auth.md +0 -3
  78. package/dist/agentic/guides/core.catalog.md +0 -3
  79. package/dist/agentic/guides/core.currencies.md +0 -3
  80. package/dist/agentic/guides/core.customer_accounts.md +0 -3
  81. package/dist/agentic/guides/core.customers.md +0 -3
  82. package/dist/agentic/guides/core.data_sync.md +0 -3
  83. package/dist/agentic/guides/core.integrations.md +0 -3
  84. package/dist/agentic/guides/core.sales.md +0 -3
  85. package/dist/agentic/guides/core.workflows.md +0 -3
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/db/commands.ts"],
4
- "sourcesContent": ["import path from 'node:path'\nimport fs from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport ts from 'typescript'\nimport { MikroORM, MetadataStorage, type Logger } from '@mikro-orm/core'\nimport { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'\nimport { Migrator } from '@mikro-orm/migrations'\nimport { PostgreSqlDriver } from '@mikro-orm/postgresql'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\nimport type { PackageResolver, ModuleEntry } from '../resolver'\n\nconst QUIET_MODE = process.env.OM_CLI_QUIET === '1' || process.env.MERCATO_QUIET === '1'\nconst PROGRESS_EMOJI = ''\n\nfunction formatResult(modId: string, message: string, emoji = '\\u2022') {\n return `${emoji} ${modId}: ${message}`\n}\n\nfunction createProgressRenderer(total: number) {\n const width = 20\n const normalizedTotal = total > 0 ? total : 1\n return (current: number) => {\n const clamped = Math.min(Math.max(current, 0), normalizedTotal)\n const filled = Math.round((clamped / normalizedTotal) * width)\n const bar = `${'='.repeat(filled)}${'.'.repeat(Math.max(width - filled, 0))}`\n return `[${bar}] ${clamped}/${normalizedTotal}`\n }\n}\n\nfunction createMinimalLogger(): Logger {\n return {\n log: () => { },\n error: (_namespace, message) => console.error(message),\n warn: (_namespace, message) => {\n if (!QUIET_MODE) console.warn(message)\n },\n logQuery: () => { },\n setDebugMode: () => { },\n isEnabled: () => false,\n }\n}\n\nfunction getClientUrl(): string {\n const url = process.env.DATABASE_URL\n if (!url) throw new Error('DATABASE_URL is not set')\n return url\n}\n\nfunction sortModules(mods: ModuleEntry[]): ModuleEntry[] {\n // Sort modules alphabetically since they are now isomorphic\n return mods.slice().sort((a, b) => a.id.localeCompare(b.id))\n}\n\n/**\n * Custom dynamic import provider for MikroORM that properly handles Windows paths.\n * MikroORM's built-in handling has a bug where it converts file:// URLs back to\n * Windows paths when the extension isn't in require.extensions (which is always\n * true for .ts files in ESM mode).\n */\nasync function dynamicImportProvider(id: string): Promise<any> {\n // On Windows, convert absolute paths to file:// URLs\n // Check if it's a Windows absolute path (e.g., C:\\... or D:\\...)\n if (process.platform === 'win32' && /^[a-zA-Z]:[\\\\/]/.test(id)) {\n id = pathToFileURL(id).href\n }\n return import(id)\n}\n\n/**\n * Sanitizes a module ID for use in SQL identifiers (table names).\n * Replaces non-alphanumeric characters with underscores to prevent SQL injection.\n * @public Exported for testing\n */\nexport function sanitizeModuleId(modId: string): string {\n return modId.replace(/[^a-z0-9_]/gi, '_')\n}\n\n/**\n * Validates that a table name is safe for use in SQL queries.\n * @throws Error if the table name contains invalid characters.\n * @public Exported for testing\n */\nexport function validateTableName(tableName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {\n throw new Error(`Invalid table name: ${tableName}. Table names must start with a letter or underscore and contain only alphanumeric characters and underscores.`)\n }\n}\n\nexport function makeConstraintDropsIdempotent(sql: string): string {\n return sql.replace(/alter table\\s+(\"[^\"]+\"|\\S+)\\s+drop constraint\\s+(\"[^\"]+\"|\\S+);/gi, 'alter table $1 drop constraint if exists $2;')\n}\n\nexport function getMigrationSnapshotName(resolver: Pick<PackageResolver, 'getRootDir'>): string {\n void resolver\n return '.snapshot-open-mercato'\n}\n\nexport function shouldCreateInitialModuleMigration(migrationsPath: string, snapshotName: string): boolean {\n const snapshotPath = path.join(migrationsPath, `${snapshotName}.json`)\n if (fs.existsSync(snapshotPath)) return false\n if (!fs.existsSync(migrationsPath)) return true\n\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => /^Migration.*\\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'))\n\n return migrationFiles.length === 0\n}\n\nexport function resolveGeneratedMigrationPath(fileName: string, migrationsPath: string): string {\n return path.isAbsolute(fileName) ? fileName : path.join(migrationsPath, fileName)\n}\n\nlet tsxLoaderRegistered = false\nlet temporaryModuleCounter = 0\n\nasync function ensureTsxLoaderRegistered() {\n if (tsxLoaderRegistered) return\n try {\n const { register } = await import('tsx/esm/api')\n register()\n tsxLoaderRegistered = true\n } catch {\n // Continue without the loader. Relative TypeScript imports may fail in this case.\n }\n}\n\nasync function importWithTypeScriptFile(filePath: string): Promise<any> {\n await ensureTsxLoaderRegistered()\n const source = fs.readFileSync(filePath, 'utf8')\n const compiled = ts.transpileModule(source, {\n fileName: filePath,\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2022,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n esModuleInterop: true,\n resolveJsonModule: true,\n jsx: ts.JsxEmit.ReactJSX,\n experimentalDecorators: true,\n emitDecoratorMetadata: false,\n useDefineForClassFields: false,\n },\n }).outputText\n const tempPath = `${filePath}.mercato-db-generate-${process.pid}-${temporaryModuleCounter++}.mjs`\n fs.writeFileSync(tempPath, compiled, 'utf8')\n try {\n return await import(pathToFileURL(tempPath).href)\n } finally {\n try {\n fs.unlinkSync(tempPath)\n } catch {\n // Ignore cleanup failures for temporary compiled modules.\n }\n }\n}\n\nasync function loadModuleEntities(entry: ModuleEntry, resolver: PackageResolver): Promise<any[]> {\n const roots = resolver.getModulePaths(entry)\n const imps = resolver.getModuleImportBase(entry)\n const isAppModule = entry.from === '@app'\n const shouldImportFromSource = isAppModule || resolver.isMonorepo()\n const bases = [\n path.join(roots.appBase, 'data'),\n path.join(roots.pkgBase, 'data'),\n path.join(roots.appBase, 'db'),\n path.join(roots.pkgBase, 'db'),\n ]\n const candidates = ['entities.ts', 'schema.ts']\n\n for (const base of bases) {\n for (const f of candidates) {\n const p = path.join(base, f)\n if (fs.existsSync(p)) {\n const sub = path.basename(base)\n const fromApp = base.startsWith(roots.appBase)\n const importPath = fromApp || shouldImportFromSource\n ? pathToFileURL(p).href\n : `${imps.pkgBase}/${sub}/${f.replace(/\\.ts$/, '')}`\n try {\n const mod = fromApp || shouldImportFromSource\n ? await importWithTypeScriptFile(p)\n : await import(importPath)\n const entities = Object.values(mod).filter((v) => typeof v === 'function')\n if (entities.length) return entities as any[]\n } catch (err) {\n // For @app modules we try a TS loader fallback; otherwise propagate errors\n if (isAppModule) {\n if (process.env.MERCATO_CLI_DEBUG_IMPORTS === '1') {\n console.warn(`[db] failed to load app module entities from ${p}: ${(err as Error)?.message || String(err)}`)\n }\n continue\n }\n throw err\n }\n }\n }\n }\n return []\n}\n\nfunction getMigrationsPath(entry: ModuleEntry, resolver: PackageResolver): string {\n const roots = resolver.getModulePaths(entry)\n\n if (entry.from === '@app') {\n // @app modules: use src/ (user's TypeScript source)\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.appBase, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Package modules: in standalone mode, use dist/ (compiled JS) since Node.js\n // can't run TypeScript from node_modules. In monorepo, use src/ (TypeScript).\n if (!resolver.isMonorepo()) {\n // Replace src/modules with dist/modules for standalone apps\n // Use regex to handle both forward and backslashes\n const distPath = roots.pkgBase.replace(/[/\\\\]src[/\\\\]modules[/\\\\]/, '/dist/modules/')\n return path.join(distPath, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.pkgBase, 'migrations').replace(/\\\\/g, '/')\n}\n\nexport interface DbOptions {\n quiet?: boolean\n}\n\nexport interface GreenfieldOptions extends DbOptions {\n yes: boolean\n}\n\nexport async function dbGenerate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n\n const sslConfig = getSslConfig()\n const usedFileNames = new Set<string>()\n\n for (const entry of ordered) {\n // Clear the global @Entity() decorator registry before loading this module's\n // entities. MikroORM's migrator reads MetadataStorage at createMigration()\n // time, so without this clear, every module's migration would include every\n // previously-loaded module's tables (see issue #1911).\n MetadataStorage.clear()\n\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n if (!entities.length) {\n if (entry.from === '@app') {\n results.push(formatResult(modId, 'no entities discovered', ''))\n }\n continue\n }\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n const snapshotName = getMigrationSnapshotName(resolver)\n const createInitialMigration = shouldCreateInitialModuleMigration(migrationsPath, snapshotName)\n\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: getClientUrl(),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities,\n metadataProvider: ReflectMetadataProvider,\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshotName,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n try {\n const diff = await orm.migrator.create(undefined, false, createInitialMigration)\n if (diff && diff.fileName) {\n try {\n const orig = resolveGeneratedMigrationPath(diff.fileName, migrationsPath)\n const base = path.basename(orig)\n const dir = path.dirname(orig)\n const ext = path.extname(base)\n const stem = base.replace(ext, '')\n const suffix = `_${modId}`\n let candidate = stem.endsWith(suffix) ? base : `${stem}${suffix}${ext}`\n let dedupe = 1\n\n while (usedFileNames.has(path.join(dir, candidate))) {\n candidate = `${stem}${suffix}_${dedupe++}${ext}`\n }\n\n const newPath = path.join(dir, candidate)\n let content = fs.readFileSync(orig, 'utf8')\n content = makeConstraintDropsIdempotent(content)\n content = content.replace(\n /export class (Migration\\d+)/,\n `export class $1_${modId.replace(/[^a-zA-Z0-9]/g, '_')}`\n )\n fs.writeFileSync(newPath, content, 'utf8')\n if (newPath !== orig) fs.unlinkSync(orig)\n usedFileNames.add(newPath)\n results.push(formatResult(modId, `generated ${path.basename(newPath)}`, ''))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n results.push(formatResult(modId, `generated ${path.basename(diff.fileName)} (rename failed: ${message})`, ''))\n }\n } else {\n results.push(formatResult(modId, 'no changes', ''))\n }\n } finally {\n await orm.close(true)\n }\n }\n\n console.log(results.join('\\n'))\n}\n\nexport async function dbMigrate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n // Skip if no entities AND no migrations directory exists\n // (allows @app modules to run migrations even if entities can't be dynamically imported)\n if (!entities.length && !fs.existsSync(migrationsPath)) continue\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n\n // dbMigrate only runs existing migration files \u2014 entities are intentionally\n // omitted so MikroORM does not compare them against the snapshot and\n // auto-generate a phantom diff migration (that would duplicate tables\n // already created by committed migrations).\n const sslConfig = getSslConfig()\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: getClientUrl(),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities: [],\n metadataProvider: ReflectMetadataProvider,\n discovery: { warnWhenNoEntities: false },\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshot: false,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n const migrator = orm.migrator as Migrator\n const pending = await migrator.getPending()\n if (!pending.length) {\n results.push(formatResult(modId, 'no pending migrations', ''))\n } else {\n const renderProgress = createProgressRenderer(pending.length)\n let applied = 0\n if (!QUIET_MODE) {\n process.stdout.write(` ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n for (const migration of pending) {\n const migrationName =\n typeof migration === 'string'\n ? migration\n : (migration as any).name ?? (migration as any).fileName\n await migrator.up(migrationName ? { migrations: [migrationName] } : undefined)\n applied += 1\n if (!QUIET_MODE) {\n process.stdout.write(`\\r ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n }\n if (!QUIET_MODE) process.stdout.write('\\n')\n results.push(\n formatResult(modId, `${pending.length} migration${pending.length === 1 ? '' : 's'} applied`, '')\n )\n }\n\n await orm.close(true)\n }\n\n console.log(results.join('\\n'))\n}\n\nexport async function dbGreenfield(resolver: PackageResolver, options: GreenfieldOptions): Promise<void> {\n if (!options.yes) {\n console.error('This command will DELETE all data. Use --yes to confirm.')\n process.exit(1)\n }\n\n console.log('Cleaning up migrations and snapshots for greenfield setup...')\n\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const outputDir = resolver.getOutputDir()\n\n for (const entry of ordered) {\n const modId = entry.id\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n if (fs.existsSync(migrationsPath)) {\n // Remove all migration files\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.ts') && file.startsWith('Migration'))\n\n for (const file of migrationFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n // Remove snapshot files\n const snapshotFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.json') && file.includes('snapshot'))\n\n for (const file of snapshotFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n if (migrationFiles.length > 0 || snapshotFiles.length > 0) {\n results.push(\n formatResult(modId, `cleaned ${migrationFiles.length} migrations, ${snapshotFiles.length} snapshots`, '')\n )\n } else {\n results.push(formatResult(modId, 'already clean', ''))\n }\n } else {\n results.push(formatResult(modId, 'no migrations directory', ''))\n }\n\n // Clean up checksum files using glob pattern\n if (fs.existsSync(outputDir)) {\n const files = fs.readdirSync(outputDir)\n const checksumFiles = files.filter((file) => file.endsWith('.checksum'))\n\n for (const file of checksumFiles) {\n fs.unlinkSync(path.join(outputDir, file))\n }\n\n if (checksumFiles.length > 0) {\n results.push(formatResult(modId, `cleaned ${checksumFiles.length} checksum files`, ''))\n }\n }\n }\n\n console.log(results.join('\\n'))\n\n // Drop per-module MikroORM migration tables to ensure clean slate\n console.log('Dropping per-module migration tables...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n await client.query('BEGIN')\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n await client.query(`DROP TABLE IF EXISTS \"${tableName}\"`)\n console.log(` ${modId}: dropped table ${tableName}`)\n }\n await client.query('COMMIT')\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop migration tables:', (e as any)?.message || e)\n throw e\n }\n\n // Drop all existing user tables to ensure fresh CREATE-only migrations\n console.log('Dropping ALL public tables for true greenfield...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n const res = await client.query(`SELECT tablename FROM pg_tables WHERE schemaname = current_schema()`)\n const tables: string[] = (res.rows || []).map((r: any) => String(r.tablename))\n if (tables.length) {\n await client.query('BEGIN')\n try {\n await client.query(\"SET session_replication_role = 'replica'\")\n for (const t of tables) {\n await client.query(`DROP TABLE IF EXISTS \"${t}\" CASCADE`)\n }\n await client.query(\"SET session_replication_role = 'origin'\")\n await client.query('COMMIT')\n console.log(` Dropped ${tables.length} tables.`)\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n }\n } else {\n console.log(' No tables found to drop.')\n }\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop public tables:', (e as any)?.message || e)\n throw e\n }\n\n // Generate fresh migrations for all modules\n console.log('Generating fresh migrations for all modules...')\n await dbGenerate(resolver)\n\n // Apply migrations\n console.log('Applying migrations...')\n await dbMigrate(resolver)\n\n console.log('Greenfield reset complete! Fresh migrations generated and applied.')\n}\n"],
5
- "mappings": "AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;AACf,SAAS,UAAU,uBAAoC;AACvD,SAAS,+BAA+B;AAExC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAG7B,MAAM,aAAa,QAAQ,IAAI,iBAAiB,OAAO,QAAQ,IAAI,kBAAkB;AACrF,MAAM,iBAAiB;AAEvB,SAAS,aAAa,OAAe,SAAiB,QAAQ,UAAU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,IAAI,gDAAgD;AAC5D,QAAM,WAAW,QAAQ;AAGzB,UAAQ,IAAI,wBAAwB;AACpC,QAAM,UAAU,QAAQ;AAExB,UAAQ,IAAI,oEAAoE;AAClF;",
4
+ "sourcesContent": ["import path from 'node:path'\nimport fs from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport ts from 'typescript'\nimport { MikroORM, MetadataStorage, type Logger } from '@mikro-orm/core'\nimport { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'\nimport { Migrator } from '@mikro-orm/migrations'\nimport { PostgreSqlDriver } from '@mikro-orm/postgresql'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\nimport type { PackageResolver, ModuleEntry } from '../resolver'\nimport { quotePostgresIdentifier } from './identifiers'\n\nconst QUIET_MODE = process.env.OM_CLI_QUIET === '1' || process.env.MERCATO_QUIET === '1'\nconst PROGRESS_EMOJI = ''\n\nfunction formatResult(modId: string, message: string, emoji = '\\u2022') {\n return `${emoji} ${modId}: ${message}`\n}\n\nfunction createProgressRenderer(total: number) {\n const width = 20\n const normalizedTotal = total > 0 ? total : 1\n return (current: number) => {\n const clamped = Math.min(Math.max(current, 0), normalizedTotal)\n const filled = Math.round((clamped / normalizedTotal) * width)\n const bar = `${'='.repeat(filled)}${'.'.repeat(Math.max(width - filled, 0))}`\n return `[${bar}] ${clamped}/${normalizedTotal}`\n }\n}\n\nfunction createMinimalLogger(): Logger {\n return {\n log: () => { },\n error: (_namespace, message) => console.error(message),\n warn: (_namespace, message) => {\n if (!QUIET_MODE) console.warn(message)\n },\n logQuery: () => { },\n setDebugMode: () => { },\n isEnabled: () => false,\n }\n}\n\nfunction getClientUrl(): string {\n const url = process.env.DATABASE_URL\n if (!url) throw new Error('DATABASE_URL is not set')\n return url\n}\n\nfunction sortModules(mods: ModuleEntry[]): ModuleEntry[] {\n // Sort modules alphabetically since they are now isomorphic\n return mods.slice().sort((a, b) => a.id.localeCompare(b.id))\n}\n\n/**\n * Custom dynamic import provider for MikroORM that properly handles Windows paths.\n * MikroORM's built-in handling has a bug where it converts file:// URLs back to\n * Windows paths when the extension isn't in require.extensions (which is always\n * true for .ts files in ESM mode).\n */\nasync function dynamicImportProvider(id: string): Promise<any> {\n // On Windows, convert absolute paths to file:// URLs\n // Check if it's a Windows absolute path (e.g., C:\\... or D:\\...)\n if (process.platform === 'win32' && /^[a-zA-Z]:[\\\\/]/.test(id)) {\n id = pathToFileURL(id).href\n }\n return import(id)\n}\n\n/**\n * Sanitizes a module ID for use in SQL identifiers (table names).\n * Replaces non-alphanumeric characters with underscores to prevent SQL injection.\n * @public Exported for testing\n */\nexport function sanitizeModuleId(modId: string): string {\n return modId.replace(/[^a-z0-9_]/gi, '_')\n}\n\n/**\n * Validates that a table name is safe for use in SQL queries.\n * @throws Error if the table name contains invalid characters.\n * @public Exported for testing\n */\nexport function validateTableName(tableName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {\n throw new Error(`Invalid table name: ${tableName}. Table names must start with a letter or underscore and contain only alphanumeric characters and underscores.`)\n }\n}\n\nexport function makeConstraintDropsIdempotent(sql: string): string {\n return sql.replace(/alter table\\s+(\"[^\"]+\"|\\S+)\\s+drop constraint\\s+(\"[^\"]+\"|\\S+);/gi, 'alter table $1 drop constraint if exists $2;')\n}\n\nexport function getMigrationSnapshotName(resolver: Pick<PackageResolver, 'getRootDir'>): string {\n void resolver\n return '.snapshot-open-mercato'\n}\n\nexport function shouldCreateInitialModuleMigration(migrationsPath: string, snapshotName: string): boolean {\n const snapshotPath = path.join(migrationsPath, `${snapshotName}.json`)\n if (fs.existsSync(snapshotPath)) return false\n if (!fs.existsSync(migrationsPath)) return true\n\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => /^Migration.*\\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'))\n\n return migrationFiles.length === 0\n}\n\nexport function resolveGeneratedMigrationPath(fileName: string, migrationsPath: string): string {\n return path.isAbsolute(fileName) ? fileName : path.join(migrationsPath, fileName)\n}\n\nlet tsxLoaderRegistered = false\nlet temporaryModuleCounter = 0\n\nasync function ensureTsxLoaderRegistered() {\n if (tsxLoaderRegistered) return\n try {\n const { register } = await import('tsx/esm/api')\n register()\n tsxLoaderRegistered = true\n } catch {\n // Continue without the loader. Relative TypeScript imports may fail in this case.\n }\n}\n\nasync function importWithTypeScriptFile(filePath: string): Promise<any> {\n await ensureTsxLoaderRegistered()\n const source = fs.readFileSync(filePath, 'utf8')\n const compiled = ts.transpileModule(source, {\n fileName: filePath,\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2022,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n esModuleInterop: true,\n resolveJsonModule: true,\n jsx: ts.JsxEmit.ReactJSX,\n experimentalDecorators: true,\n emitDecoratorMetadata: false,\n useDefineForClassFields: false,\n },\n }).outputText\n const tempPath = `${filePath}.mercato-db-generate-${process.pid}-${temporaryModuleCounter++}.mjs`\n fs.writeFileSync(tempPath, compiled, 'utf8')\n try {\n return await import(pathToFileURL(tempPath).href)\n } finally {\n try {\n fs.unlinkSync(tempPath)\n } catch {\n // Ignore cleanup failures for temporary compiled modules.\n }\n }\n}\n\nasync function loadModuleEntities(entry: ModuleEntry, resolver: PackageResolver): Promise<any[]> {\n const roots = resolver.getModulePaths(entry)\n const imps = resolver.getModuleImportBase(entry)\n const isAppModule = entry.from === '@app'\n const shouldImportFromSource = isAppModule || resolver.isMonorepo()\n const bases = [\n path.join(roots.appBase, 'data'),\n path.join(roots.pkgBase, 'data'),\n path.join(roots.appBase, 'db'),\n path.join(roots.pkgBase, 'db'),\n ]\n const candidates = ['entities.ts', 'schema.ts']\n\n for (const base of bases) {\n for (const f of candidates) {\n const p = path.join(base, f)\n if (fs.existsSync(p)) {\n const sub = path.basename(base)\n const fromApp = base.startsWith(roots.appBase)\n const importPath = fromApp || shouldImportFromSource\n ? pathToFileURL(p).href\n : `${imps.pkgBase}/${sub}/${f.replace(/\\.ts$/, '')}`\n try {\n const mod = fromApp || shouldImportFromSource\n ? await importWithTypeScriptFile(p)\n : await import(importPath)\n const entities = Object.values(mod).filter((v) => typeof v === 'function')\n if (entities.length) return entities as any[]\n } catch (err) {\n // For @app modules we try a TS loader fallback; otherwise propagate errors\n if (isAppModule) {\n if (process.env.MERCATO_CLI_DEBUG_IMPORTS === '1') {\n console.warn(`[db] failed to load app module entities from ${p}: ${(err as Error)?.message || String(err)}`)\n }\n continue\n }\n throw err\n }\n }\n }\n }\n return []\n}\n\nfunction getMigrationsPath(entry: ModuleEntry, resolver: PackageResolver): string {\n const roots = resolver.getModulePaths(entry)\n\n if (entry.from === '@app') {\n // @app modules: use src/ (user's TypeScript source)\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.appBase, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Package modules: in standalone mode, use dist/ (compiled JS) since Node.js\n // can't run TypeScript from node_modules. In monorepo, use src/ (TypeScript).\n if (!resolver.isMonorepo()) {\n // Replace src/modules with dist/modules for standalone apps\n // Use regex to handle both forward and backslashes\n const distPath = roots.pkgBase.replace(/[/\\\\]src[/\\\\]modules[/\\\\]/, '/dist/modules/')\n return path.join(distPath, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.pkgBase, 'migrations').replace(/\\\\/g, '/')\n}\n\nexport interface DbOptions {\n quiet?: boolean\n}\n\nexport interface GreenfieldOptions extends DbOptions {\n yes: boolean\n}\n\nexport async function dbGenerate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n\n const sslConfig = getSslConfig()\n const usedFileNames = new Set<string>()\n\n for (const entry of ordered) {\n // Clear the global @Entity() decorator registry before loading this module's\n // entities. MikroORM's migrator reads MetadataStorage at createMigration()\n // time, so without this clear, every module's migration would include every\n // previously-loaded module's tables (see issue #1911).\n MetadataStorage.clear()\n\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n if (!entities.length) {\n if (entry.from === '@app') {\n results.push(formatResult(modId, 'no entities discovered', ''))\n }\n continue\n }\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n const snapshotName = getMigrationSnapshotName(resolver)\n const createInitialMigration = shouldCreateInitialModuleMigration(migrationsPath, snapshotName)\n\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: getClientUrl(),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities,\n metadataProvider: ReflectMetadataProvider,\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshotName,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n try {\n const diff = await orm.migrator.create(undefined, false, createInitialMigration)\n if (diff && diff.fileName) {\n try {\n const orig = resolveGeneratedMigrationPath(diff.fileName, migrationsPath)\n const base = path.basename(orig)\n const dir = path.dirname(orig)\n const ext = path.extname(base)\n const stem = base.replace(ext, '')\n const suffix = `_${modId}`\n let candidate = stem.endsWith(suffix) ? base : `${stem}${suffix}${ext}`\n let dedupe = 1\n\n while (usedFileNames.has(path.join(dir, candidate))) {\n candidate = `${stem}${suffix}_${dedupe++}${ext}`\n }\n\n const newPath = path.join(dir, candidate)\n let content = fs.readFileSync(orig, 'utf8')\n content = makeConstraintDropsIdempotent(content)\n content = content.replace(\n /export class (Migration\\d+)/,\n `export class $1_${modId.replace(/[^a-zA-Z0-9]/g, '_')}`\n )\n fs.writeFileSync(newPath, content, 'utf8')\n if (newPath !== orig) fs.unlinkSync(orig)\n usedFileNames.add(newPath)\n results.push(formatResult(modId, `generated ${path.basename(newPath)}`, ''))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n results.push(formatResult(modId, `generated ${path.basename(diff.fileName)} (rename failed: ${message})`, ''))\n }\n } else {\n results.push(formatResult(modId, 'no changes', ''))\n }\n } finally {\n await orm.close(true)\n }\n }\n\n console.log(results.join('\\n'))\n}\n\nexport async function dbMigrate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n // Skip if no entities AND no migrations directory exists\n // (allows @app modules to run migrations even if entities can't be dynamically imported)\n if (!entities.length && !fs.existsSync(migrationsPath)) continue\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n\n // dbMigrate only runs existing migration files \u2014 entities are intentionally\n // omitted so MikroORM does not compare them against the snapshot and\n // auto-generate a phantom diff migration (that would duplicate tables\n // already created by committed migrations).\n const sslConfig = getSslConfig()\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: getClientUrl(),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities: [],\n metadataProvider: ReflectMetadataProvider,\n discovery: { warnWhenNoEntities: false },\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshot: false,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n const migrator = orm.migrator as Migrator\n const pending = await migrator.getPending()\n if (!pending.length) {\n results.push(formatResult(modId, 'no pending migrations', ''))\n } else {\n const renderProgress = createProgressRenderer(pending.length)\n let applied = 0\n if (!QUIET_MODE) {\n process.stdout.write(` ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n for (const migration of pending) {\n const migrationName =\n typeof migration === 'string'\n ? migration\n : (migration as any).name ?? (migration as any).fileName\n await migrator.up(migrationName ? { migrations: [migrationName] } : undefined)\n applied += 1\n if (!QUIET_MODE) {\n process.stdout.write(`\\r ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n }\n if (!QUIET_MODE) process.stdout.write('\\n')\n results.push(\n formatResult(modId, `${pending.length} migration${pending.length === 1 ? '' : 's'} applied`, '')\n )\n }\n\n await orm.close(true)\n }\n\n console.log(results.join('\\n'))\n}\n\nexport async function dbGreenfield(resolver: PackageResolver, options: GreenfieldOptions): Promise<void> {\n if (!options.yes) {\n console.error('This command will DELETE all data. Use --yes to confirm.')\n process.exit(1)\n }\n\n console.log('Cleaning up migrations and snapshots for greenfield setup...')\n\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const outputDir = resolver.getOutputDir()\n\n for (const entry of ordered) {\n const modId = entry.id\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n if (fs.existsSync(migrationsPath)) {\n // Remove all migration files\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.ts') && file.startsWith('Migration'))\n\n for (const file of migrationFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n // Remove snapshot files\n const snapshotFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.json') && file.includes('snapshot'))\n\n for (const file of snapshotFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n if (migrationFiles.length > 0 || snapshotFiles.length > 0) {\n results.push(\n formatResult(modId, `cleaned ${migrationFiles.length} migrations, ${snapshotFiles.length} snapshots`, '')\n )\n } else {\n results.push(formatResult(modId, 'already clean', ''))\n }\n } else {\n results.push(formatResult(modId, 'no migrations directory', ''))\n }\n\n // Clean up checksum files using glob pattern\n if (fs.existsSync(outputDir)) {\n const files = fs.readdirSync(outputDir)\n const checksumFiles = files.filter((file) => file.endsWith('.checksum'))\n\n for (const file of checksumFiles) {\n fs.unlinkSync(path.join(outputDir, file))\n }\n\n if (checksumFiles.length > 0) {\n results.push(formatResult(modId, `cleaned ${checksumFiles.length} checksum files`, ''))\n }\n }\n }\n\n console.log(results.join('\\n'))\n\n // Drop per-module MikroORM migration tables to ensure clean slate\n console.log('Dropping per-module migration tables...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n await client.query('BEGIN')\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n await client.query(`DROP TABLE IF EXISTS \"${tableName}\"`)\n console.log(` ${modId}: dropped table ${tableName}`)\n }\n await client.query('COMMIT')\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop migration tables:', (e as any)?.message || e)\n throw e\n }\n\n // Drop all existing user tables to ensure fresh CREATE-only migrations\n console.log('Dropping ALL public tables for true greenfield...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n const res = await client.query(`SELECT tablename FROM pg_tables WHERE schemaname = current_schema()`)\n const tables: string[] = (res.rows || []).map((r: any) => String(r.tablename))\n if (tables.length) {\n await client.query('BEGIN')\n try {\n await client.query(\"SET session_replication_role = 'replica'\")\n for (const t of tables) {\n await client.query(`DROP TABLE IF EXISTS ${quotePostgresIdentifier(t)} CASCADE`)\n }\n await client.query(\"SET session_replication_role = 'origin'\")\n await client.query('COMMIT')\n console.log(` Dropped ${tables.length} tables.`)\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n }\n } else {\n console.log(' No tables found to drop.')\n }\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop public tables:', (e as any)?.message || e)\n throw e\n }\n\n // Generate fresh migrations for all modules\n console.log('Generating fresh migrations for all modules...')\n await dbGenerate(resolver)\n\n // Apply migrations\n console.log('Applying migrations...')\n await dbMigrate(resolver)\n\n console.log('Greenfield reset complete! Fresh migrations generated and applied.')\n}\n"],
5
+ "mappings": "AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;AACf,SAAS,UAAU,uBAAoC;AACvD,SAAS,+BAA+B;AAExC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAE7B,SAAS,+BAA+B;AAExC,MAAM,aAAa,QAAQ,IAAI,iBAAiB,OAAO,QAAQ,IAAI,kBAAkB;AACrF,MAAM,iBAAiB;AAEvB,SAAS,aAAa,OAAe,SAAiB,QAAQ,UAAU;AACtE,SAAO,GAAG,KAAK,IAAI,KAAK,KAAK,OAAO;AACtC;AAEA,SAAS,uBAAuB,OAAe;AAC7C,QAAM,QAAQ;AACd,QAAM,kBAAkB,QAAQ,IAAI,QAAQ;AAC5C,SAAO,CAAC,YAAoB;AAC1B,UAAM,UAAU,KAAK,IAAI,KAAK,IAAI,SAAS,CAAC,GAAG,eAAe;AAC9D,UAAM,SAAS,KAAK,MAAO,UAAU,kBAAmB,KAAK;AAC7D,UAAM,MAAM,GAAG,IAAI,OAAO,MAAM,CAAC,GAAG,IAAI,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC,CAAC,CAAC;AAC3E,WAAO,IAAI,GAAG,KAAK,OAAO,IAAI,eAAe;AAAA,EAC/C;AACF;AAEA,SAAS,sBAA8B;AACrC,SAAO;AAAA,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AAqE;AACpG,YAAM,UAAoB,IAAI,QAAQ,CAAC,GAAG,IAAI,CAAC,MAAW,OAAO,EAAE,SAAS,CAAC;AAC7E,UAAI,OAAO,QAAQ;AACjB,cAAM,OAAO,MAAM,OAAO;AAC1B,YAAI;AACF,gBAAM,OAAO,MAAM,0CAA0C;AAC7D,qBAAW,KAAK,QAAQ;AACtB,kBAAM,OAAO,MAAM,wBAAwB,wBAAwB,CAAC,CAAC,UAAU;AAAA,UACjF;AACA,gBAAM,OAAO,MAAM,yCAAyC;AAC5D,gBAAM,OAAO,MAAM,QAAQ;AAC3B,kBAAQ,IAAI,cAAc,OAAO,MAAM,UAAU;AAAA,QACnD,SAAS,GAAG;AACV,gBAAM,OAAO,MAAM,UAAU;AAC7B,gBAAM;AAAA,QACR;AAAA,MACF,OAAO;AACL,gBAAQ,IAAI,6BAA6B;AAAA,MAC3C;AAAA,IACF,UAAE;AACA,UAAI;AACF,cAAM,OAAO,IAAI;AAAA,MACnB,QAAQ;AAAA,MAAE;AAAA,IACZ;AAAA,EACF,SAAS,GAAG;AACV,YAAQ,MAAM,iCAAkC,GAAW,WAAW,CAAC;AACvE,UAAM;AAAA,EACR;AAGA,UAAQ,IAAI,gDAAgD;AAC5D,QAAM,WAAW,QAAQ;AAGzB,UAAQ,IAAI,wBAAwB;AACpC,QAAM,UAAU,QAAQ;AAExB,UAAQ,IAAI,oEAAoE;AAClF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,7 @@
1
+ function quotePostgresIdentifier(identifier) {
2
+ return `"${identifier.replace(/"/g, '""')}"`;
3
+ }
4
+ export {
5
+ quotePostgresIdentifier
6
+ };
7
+ //# sourceMappingURL=identifiers.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/db/identifiers.ts"],
4
+ "sourcesContent": ["export function quotePostgresIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`\n}\n"],
5
+ "mappings": "AAAO,SAAS,wBAAwB,YAA4B;AAClE,SAAO,IAAI,WAAW,QAAQ,MAAM,IAAI,CAAC;AAC3C;",
6
+ "names": []
7
+ }
@@ -2,17 +2,6 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import ts from "typescript";
4
4
  import { toSnake } from "../utils.js";
5
- const MODULE_FACTS_ALLOWLIST = [
6
- "auth",
7
- "catalog",
8
- "currencies",
9
- "customer_accounts",
10
- "customers",
11
- "data_sync",
12
- "integrations",
13
- "sales",
14
- "workflows"
15
- ];
16
5
  function readSourceFile(filePath) {
17
6
  if (!fs.existsSync(filePath)) return null;
18
7
  const source = fs.readFileSync(filePath, "utf8");
@@ -707,7 +696,7 @@ function renderModuleFactsJson(factsByModule) {
707
696
  `;
708
697
  }
709
698
  function extractAllModuleFacts(options) {
710
- const sources = options.sources ? [...options.sources] : options.coreSrcRoot ? (options.moduleIds ?? MODULE_FACTS_ALLOWLIST).map((moduleId) => ({
699
+ const sources = options.sources ? [...options.sources] : options.coreSrcRoot ? (options.moduleIds ?? []).map((moduleId) => ({
711
700
  moduleId,
712
701
  moduleRoot: path.join(options.coreSrcRoot, moduleId)
713
702
  })) : [];
@@ -729,7 +718,6 @@ function extractAllModuleFacts(options) {
729
718
  return { factsByModule, markdownByModule, warnings };
730
719
  }
731
720
  export {
732
- MODULE_FACTS_ALLOWLIST,
733
721
  buildModuleFactsJsonObject,
734
722
  extractAllModuleFacts,
735
723
  extractModuleFacts,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/generators/module-facts.ts"],
4
- "sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport ts from 'typescript'\nimport { toSnake } from '../utils'\n\nexport interface ModuleEntityFact {\n id: string\n class: string\n table: string\n editable: boolean\n customFields: boolean\n}\n\nexport interface ApiRouteAuthRule {\n requireAuth?: boolean\n requireFeatures?: string[]\n requireRoles?: string[]\n}\n\nexport interface ModuleApiRouteFact {\n path: string\n methods: string[]\n auth: Record<string, ApiRouteAuthRule>\n}\n\nexport interface ModuleEventFact {\n id: string\n label?: string\n category: string | null\n entity: string | null\n}\n\nexport interface ModuleHostTokens {\n entityIds: string[]\n tableIds: string[]\n}\n\nexport interface ModuleFacts {\n module: string\n title: string | null\n description: string | null\n coreVersion: string | null\n entities: ModuleEntityFact[]\n events: ModuleEventFact[]\n aclFeatures: string[]\n apiRoutes: ModuleApiRouteFact[]\n diTokens: string[]\n searchEntities: string[]\n hostTokens: ModuleHostTokens\n notifications: string[]\n cli: string[]\n warnings: string[]\n}\n\nexport interface ExtractModuleFactsOptions {\n moduleId: string\n /**\n * Parent modules directory joined with `moduleId` to locate the module source.\n * Legacy input; prefer the explicit per-module `moduleRoot` for modules that do\n * not live under a single shared root (auto-discovery). One of `moduleRoot` /\n * `coreSrcRoot` must be provided.\n */\n coreSrcRoot?: string\n /** Explicit module source directory. When set it overrides `coreSrcRoot + moduleId`. */\n moduleRoot?: string\n coreVersion?: string | null\n registryPath?: string | null\n registrySource?: string | null\n}\n\n/** A discovered module and the source directory its facts are extracted from. */\nexport interface ModuleFactSource {\n moduleId: string\n moduleRoot: string\n from?: string\n}\n\n/**\n * @deprecated Superseded by auto-discovery (`discoverPackageModuleSources` in\n * `module-facts-discovery.ts`). Retained as a stable export for one minor; no\n * longer gates which modules receive fact-sheets.\n */\nexport const MODULE_FACTS_ALLOWLIST = [\n 'auth',\n 'catalog',\n 'currencies',\n 'customer_accounts',\n 'customers',\n 'data_sync',\n 'integrations',\n 'sales',\n 'workflows',\n] as const\n\n/** @deprecated See {@link MODULE_FACTS_ALLOWLIST}. */\nexport type ModuleFactsModuleId = (typeof MODULE_FACTS_ALLOWLIST)[number]\n\nfunction readSourceFile(filePath: string): ts.SourceFile | null {\n if (!fs.existsSync(filePath)) return null\n const source = fs.readFileSync(filePath, 'utf8')\n const scriptKind = filePath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS\n return ts.createSourceFile(filePath, source, ts.ScriptTarget.ES2020, true, scriptKind)\n}\n\nfunction resolveConventionFile(baseDir: string, basename: string): string | null {\n for (const extension of ['.ts', '.tsx']) {\n const candidate = path.join(baseDir, `${basename}${extension}`)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nfunction readStringPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): string | undefined {\n for (const property of objectLiteral.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n const name = ts.isIdentifier(property.name)\n ? property.name.text\n : ts.isStringLiteralLike(property.name)\n ? property.name.text\n : undefined\n if (name !== propertyName) continue\n if (ts.isStringLiteralLike(property.initializer)) return property.initializer.text\n return undefined\n }\n return undefined\n}\n\nfunction getClassDecoratorCall(node: ts.ClassDeclaration, decoratorName: string): ts.CallExpression | undefined {\n const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) ?? [] : []\n for (const decorator of decorators) {\n const expression = decorator.expression\n if (!ts.isCallExpression(expression)) continue\n if (ts.isIdentifier(expression.expression) && expression.expression.text === decoratorName) {\n return expression\n }\n }\n return undefined\n}\n\nfunction readDecoratorTableName(decoratorCall: ts.CallExpression): string | undefined {\n const firstArgument = decoratorCall.arguments[0]\n if (!firstArgument || !ts.isObjectLiteralExpression(firstArgument)) return undefined\n return readStringPropertyInitializer(firstArgument, 'tableName')\n}\n\nfunction getPropertyDecoratorName(member: ts.PropertyDeclaration): string | undefined {\n const decorators = ts.canHaveDecorators(member) ? ts.getDecorators(member) ?? [] : []\n for (const decorator of decorators) {\n const expression = decorator.expression\n if (!ts.isCallExpression(expression)) continue\n const firstArgument = expression.arguments[0]\n if (!firstArgument || !ts.isObjectLiteralExpression(firstArgument)) continue\n const columnName = readStringPropertyInitializer(firstArgument, 'name')\n if (columnName) return columnName\n }\n return undefined\n}\n\nfunction classHasUpdatedAtColumn(node: ts.ClassDeclaration): boolean {\n for (const member of node.members) {\n if (!ts.isPropertyDeclaration(member) || !member.name) continue\n const propertyName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteralLike(member.name)\n ? member.name.text\n : undefined\n if (propertyName === 'updatedAt') return true\n if (getPropertyDecoratorName(member) === 'updated_at') return true\n }\n return false\n}\n\nfunction collectCustomFieldEntityIds(ceFilePath: string | null): Set<string> {\n const result = new Set<string>()\n if (!ceFilePath) return result\n const sourceFile = readSourceFile(ceFilePath)\n if (!sourceFile) return result\n\n const visit = (node: ts.Node): void => {\n if (ts.isObjectLiteralExpression(node)) {\n const id = readStringPropertyInitializer(node, 'id')\n if (id && id.includes(':')) result.add(id)\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return result\n}\n\nfunction extractEntities(\n moduleId: string,\n entitiesFilePath: string | null,\n customFieldEntityIds: Set<string>,\n): ModuleEntityFact[] {\n const sourceFile = entitiesFilePath ? readSourceFile(entitiesFilePath) : null\n if (!sourceFile) return []\n\n const facts: ModuleEntityFact[] = []\n sourceFile.forEachChild((node) => {\n if (!ts.isClassDeclaration(node) || !node.name) return\n const isExported = node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n if (!isExported) return\n const entityDecorator = getClassDecoratorCall(node, 'Entity')\n if (!entityDecorator) return\n\n const className = node.name.text\n const table = readDecoratorTableName(entityDecorator)\n if (!table) return\n\n const entityId = `${moduleId}:${toSnake(className)}`\n facts.push({\n id: entityId,\n class: className,\n table,\n editable: classHasUpdatedAtColumn(node),\n customFields: customFieldEntityIds.has(entityId),\n })\n })\n\n return facts\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression\n while (ts.isAsExpression(current) || ts.isParenthesizedExpression(current) || ts.isTypeAssertionExpression(current)) {\n current = current.expression\n }\n return current\n}\n\nfunction unwrapArrayLiteral(expression: ts.Expression): ts.ArrayLiteralExpression | null {\n const current = unwrapExpression(expression)\n return ts.isArrayLiteralExpression(current) ? current : null\n}\n\nfunction getPropertyName(property: ts.ObjectLiteralElementLike): string | undefined {\n if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) return undefined\n const name = property.name\n if (!name) return undefined\n if (ts.isIdentifier(name)) return name.text\n if (ts.isStringLiteralLike(name)) return name.text\n return undefined\n}\n\nfunction getObjectPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): ts.Expression | undefined {\n for (const property of objectLiteral.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n if (getPropertyName(property) === propertyName) return property.initializer\n }\n return undefined\n}\n\nfunction findObjectLiteralDeclaration(\n sourceFile: ts.SourceFile,\n variableName: string,\n): ts.ObjectLiteralExpression | null {\n let result: ts.ObjectLiteralExpression | null = null\n const visit = (node: ts.Node): void => {\n if (result) return\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === variableName &&\n node.initializer\n ) {\n const unwrapped = unwrapExpression(node.initializer)\n if (ts.isObjectLiteralExpression(unwrapped)) {\n result = unwrapped\n return\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return result\n}\n\nfunction buildVariableInitializerMap(sourceFile: ts.SourceFile): Map<string, ts.Expression> {\n const initializers = new Map<string, ts.Expression>()\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {\n if (!initializers.has(node.name.text)) initializers.set(node.name.text, node.initializer)\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return initializers\n}\n\nfunction resolveToObjectLiteral(\n expression: ts.Expression,\n initializers: Map<string, ts.Expression>,\n): ts.ObjectLiteralExpression | null {\n const unwrapped = unwrapExpression(expression)\n if (ts.isObjectLiteralExpression(unwrapped)) return unwrapped\n if (ts.isIdentifier(unwrapped)) {\n const referenced = initializers.get(unwrapped.text)\n if (referenced) return resolveToObjectLiteral(referenced, initializers)\n }\n return null\n}\n\nfunction resolveToArrayLiteral(\n expression: ts.Expression,\n initializers: Map<string, ts.Expression>,\n): ts.ArrayLiteralExpression | null {\n const unwrapped = unwrapExpression(expression)\n if (ts.isArrayLiteralExpression(unwrapped)) return unwrapped\n if (ts.isIdentifier(unwrapped)) {\n const referenced = initializers.get(unwrapped.text)\n if (referenced) return resolveToArrayLiteral(referenced, initializers)\n }\n return null\n}\n\nfunction findDefaultExportExpression(sourceFile: ts.SourceFile): ts.Expression | null {\n for (const statement of sourceFile.statements) {\n if (ts.isExportAssignment(statement) && !statement.isExportEquals) return statement.expression\n }\n return null\n}\n\nfunction findArrayLiteralDeclaration(\n sourceFile: ts.SourceFile,\n variableName: string,\n): ts.ArrayLiteralExpression | null {\n let result: ts.ArrayLiteralExpression | null = null\n const visit = (node: ts.Node): void => {\n if (result) return\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === variableName &&\n node.initializer\n ) {\n const arrayLiteral = unwrapArrayLiteral(node.initializer)\n if (arrayLiteral) {\n result = arrayLiteral\n return\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return result\n}\n\nfunction extractEvents(eventsFilePath: string | null): ModuleEventFact[] {\n const sourceFile = eventsFilePath ? readSourceFile(eventsFilePath) : null\n if (!sourceFile) return []\n\n const eventsArray = findArrayLiteralDeclaration(sourceFile, 'events')\n if (!eventsArray) return []\n\n const facts: ModuleEventFact[] = []\n for (const element of eventsArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const id = readStringPropertyInitializer(element, 'id')\n if (!id) continue\n const label = readStringPropertyInitializer(element, 'label')\n const category = readStringPropertyInitializer(element, 'category')\n const entity = readStringPropertyInitializer(element, 'entity')\n const fact: ModuleEventFact = {\n id,\n category: category ?? null,\n entity: entity ?? null,\n }\n if (label !== undefined) fact.label = label\n facts.push(fact)\n }\n\n return facts\n}\n\nfunction extractAclFeatures(aclFilePath: string | null): string[] {\n const sourceFile = aclFilePath ? readSourceFile(aclFilePath) : null\n if (!sourceFile) return []\n\n const featuresArray = findArrayLiteralDeclaration(sourceFile, 'features')\n if (!featuresArray) return []\n\n const featureIds: string[] = []\n const seen = new Set<string>()\n for (const element of featuresArray.elements) {\n let featureId: string | undefined\n if (ts.isObjectLiteralExpression(element)) {\n featureId = readStringPropertyInitializer(element, 'id')\n } else if (ts.isStringLiteralLike(element)) {\n featureId = element.text\n }\n if (!featureId || seen.has(featureId)) continue\n seen.add(featureId)\n featureIds.push(featureId)\n }\n\n return featureIds\n}\n\nfunction readBooleanPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): boolean | undefined {\n const initializer = getObjectPropertyInitializer(objectLiteral, propertyName)\n if (!initializer) return undefined\n if (initializer.kind === ts.SyntaxKind.TrueKeyword) return true\n if (initializer.kind === ts.SyntaxKind.FalseKeyword) return false\n return undefined\n}\n\nfunction readStringArrayPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): string[] | undefined {\n const initializer = getObjectPropertyInitializer(objectLiteral, propertyName)\n if (!initializer) return undefined\n const arrayLiteral = unwrapArrayLiteral(initializer)\n if (!arrayLiteral) return undefined\n const values: string[] = []\n for (const element of arrayLiteral.elements) {\n if (ts.isStringLiteralLike(element)) values.push(element.text)\n }\n return values\n}\n\nfunction parseApiRouteAuthRule(metadataLiteral: ts.ObjectLiteralExpression): ApiRouteAuthRule {\n const rule: ApiRouteAuthRule = {}\n const requireAuth = readBooleanPropertyInitializer(metadataLiteral, 'requireAuth')\n if (requireAuth !== undefined) rule.requireAuth = requireAuth\n const requireFeatures = readStringArrayPropertyInitializer(metadataLiteral, 'requireFeatures')\n if (requireFeatures && requireFeatures.length > 0) rule.requireFeatures = requireFeatures\n const requireRoles = readStringArrayPropertyInitializer(metadataLiteral, 'requireRoles')\n if (requireRoles && requireRoles.length > 0) rule.requireRoles = requireRoles\n return rule\n}\n\nfunction parseApiRouteEntry(entryLiteral: ts.ObjectLiteralExpression): ModuleApiRouteFact | null {\n const routePath = readStringPropertyInitializer(entryLiteral, 'path')\n if (!routePath) return null\n\n const methods: string[] = []\n const seenMethods = new Set<string>()\n const handlersInitializer = getObjectPropertyInitializer(entryLiteral, 'handlers')\n if (handlersInitializer && ts.isObjectLiteralExpression(handlersInitializer)) {\n for (const property of handlersInitializer.properties) {\n const methodName = getPropertyName(property)\n if (methodName && !seenMethods.has(methodName)) {\n seenMethods.add(methodName)\n methods.push(methodName)\n }\n }\n } else {\n const singleMethod = readStringPropertyInitializer(entryLiteral, 'method')\n if (singleMethod && !seenMethods.has(singleMethod)) {\n seenMethods.add(singleMethod)\n methods.push(singleMethod)\n }\n }\n\n const auth: Record<string, ApiRouteAuthRule> = {}\n const metadataInitializer = getObjectPropertyInitializer(entryLiteral, 'metadata')\n if (metadataInitializer && ts.isObjectLiteralExpression(metadataInitializer)) {\n for (const property of metadataInitializer.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n const methodName = getPropertyName(property)\n if (!methodName) continue\n const methodMetadata = unwrapExpression(property.initializer)\n if (!ts.isObjectLiteralExpression(methodMetadata)) continue\n auth[methodName] = parseApiRouteAuthRule(methodMetadata)\n if (!seenMethods.has(methodName)) {\n seenMethods.add(methodName)\n methods.push(methodName)\n }\n }\n }\n\n return { path: routePath, methods, auth }\n}\n\nfunction extractApiRoutes(\n moduleId: string,\n registrySource: string | null,\n registryDescription: string,\n warnings: string[],\n): ModuleApiRouteFact[] {\n if (registrySource == null) {\n warnings.push(`[module-facts] module registry unavailable (${registryDescription}); API route auth omitted for ${moduleId}`)\n return []\n }\n\n const sourceFile = ts.createSourceFile(\n 'module-registry.generated.ts',\n registrySource,\n ts.ScriptTarget.ES2020,\n true,\n ts.ScriptKind.TS,\n )\n\n const routes: ModuleApiRouteFact[] = []\n const seenPaths = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (ts.isObjectLiteralExpression(node) && readStringPropertyInitializer(node, 'id') === moduleId) {\n const apisInitializer = getObjectPropertyInitializer(node, 'apis')\n const apisArray = apisInitializer ? unwrapArrayLiteral(apisInitializer) : null\n if (apisArray) {\n for (const element of apisArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const route = parseApiRouteEntry(element)\n if (route && !seenPaths.has(route.path)) {\n seenPaths.add(route.path)\n routes.push(route)\n }\n }\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return routes\n}\n\nfunction resolveRegistrySource(options: ExtractModuleFactsOptions): { source: string | null; description: string } {\n if (typeof options.registrySource === 'string') {\n return { source: options.registrySource, description: 'registrySource' }\n }\n if (options.registryPath) {\n if (!fs.existsSync(options.registryPath)) {\n return { source: null, description: options.registryPath }\n }\n return { source: fs.readFileSync(options.registryPath, 'utf8'), description: options.registryPath }\n }\n return { source: null, description: 'registryPath not provided' }\n}\n\nfunction detectAwilixRegistrationKind(expression: ts.Expression): string | null {\n let current: ts.Expression = unwrapExpression(expression)\n while (ts.isCallExpression(current)) {\n const callee = current.expression\n if (ts.isIdentifier(callee)) return callee.text\n if (ts.isPropertyAccessExpression(callee)) {\n current = callee.expression\n continue\n }\n break\n }\n return null\n}\n\nfunction extractDiTokens(diFilePath: string | null): string[] {\n if (!diFilePath) return []\n const sourceFile = readSourceFile(diFilePath)\n if (!sourceFile) return []\n\n const tokens: string[] = []\n const seen = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === 'register'\n ) {\n const argument = node.arguments[0]\n if (argument && ts.isObjectLiteralExpression(argument)) {\n for (const property of argument.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n const kind = detectAwilixRegistrationKind(property.initializer)\n if (kind !== 'asFunction' && kind !== 'asClass') continue\n const tokenName = getPropertyName(property)\n if (tokenName && !seen.has(tokenName)) {\n seen.add(tokenName)\n tokens.push(tokenName)\n }\n }\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return tokens\n}\n\nfunction extractSearchEntities(searchFilePath: string | null, warnings: string[]): string[] {\n if (!searchFilePath) return []\n const sourceFile = readSourceFile(searchFilePath)\n if (!sourceFile) return []\n\n const searchConfig = findObjectLiteralDeclaration(sourceFile, 'searchConfig')\n if (!searchConfig) {\n warnings.push(`[module-facts] search.ts present but no searchConfig object literal: ${searchFilePath}`)\n return []\n }\n const entitiesInitializer = getObjectPropertyInitializer(searchConfig, 'entities')\n const entitiesArray = entitiesInitializer ? unwrapArrayLiteral(entitiesInitializer) : null\n if (!entitiesArray) {\n warnings.push(`[module-facts] searchConfig.entities is not an array literal: ${searchFilePath}`)\n return []\n }\n\n const entityIds: string[] = []\n const seen = new Set<string>()\n for (const element of entitiesArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const entityId = readStringPropertyInitializer(element, 'entityId')\n if (entityId && !seen.has(entityId)) {\n seen.add(entityId)\n entityIds.push(entityId)\n }\n }\n return entityIds\n}\n\nfunction extractNotifications(notificationsFilePath: string | null, warnings: string[]): string[] {\n if (!notificationsFilePath) return []\n const sourceFile = readSourceFile(notificationsFilePath)\n if (!sourceFile) return []\n\n const notificationsArray =\n findArrayLiteralDeclaration(sourceFile, 'notificationTypes') ??\n findArrayLiteralDeclaration(sourceFile, 'notifications')\n if (!notificationsArray) {\n warnings.push(`[module-facts] notifications.ts present but no notificationTypes array literal: ${notificationsFilePath}`)\n return []\n }\n\n const notificationIds: string[] = []\n const seen = new Set<string>()\n for (const element of notificationsArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const notificationId = readStringPropertyInitializer(element, 'type')\n if (notificationId && !seen.has(notificationId)) {\n seen.add(notificationId)\n notificationIds.push(notificationId)\n }\n }\n return notificationIds\n}\n\nfunction extractCli(cliFilePath: string | null, warnings: string[]): string[] {\n if (!cliFilePath) return []\n const sourceFile = readSourceFile(cliFilePath)\n if (!sourceFile) return []\n\n const defaultExport = findDefaultExportExpression(sourceFile)\n if (!defaultExport) {\n warnings.push(`[module-facts] cli.ts present but no default export: ${cliFilePath}`)\n return []\n }\n\n const initializers = buildVariableInitializerMap(sourceFile)\n const collectCommand = (objectLiteral: ts.ObjectLiteralExpression): string | undefined =>\n readStringPropertyInitializer(objectLiteral, 'command')\n\n const commands: string[] = []\n const seen = new Set<string>()\n const pushCommand = (command: string | undefined): void => {\n if (command && !seen.has(command)) {\n seen.add(command)\n commands.push(command)\n }\n }\n\n const arrayLiteral = resolveToArrayLiteral(defaultExport, initializers)\n if (arrayLiteral) {\n for (const element of arrayLiteral.elements) {\n const objectLiteral = resolveToObjectLiteral(element, initializers)\n if (objectLiteral) pushCommand(collectCommand(objectLiteral))\n }\n return commands\n }\n\n const singleObject = resolveToObjectLiteral(defaultExport, initializers)\n if (singleObject) {\n pushCommand(collectCommand(singleObject))\n return commands\n }\n\n warnings.push(`[module-facts] cli.ts default export is neither an array nor an object literal: ${cliFilePath}`)\n return commands\n}\n\nfunction listSourceFilesRecursive(directory: string): string[] {\n const files: string[] = []\n for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {\n if (entry.name === '__tests__' || entry.name === 'node_modules') continue\n const fullPath = path.join(directory, entry.name)\n if (entry.isDirectory()) {\n files.push(...listSourceFilesRecursive(fullPath))\n } else if (/\\.tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {\n files.push(fullPath)\n }\n }\n return files\n}\n\nfunction extractTableIds(backendDir: string): string[] {\n if (!fs.existsSync(backendDir)) return []\n\n const tableIds: string[] = []\n const seen = new Set<string>()\n for (const filePath of listSourceFilesRecursive(backendDir)) {\n const sourceFile = readSourceFile(filePath)\n if (!sourceFile) continue\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAssignment(node)) {\n const propertyName = getPropertyName(node)\n if (\n (propertyName === 'tableId' || propertyName === 'extensionTableId') &&\n ts.isStringLiteralLike(node.initializer)\n ) {\n const value = node.initializer.text\n if (value && !seen.has(value)) {\n seen.add(value)\n tableIds.push(value)\n }\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n }\n tableIds.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n return tableIds\n}\n\nfunction extractHostEntityIds(entities: ModuleEntityFact[]): string[] {\n return entities.filter((entity) => entity.id.endsWith('_entity')).map((entity) => entity.id)\n}\n\nfunction extractModuleMeta(indexFilePath: string | null): { title: string | null; description: string | null } {\n if (!indexFilePath) return { title: null, description: null }\n const sourceFile = readSourceFile(indexFilePath)\n if (!sourceFile) return { title: null, description: null }\n const metadata = findObjectLiteralDeclaration(sourceFile, 'metadata')\n if (!metadata) return { title: null, description: null }\n return {\n title: readStringPropertyInitializer(metadata, 'title') ?? null,\n description: readStringPropertyInitializer(metadata, 'description') ?? null,\n }\n}\n\nexport function extractModuleFacts(options: ExtractModuleFactsOptions): ModuleFacts {\n const { moduleId, coreVersion = null } = options\n const moduleRoot = options.moduleRoot\n ?? (options.coreSrcRoot ? path.join(options.coreSrcRoot, moduleId) : null)\n if (!moduleRoot) {\n throw new Error(`[internal] extractModuleFacts requires moduleRoot or coreSrcRoot for module \"${moduleId}\"`)\n }\n\n const entitiesFilePath =\n resolveConventionFile(path.join(moduleRoot, 'data'), 'entities') ??\n resolveConventionFile(path.join(moduleRoot, 'db'), 'entities') ??\n resolveConventionFile(path.join(moduleRoot, 'data'), 'schema')\n const ceFilePath = resolveConventionFile(moduleRoot, 'ce')\n const eventsFilePath = resolveConventionFile(moduleRoot, 'events')\n const aclFilePath = resolveConventionFile(moduleRoot, 'acl')\n const diFilePath = resolveConventionFile(moduleRoot, 'di')\n const searchFilePath = resolveConventionFile(moduleRoot, 'search')\n const notificationsFilePath = resolveConventionFile(moduleRoot, 'notifications')\n const cliFilePath = resolveConventionFile(moduleRoot, 'cli')\n const indexFilePath = resolveConventionFile(moduleRoot, 'index')\n const backendDir = path.join(moduleRoot, 'backend')\n\n const warnings: string[] = []\n const { title, description } = extractModuleMeta(indexFilePath)\n const customFieldEntityIds = collectCustomFieldEntityIds(ceFilePath)\n const entities = extractEntities(moduleId, entitiesFilePath, customFieldEntityIds)\n const events = extractEvents(eventsFilePath)\n const aclFeatures = extractAclFeatures(aclFilePath)\n\n const { source: registrySource, description: registryDescription } = resolveRegistrySource(options)\n const apiRoutes = extractApiRoutes(moduleId, registrySource, registryDescription, warnings)\n const diTokens = extractDiTokens(diFilePath)\n const searchEntities = extractSearchEntities(searchFilePath, warnings)\n const notifications = extractNotifications(notificationsFilePath, warnings)\n const cli = extractCli(cliFilePath, warnings)\n const hostTokens: ModuleHostTokens = {\n entityIds: extractHostEntityIds(entities),\n tableIds: extractTableIds(backendDir),\n }\n\n return {\n module: moduleId,\n title,\n description,\n coreVersion,\n entities,\n events,\n aclFeatures,\n apiRoutes,\n diTokens,\n searchEntities,\n hostTokens,\n notifications,\n cli,\n warnings,\n }\n}\n\nexport interface ModuleFactsJsonEvent {\n id: string\n category: string | null\n entity: string | null\n}\n\nexport interface ModuleFactsJsonEntry {\n title: string | null\n description: string | null\n coreVersion: string | null\n entities: ModuleEntityFact[]\n events: ModuleFactsJsonEvent[]\n aclFeatures: string[]\n apiRoutes: ModuleApiRouteFact[]\n diTokens: string[]\n searchEntities: string[]\n hostTokens: ModuleHostTokens\n notifications: string[]\n cli: string[]\n}\n\nconst EMPTY_SECTION_MARKER = '_none_'\n\nfunction renderVersionStamp(coreVersion: string | null): string {\n const version = coreVersion && coreVersion.length > 0 ? coreVersion : '<unknown>'\n return `<!-- generated from @open-mercato/core ${version} \u2014 R1 staleness stamp -->`\n}\n\nfunction renderEntitiesSection(entities: ModuleEntityFact[]): string {\n if (entities.length === 0) return `## Entities\\n\\n${EMPTY_SECTION_MARKER}`\n const header = '| Entity ID | Class | Table | Editable | CustomFields |'\n const divider = '|---|---|---|---|---|'\n const rows = entities.map(\n (entity) =>\n `| ${entity.id} | ${entity.class} | ${entity.table} | ${entity.editable ? 'yes' : 'no'} | ${entity.customFields ? 'yes' : 'no'} |`,\n )\n return ['## Entities', '', header, divider, ...rows].join('\\n')\n}\n\nfunction renderEventsSection(events: ModuleEventFact[]): string {\n const heading = `## Events (${events.length})`\n if (events.length === 0) return `${heading}\\n\\n${EMPTY_SECTION_MARKER}`\n const header = '| ID | Category | Entity |'\n const divider = '|---|---|---|'\n const rows = events.map((event) => `| ${event.id} | ${event.category ?? '\u2014'} | ${event.entity ?? '\u2014'} |`)\n return [heading, '', header, divider, ...rows].join('\\n')\n}\n\nfunction renderInlineListSection(heading: string, values: string[]): string {\n if (values.length === 0) return `${heading}\\n\\n${EMPTY_SECTION_MARKER}`\n return `${heading}\\n\\n${values.join(' \u00B7 ')}`\n}\n\nfunction describeAuthRule(rule: ApiRouteAuthRule | undefined): string {\n if (!rule) return 'public'\n if (rule.requireFeatures && rule.requireFeatures.length > 0) return rule.requireFeatures.join(', ')\n if (rule.requireRoles && rule.requireRoles.length > 0) return rule.requireRoles.join(', ')\n if (rule.requireAuth) return 'auth'\n return 'public'\n}\n\nfunction renderApiRouteAuthCell(route: ModuleApiRouteFact): string {\n if (route.methods.length === 0) return '\u2014'\n const groups: Array<{ label: string; methods: string[] }> = []\n for (const method of route.methods) {\n const label = describeAuthRule(route.auth[method])\n const existing = groups.find((group) => group.label === label)\n if (existing) existing.methods.push(method)\n else groups.push({ label, methods: [method] })\n }\n return groups.map((group) => `${group.methods.join('/')} \u2192 ${group.label}`).join(' \u00B7 ')\n}\n\nfunction renderApiRoutesSection(routes: ModuleApiRouteFact[]): string {\n if (routes.length === 0) return `## API routes\\n\\n${EMPTY_SECTION_MARKER}`\n const header = '| Path | Methods | Auth (per-method requireFeatures) |'\n const divider = '|---|---|---|'\n const rows = routes.map(\n (route) => `| ${route.path} | ${route.methods.join(' ')} | ${renderApiRouteAuthCell(route)} |`,\n )\n return ['## API routes', '', header, divider, ...rows].join('\\n')\n}\n\nfunction renderHostTokensSection(hostTokens: ModuleHostTokens): string {\n const entityIdsLine = hostTokens.entityIds.length > 0 ? hostTokens.entityIds.join(' \u00B7 ') : EMPTY_SECTION_MARKER\n const tableIdsLine = hostTokens.tableIds.length > 0 ? hostTokens.tableIds.join(' \u00B7 ') : EMPTY_SECTION_MARKER\n return ['## Host extension points', '', `- Entity IDs: ${entityIdsLine}`, `- Table IDs: ${tableIdsLine}`].join('\\n')\n}\n\nexport function renderModuleFactsMarkdown(facts: ModuleFacts): string {\n const sections = [\n `# ${facts.module} \u2014 module facts (generated, do not edit)`,\n renderVersionStamp(facts.coreVersion),\n '',\n renderEntitiesSection(facts.entities),\n '',\n renderEventsSection(facts.events),\n '',\n renderInlineListSection(`## ACL features (${facts.aclFeatures.length})`, facts.aclFeatures),\n '',\n renderApiRoutesSection(facts.apiRoutes),\n '',\n renderInlineListSection('## DI service tokens', facts.diTokens),\n '',\n renderInlineListSection('## Search entities', facts.searchEntities),\n '',\n renderHostTokensSection(facts.hostTokens),\n '',\n renderInlineListSection('## Notifications', facts.notifications),\n '',\n renderInlineListSection('## CLI', facts.cli),\n '',\n ]\n return sections.join('\\n')\n}\n\nexport function toModuleFactsJsonEntry(facts: ModuleFacts): ModuleFactsJsonEntry {\n return {\n title: facts.title,\n description: facts.description,\n coreVersion: facts.coreVersion,\n entities: facts.entities,\n events: facts.events.map((event) => ({ id: event.id, category: event.category, entity: event.entity })),\n aclFeatures: facts.aclFeatures,\n apiRoutes: facts.apiRoutes,\n diTokens: facts.diTokens,\n searchEntities: facts.searchEntities,\n hostTokens: facts.hostTokens,\n notifications: facts.notifications,\n cli: facts.cli,\n }\n}\n\nexport function buildModuleFactsJsonObject(\n factsByModule: Record<string, ModuleFacts>,\n): Record<string, ModuleFactsJsonEntry> {\n const result: Record<string, ModuleFactsJsonEntry> = {}\n for (const moduleId of Object.keys(factsByModule).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n result[moduleId] = toModuleFactsJsonEntry(factsByModule[moduleId])\n }\n return result\n}\n\nexport function renderModuleFactsJson(factsByModule: Record<string, ModuleFacts>): string {\n return `${JSON.stringify(buildModuleFactsJsonObject(factsByModule), null, 2)}\\n`\n}\n\nexport interface ExtractAllModuleFactsOptions {\n /**\n * Discovered module sources (auto-discovery path). When provided, each entry's\n * explicit `moduleRoot` is used and `coreSrcRoot`/`moduleIds` are ignored.\n */\n sources?: readonly ModuleFactSource[]\n /** Legacy shared-root path. Used only when `sources` is not provided. */\n coreSrcRoot?: string\n registryPath?: string | null\n registrySource?: string | null\n coreVersion?: string | null\n /** @deprecated Legacy allowlist iteration; only consulted when `sources` is absent. */\n moduleIds?: readonly string[]\n}\n\nexport interface ExtractAllModuleFactsResult {\n factsByModule: Record<string, ModuleFacts>\n markdownByModule: Record<string, string>\n warnings: string[]\n}\n\nexport function extractAllModuleFacts(options: ExtractAllModuleFactsOptions): ExtractAllModuleFactsResult {\n const sources: ModuleFactSource[] = options.sources\n ? [...options.sources]\n : (options.coreSrcRoot\n ? (options.moduleIds ?? MODULE_FACTS_ALLOWLIST).map((moduleId) => ({\n moduleId,\n moduleRoot: path.join(options.coreSrcRoot as string, moduleId),\n }))\n : [])\n\n const factsByModule: Record<string, ModuleFacts> = {}\n const markdownByModule: Record<string, string> = {}\n const warnings: string[] = []\n for (const source of sources) {\n const facts = extractModuleFacts({\n moduleId: source.moduleId,\n moduleRoot: source.moduleRoot,\n coreVersion: options.coreVersion ?? null,\n registryPath: options.registryPath ?? null,\n registrySource: options.registrySource ?? null,\n })\n factsByModule[source.moduleId] = facts\n markdownByModule[source.moduleId] = renderModuleFactsMarkdown(facts)\n warnings.push(...facts.warnings)\n }\n return { factsByModule, markdownByModule, warnings }\n}\n"],
5
- "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,eAAe;AA+EjB,MAAM,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKA,SAAS,eAAe,UAAwC;AAC9D,MAAI,CAAC,GAAG,WAAW,QAAQ,EAAG,QAAO;AACrC,QAAM,SAAS,GAAG,aAAa,UAAU,MAAM;AAC/C,QAAM,aAAa,SAAS,SAAS,MAAM,IAAI,GAAG,WAAW,MAAM,GAAG,WAAW;AACjF,S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KAAK,KAAK,QAAQ,aAAuB,QAAQ;AAAA,EAC/D,EAAE,IACF,CAAC;AAET,QAAM,gBAA6C,CAAC;AACpD,QAAM,mBAA2C,CAAC;AAClD,QAAM,WAAqB,CAAC;AAC5B,aAAW,UAAU,SAAS;AAC5B,UAAM,QAAQ,mBAAmB;AAAA,MAC/B,UAAU,OAAO;AAAA,MACjB,YAAY,OAAO;AAAA,MACnB,aAAa,QAAQ,eAAe;AAAA,MACpC,cAAc,QAAQ,gBAAgB;AAAA,MACtC,gBAAgB,QAAQ,kBAAkB;AAAA,IAC5C,CAAC;AACD,kBAAc,OAAO,QAAQ,IAAI;AACjC,qBAAiB,OAAO,QAAQ,IAAI,0BAA0B,KAAK;AACnE,aAAS,KAAK,GAAG,MAAM,QAAQ;AAAA,EACjC;AACA,SAAO,EAAE,eAAe,kBAAkB,SAAS;AACrD;",
4
+ "sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport ts from 'typescript'\nimport { toSnake } from '../utils'\n\nexport interface ModuleEntityFact {\n id: string\n class: string\n table: string\n editable: boolean\n customFields: boolean\n}\n\nexport interface ApiRouteAuthRule {\n requireAuth?: boolean\n requireFeatures?: string[]\n requireRoles?: string[]\n}\n\nexport interface ModuleApiRouteFact {\n path: string\n methods: string[]\n auth: Record<string, ApiRouteAuthRule>\n}\n\nexport interface ModuleEventFact {\n id: string\n label?: string\n category: string | null\n entity: string | null\n}\n\nexport interface ModuleHostTokens {\n entityIds: string[]\n tableIds: string[]\n}\n\nexport interface ModuleFacts {\n module: string\n title: string | null\n description: string | null\n coreVersion: string | null\n entities: ModuleEntityFact[]\n events: ModuleEventFact[]\n aclFeatures: string[]\n apiRoutes: ModuleApiRouteFact[]\n diTokens: string[]\n searchEntities: string[]\n hostTokens: ModuleHostTokens\n notifications: string[]\n cli: string[]\n warnings: string[]\n}\n\nexport interface ExtractModuleFactsOptions {\n moduleId: string\n /**\n * Parent modules directory joined with `moduleId` to locate the module source.\n * Legacy input; prefer the explicit per-module `moduleRoot` for modules that do\n * not live under a single shared root (auto-discovery). One of `moduleRoot` /\n * `coreSrcRoot` must be provided.\n */\n coreSrcRoot?: string\n /** Explicit module source directory. When set it overrides `coreSrcRoot + moduleId`. */\n moduleRoot?: string\n coreVersion?: string | null\n registryPath?: string | null\n registrySource?: string | null\n}\n\n/** A discovered module and the source directory its facts are extracted from. */\nexport interface ModuleFactSource {\n moduleId: string\n moduleRoot: string\n from?: string\n}\n\nfunction readSourceFile(filePath: string): ts.SourceFile | null {\n if (!fs.existsSync(filePath)) return null\n const source = fs.readFileSync(filePath, 'utf8')\n const scriptKind = filePath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS\n return ts.createSourceFile(filePath, source, ts.ScriptTarget.ES2020, true, scriptKind)\n}\n\nfunction resolveConventionFile(baseDir: string, basename: string): string | null {\n for (const extension of ['.ts', '.tsx']) {\n const candidate = path.join(baseDir, `${basename}${extension}`)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nfunction readStringPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): string | undefined {\n for (const property of objectLiteral.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n const name = ts.isIdentifier(property.name)\n ? property.name.text\n : ts.isStringLiteralLike(property.name)\n ? property.name.text\n : undefined\n if (name !== propertyName) continue\n if (ts.isStringLiteralLike(property.initializer)) return property.initializer.text\n return undefined\n }\n return undefined\n}\n\nfunction getClassDecoratorCall(node: ts.ClassDeclaration, decoratorName: string): ts.CallExpression | undefined {\n const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) ?? [] : []\n for (const decorator of decorators) {\n const expression = decorator.expression\n if (!ts.isCallExpression(expression)) continue\n if (ts.isIdentifier(expression.expression) && expression.expression.text === decoratorName) {\n return expression\n }\n }\n return undefined\n}\n\nfunction readDecoratorTableName(decoratorCall: ts.CallExpression): string | undefined {\n const firstArgument = decoratorCall.arguments[0]\n if (!firstArgument || !ts.isObjectLiteralExpression(firstArgument)) return undefined\n return readStringPropertyInitializer(firstArgument, 'tableName')\n}\n\nfunction getPropertyDecoratorName(member: ts.PropertyDeclaration): string | undefined {\n const decorators = ts.canHaveDecorators(member) ? ts.getDecorators(member) ?? [] : []\n for (const decorator of decorators) {\n const expression = decorator.expression\n if (!ts.isCallExpression(expression)) continue\n const firstArgument = expression.arguments[0]\n if (!firstArgument || !ts.isObjectLiteralExpression(firstArgument)) continue\n const columnName = readStringPropertyInitializer(firstArgument, 'name')\n if (columnName) return columnName\n }\n return undefined\n}\n\nfunction classHasUpdatedAtColumn(node: ts.ClassDeclaration): boolean {\n for (const member of node.members) {\n if (!ts.isPropertyDeclaration(member) || !member.name) continue\n const propertyName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteralLike(member.name)\n ? member.name.text\n : undefined\n if (propertyName === 'updatedAt') return true\n if (getPropertyDecoratorName(member) === 'updated_at') return true\n }\n return false\n}\n\nfunction collectCustomFieldEntityIds(ceFilePath: string | null): Set<string> {\n const result = new Set<string>()\n if (!ceFilePath) return result\n const sourceFile = readSourceFile(ceFilePath)\n if (!sourceFile) return result\n\n const visit = (node: ts.Node): void => {\n if (ts.isObjectLiteralExpression(node)) {\n const id = readStringPropertyInitializer(node, 'id')\n if (id && id.includes(':')) result.add(id)\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return result\n}\n\nfunction extractEntities(\n moduleId: string,\n entitiesFilePath: string | null,\n customFieldEntityIds: Set<string>,\n): ModuleEntityFact[] {\n const sourceFile = entitiesFilePath ? readSourceFile(entitiesFilePath) : null\n if (!sourceFile) return []\n\n const facts: ModuleEntityFact[] = []\n sourceFile.forEachChild((node) => {\n if (!ts.isClassDeclaration(node) || !node.name) return\n const isExported = node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n if (!isExported) return\n const entityDecorator = getClassDecoratorCall(node, 'Entity')\n if (!entityDecorator) return\n\n const className = node.name.text\n const table = readDecoratorTableName(entityDecorator)\n if (!table) return\n\n const entityId = `${moduleId}:${toSnake(className)}`\n facts.push({\n id: entityId,\n class: className,\n table,\n editable: classHasUpdatedAtColumn(node),\n customFields: customFieldEntityIds.has(entityId),\n })\n })\n\n return facts\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression\n while (ts.isAsExpression(current) || ts.isParenthesizedExpression(current) || ts.isTypeAssertionExpression(current)) {\n current = current.expression\n }\n return current\n}\n\nfunction unwrapArrayLiteral(expression: ts.Expression): ts.ArrayLiteralExpression | null {\n const current = unwrapExpression(expression)\n return ts.isArrayLiteralExpression(current) ? current : null\n}\n\nfunction getPropertyName(property: ts.ObjectLiteralElementLike): string | undefined {\n if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) return undefined\n const name = property.name\n if (!name) return undefined\n if (ts.isIdentifier(name)) return name.text\n if (ts.isStringLiteralLike(name)) return name.text\n return undefined\n}\n\nfunction getObjectPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): ts.Expression | undefined {\n for (const property of objectLiteral.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n if (getPropertyName(property) === propertyName) return property.initializer\n }\n return undefined\n}\n\nfunction findObjectLiteralDeclaration(\n sourceFile: ts.SourceFile,\n variableName: string,\n): ts.ObjectLiteralExpression | null {\n let result: ts.ObjectLiteralExpression | null = null\n const visit = (node: ts.Node): void => {\n if (result) return\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === variableName &&\n node.initializer\n ) {\n const unwrapped = unwrapExpression(node.initializer)\n if (ts.isObjectLiteralExpression(unwrapped)) {\n result = unwrapped\n return\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return result\n}\n\nfunction buildVariableInitializerMap(sourceFile: ts.SourceFile): Map<string, ts.Expression> {\n const initializers = new Map<string, ts.Expression>()\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {\n if (!initializers.has(node.name.text)) initializers.set(node.name.text, node.initializer)\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return initializers\n}\n\nfunction resolveToObjectLiteral(\n expression: ts.Expression,\n initializers: Map<string, ts.Expression>,\n): ts.ObjectLiteralExpression | null {\n const unwrapped = unwrapExpression(expression)\n if (ts.isObjectLiteralExpression(unwrapped)) return unwrapped\n if (ts.isIdentifier(unwrapped)) {\n const referenced = initializers.get(unwrapped.text)\n if (referenced) return resolveToObjectLiteral(referenced, initializers)\n }\n return null\n}\n\nfunction resolveToArrayLiteral(\n expression: ts.Expression,\n initializers: Map<string, ts.Expression>,\n): ts.ArrayLiteralExpression | null {\n const unwrapped = unwrapExpression(expression)\n if (ts.isArrayLiteralExpression(unwrapped)) return unwrapped\n if (ts.isIdentifier(unwrapped)) {\n const referenced = initializers.get(unwrapped.text)\n if (referenced) return resolveToArrayLiteral(referenced, initializers)\n }\n return null\n}\n\nfunction findDefaultExportExpression(sourceFile: ts.SourceFile): ts.Expression | null {\n for (const statement of sourceFile.statements) {\n if (ts.isExportAssignment(statement) && !statement.isExportEquals) return statement.expression\n }\n return null\n}\n\nfunction findArrayLiteralDeclaration(\n sourceFile: ts.SourceFile,\n variableName: string,\n): ts.ArrayLiteralExpression | null {\n let result: ts.ArrayLiteralExpression | null = null\n const visit = (node: ts.Node): void => {\n if (result) return\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === variableName &&\n node.initializer\n ) {\n const arrayLiteral = unwrapArrayLiteral(node.initializer)\n if (arrayLiteral) {\n result = arrayLiteral\n return\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return result\n}\n\nfunction extractEvents(eventsFilePath: string | null): ModuleEventFact[] {\n const sourceFile = eventsFilePath ? readSourceFile(eventsFilePath) : null\n if (!sourceFile) return []\n\n const eventsArray = findArrayLiteralDeclaration(sourceFile, 'events')\n if (!eventsArray) return []\n\n const facts: ModuleEventFact[] = []\n for (const element of eventsArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const id = readStringPropertyInitializer(element, 'id')\n if (!id) continue\n const label = readStringPropertyInitializer(element, 'label')\n const category = readStringPropertyInitializer(element, 'category')\n const entity = readStringPropertyInitializer(element, 'entity')\n const fact: ModuleEventFact = {\n id,\n category: category ?? null,\n entity: entity ?? null,\n }\n if (label !== undefined) fact.label = label\n facts.push(fact)\n }\n\n return facts\n}\n\nfunction extractAclFeatures(aclFilePath: string | null): string[] {\n const sourceFile = aclFilePath ? readSourceFile(aclFilePath) : null\n if (!sourceFile) return []\n\n const featuresArray = findArrayLiteralDeclaration(sourceFile, 'features')\n if (!featuresArray) return []\n\n const featureIds: string[] = []\n const seen = new Set<string>()\n for (const element of featuresArray.elements) {\n let featureId: string | undefined\n if (ts.isObjectLiteralExpression(element)) {\n featureId = readStringPropertyInitializer(element, 'id')\n } else if (ts.isStringLiteralLike(element)) {\n featureId = element.text\n }\n if (!featureId || seen.has(featureId)) continue\n seen.add(featureId)\n featureIds.push(featureId)\n }\n\n return featureIds\n}\n\nfunction readBooleanPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): boolean | undefined {\n const initializer = getObjectPropertyInitializer(objectLiteral, propertyName)\n if (!initializer) return undefined\n if (initializer.kind === ts.SyntaxKind.TrueKeyword) return true\n if (initializer.kind === ts.SyntaxKind.FalseKeyword) return false\n return undefined\n}\n\nfunction readStringArrayPropertyInitializer(\n objectLiteral: ts.ObjectLiteralExpression,\n propertyName: string,\n): string[] | undefined {\n const initializer = getObjectPropertyInitializer(objectLiteral, propertyName)\n if (!initializer) return undefined\n const arrayLiteral = unwrapArrayLiteral(initializer)\n if (!arrayLiteral) return undefined\n const values: string[] = []\n for (const element of arrayLiteral.elements) {\n if (ts.isStringLiteralLike(element)) values.push(element.text)\n }\n return values\n}\n\nfunction parseApiRouteAuthRule(metadataLiteral: ts.ObjectLiteralExpression): ApiRouteAuthRule {\n const rule: ApiRouteAuthRule = {}\n const requireAuth = readBooleanPropertyInitializer(metadataLiteral, 'requireAuth')\n if (requireAuth !== undefined) rule.requireAuth = requireAuth\n const requireFeatures = readStringArrayPropertyInitializer(metadataLiteral, 'requireFeatures')\n if (requireFeatures && requireFeatures.length > 0) rule.requireFeatures = requireFeatures\n const requireRoles = readStringArrayPropertyInitializer(metadataLiteral, 'requireRoles')\n if (requireRoles && requireRoles.length > 0) rule.requireRoles = requireRoles\n return rule\n}\n\nfunction parseApiRouteEntry(entryLiteral: ts.ObjectLiteralExpression): ModuleApiRouteFact | null {\n const routePath = readStringPropertyInitializer(entryLiteral, 'path')\n if (!routePath) return null\n\n const methods: string[] = []\n const seenMethods = new Set<string>()\n const handlersInitializer = getObjectPropertyInitializer(entryLiteral, 'handlers')\n if (handlersInitializer && ts.isObjectLiteralExpression(handlersInitializer)) {\n for (const property of handlersInitializer.properties) {\n const methodName = getPropertyName(property)\n if (methodName && !seenMethods.has(methodName)) {\n seenMethods.add(methodName)\n methods.push(methodName)\n }\n }\n } else {\n const singleMethod = readStringPropertyInitializer(entryLiteral, 'method')\n if (singleMethod && !seenMethods.has(singleMethod)) {\n seenMethods.add(singleMethod)\n methods.push(singleMethod)\n }\n }\n\n const auth: Record<string, ApiRouteAuthRule> = {}\n const metadataInitializer = getObjectPropertyInitializer(entryLiteral, 'metadata')\n if (metadataInitializer && ts.isObjectLiteralExpression(metadataInitializer)) {\n for (const property of metadataInitializer.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n const methodName = getPropertyName(property)\n if (!methodName) continue\n const methodMetadata = unwrapExpression(property.initializer)\n if (!ts.isObjectLiteralExpression(methodMetadata)) continue\n auth[methodName] = parseApiRouteAuthRule(methodMetadata)\n if (!seenMethods.has(methodName)) {\n seenMethods.add(methodName)\n methods.push(methodName)\n }\n }\n }\n\n return { path: routePath, methods, auth }\n}\n\nfunction extractApiRoutes(\n moduleId: string,\n registrySource: string | null,\n registryDescription: string,\n warnings: string[],\n): ModuleApiRouteFact[] {\n if (registrySource == null) {\n warnings.push(`[module-facts] module registry unavailable (${registryDescription}); API route auth omitted for ${moduleId}`)\n return []\n }\n\n const sourceFile = ts.createSourceFile(\n 'module-registry.generated.ts',\n registrySource,\n ts.ScriptTarget.ES2020,\n true,\n ts.ScriptKind.TS,\n )\n\n const routes: ModuleApiRouteFact[] = []\n const seenPaths = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (ts.isObjectLiteralExpression(node) && readStringPropertyInitializer(node, 'id') === moduleId) {\n const apisInitializer = getObjectPropertyInitializer(node, 'apis')\n const apisArray = apisInitializer ? unwrapArrayLiteral(apisInitializer) : null\n if (apisArray) {\n for (const element of apisArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const route = parseApiRouteEntry(element)\n if (route && !seenPaths.has(route.path)) {\n seenPaths.add(route.path)\n routes.push(route)\n }\n }\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return routes\n}\n\nfunction resolveRegistrySource(options: ExtractModuleFactsOptions): { source: string | null; description: string } {\n if (typeof options.registrySource === 'string') {\n return { source: options.registrySource, description: 'registrySource' }\n }\n if (options.registryPath) {\n if (!fs.existsSync(options.registryPath)) {\n return { source: null, description: options.registryPath }\n }\n return { source: fs.readFileSync(options.registryPath, 'utf8'), description: options.registryPath }\n }\n return { source: null, description: 'registryPath not provided' }\n}\n\nfunction detectAwilixRegistrationKind(expression: ts.Expression): string | null {\n let current: ts.Expression = unwrapExpression(expression)\n while (ts.isCallExpression(current)) {\n const callee = current.expression\n if (ts.isIdentifier(callee)) return callee.text\n if (ts.isPropertyAccessExpression(callee)) {\n current = callee.expression\n continue\n }\n break\n }\n return null\n}\n\nfunction extractDiTokens(diFilePath: string | null): string[] {\n if (!diFilePath) return []\n const sourceFile = readSourceFile(diFilePath)\n if (!sourceFile) return []\n\n const tokens: string[] = []\n const seen = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n node.expression.name.text === 'register'\n ) {\n const argument = node.arguments[0]\n if (argument && ts.isObjectLiteralExpression(argument)) {\n for (const property of argument.properties) {\n if (!ts.isPropertyAssignment(property)) continue\n const kind = detectAwilixRegistrationKind(property.initializer)\n if (kind !== 'asFunction' && kind !== 'asClass') continue\n const tokenName = getPropertyName(property)\n if (tokenName && !seen.has(tokenName)) {\n seen.add(tokenName)\n tokens.push(tokenName)\n }\n }\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n return tokens\n}\n\nfunction extractSearchEntities(searchFilePath: string | null, warnings: string[]): string[] {\n if (!searchFilePath) return []\n const sourceFile = readSourceFile(searchFilePath)\n if (!sourceFile) return []\n\n const searchConfig = findObjectLiteralDeclaration(sourceFile, 'searchConfig')\n if (!searchConfig) {\n warnings.push(`[module-facts] search.ts present but no searchConfig object literal: ${searchFilePath}`)\n return []\n }\n const entitiesInitializer = getObjectPropertyInitializer(searchConfig, 'entities')\n const entitiesArray = entitiesInitializer ? unwrapArrayLiteral(entitiesInitializer) : null\n if (!entitiesArray) {\n warnings.push(`[module-facts] searchConfig.entities is not an array literal: ${searchFilePath}`)\n return []\n }\n\n const entityIds: string[] = []\n const seen = new Set<string>()\n for (const element of entitiesArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const entityId = readStringPropertyInitializer(element, 'entityId')\n if (entityId && !seen.has(entityId)) {\n seen.add(entityId)\n entityIds.push(entityId)\n }\n }\n return entityIds\n}\n\nfunction extractNotifications(notificationsFilePath: string | null, warnings: string[]): string[] {\n if (!notificationsFilePath) return []\n const sourceFile = readSourceFile(notificationsFilePath)\n if (!sourceFile) return []\n\n const notificationsArray =\n findArrayLiteralDeclaration(sourceFile, 'notificationTypes') ??\n findArrayLiteralDeclaration(sourceFile, 'notifications')\n if (!notificationsArray) {\n warnings.push(`[module-facts] notifications.ts present but no notificationTypes array literal: ${notificationsFilePath}`)\n return []\n }\n\n const notificationIds: string[] = []\n const seen = new Set<string>()\n for (const element of notificationsArray.elements) {\n if (!ts.isObjectLiteralExpression(element)) continue\n const notificationId = readStringPropertyInitializer(element, 'type')\n if (notificationId && !seen.has(notificationId)) {\n seen.add(notificationId)\n notificationIds.push(notificationId)\n }\n }\n return notificationIds\n}\n\nfunction extractCli(cliFilePath: string | null, warnings: string[]): string[] {\n if (!cliFilePath) return []\n const sourceFile = readSourceFile(cliFilePath)\n if (!sourceFile) return []\n\n const defaultExport = findDefaultExportExpression(sourceFile)\n if (!defaultExport) {\n warnings.push(`[module-facts] cli.ts present but no default export: ${cliFilePath}`)\n return []\n }\n\n const initializers = buildVariableInitializerMap(sourceFile)\n const collectCommand = (objectLiteral: ts.ObjectLiteralExpression): string | undefined =>\n readStringPropertyInitializer(objectLiteral, 'command')\n\n const commands: string[] = []\n const seen = new Set<string>()\n const pushCommand = (command: string | undefined): void => {\n if (command && !seen.has(command)) {\n seen.add(command)\n commands.push(command)\n }\n }\n\n const arrayLiteral = resolveToArrayLiteral(defaultExport, initializers)\n if (arrayLiteral) {\n for (const element of arrayLiteral.elements) {\n const objectLiteral = resolveToObjectLiteral(element, initializers)\n if (objectLiteral) pushCommand(collectCommand(objectLiteral))\n }\n return commands\n }\n\n const singleObject = resolveToObjectLiteral(defaultExport, initializers)\n if (singleObject) {\n pushCommand(collectCommand(singleObject))\n return commands\n }\n\n warnings.push(`[module-facts] cli.ts default export is neither an array nor an object literal: ${cliFilePath}`)\n return commands\n}\n\nfunction listSourceFilesRecursive(directory: string): string[] {\n const files: string[] = []\n for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {\n if (entry.name === '__tests__' || entry.name === 'node_modules') continue\n const fullPath = path.join(directory, entry.name)\n if (entry.isDirectory()) {\n files.push(...listSourceFilesRecursive(fullPath))\n } else if (/\\.tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {\n files.push(fullPath)\n }\n }\n return files\n}\n\nfunction extractTableIds(backendDir: string): string[] {\n if (!fs.existsSync(backendDir)) return []\n\n const tableIds: string[] = []\n const seen = new Set<string>()\n for (const filePath of listSourceFilesRecursive(backendDir)) {\n const sourceFile = readSourceFile(filePath)\n if (!sourceFile) continue\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAssignment(node)) {\n const propertyName = getPropertyName(node)\n if (\n (propertyName === 'tableId' || propertyName === 'extensionTableId') &&\n ts.isStringLiteralLike(node.initializer)\n ) {\n const value = node.initializer.text\n if (value && !seen.has(value)) {\n seen.add(value)\n tableIds.push(value)\n }\n }\n }\n node.forEachChild(visit)\n }\n sourceFile.forEachChild(visit)\n }\n tableIds.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))\n return tableIds\n}\n\nfunction extractHostEntityIds(entities: ModuleEntityFact[]): string[] {\n return entities.filter((entity) => entity.id.endsWith('_entity')).map((entity) => entity.id)\n}\n\nfunction extractModuleMeta(indexFilePath: string | null): { title: string | null; description: string | null } {\n if (!indexFilePath) return { title: null, description: null }\n const sourceFile = readSourceFile(indexFilePath)\n if (!sourceFile) return { title: null, description: null }\n const metadata = findObjectLiteralDeclaration(sourceFile, 'metadata')\n if (!metadata) return { title: null, description: null }\n return {\n title: readStringPropertyInitializer(metadata, 'title') ?? null,\n description: readStringPropertyInitializer(metadata, 'description') ?? null,\n }\n}\n\nexport function extractModuleFacts(options: ExtractModuleFactsOptions): ModuleFacts {\n const { moduleId, coreVersion = null } = options\n const moduleRoot = options.moduleRoot\n ?? (options.coreSrcRoot ? path.join(options.coreSrcRoot, moduleId) : null)\n if (!moduleRoot) {\n throw new Error(`[internal] extractModuleFacts requires moduleRoot or coreSrcRoot for module \"${moduleId}\"`)\n }\n\n const entitiesFilePath =\n resolveConventionFile(path.join(moduleRoot, 'data'), 'entities') ??\n resolveConventionFile(path.join(moduleRoot, 'db'), 'entities') ??\n resolveConventionFile(path.join(moduleRoot, 'data'), 'schema')\n const ceFilePath = resolveConventionFile(moduleRoot, 'ce')\n const eventsFilePath = resolveConventionFile(moduleRoot, 'events')\n const aclFilePath = resolveConventionFile(moduleRoot, 'acl')\n const diFilePath = resolveConventionFile(moduleRoot, 'di')\n const searchFilePath = resolveConventionFile(moduleRoot, 'search')\n const notificationsFilePath = resolveConventionFile(moduleRoot, 'notifications')\n const cliFilePath = resolveConventionFile(moduleRoot, 'cli')\n const indexFilePath = resolveConventionFile(moduleRoot, 'index')\n const backendDir = path.join(moduleRoot, 'backend')\n\n const warnings: string[] = []\n const { title, description } = extractModuleMeta(indexFilePath)\n const customFieldEntityIds = collectCustomFieldEntityIds(ceFilePath)\n const entities = extractEntities(moduleId, entitiesFilePath, customFieldEntityIds)\n const events = extractEvents(eventsFilePath)\n const aclFeatures = extractAclFeatures(aclFilePath)\n\n const { source: registrySource, description: registryDescription } = resolveRegistrySource(options)\n const apiRoutes = extractApiRoutes(moduleId, registrySource, registryDescription, warnings)\n const diTokens = extractDiTokens(diFilePath)\n const searchEntities = extractSearchEntities(searchFilePath, warnings)\n const notifications = extractNotifications(notificationsFilePath, warnings)\n const cli = extractCli(cliFilePath, warnings)\n const hostTokens: ModuleHostTokens = {\n entityIds: extractHostEntityIds(entities),\n tableIds: extractTableIds(backendDir),\n }\n\n return {\n module: moduleId,\n title,\n description,\n coreVersion,\n entities,\n events,\n aclFeatures,\n apiRoutes,\n diTokens,\n searchEntities,\n hostTokens,\n notifications,\n cli,\n warnings,\n }\n}\n\nexport interface ModuleFactsJsonEvent {\n id: string\n category: string | null\n entity: string | null\n}\n\nexport interface ModuleFactsJsonEntry {\n title: string | null\n description: string | null\n coreVersion: string | null\n entities: ModuleEntityFact[]\n events: ModuleFactsJsonEvent[]\n aclFeatures: string[]\n apiRoutes: ModuleApiRouteFact[]\n diTokens: string[]\n searchEntities: string[]\n hostTokens: ModuleHostTokens\n notifications: string[]\n cli: string[]\n}\n\nconst EMPTY_SECTION_MARKER = '_none_'\n\nfunction renderVersionStamp(coreVersion: string | null): string {\n const version = coreVersion && coreVersion.length > 0 ? coreVersion : '<unknown>'\n return `<!-- generated from @open-mercato/core ${version} \u2014 R1 staleness stamp -->`\n}\n\nfunction renderEntitiesSection(entities: ModuleEntityFact[]): string {\n if (entities.length === 0) return `## Entities\\n\\n${EMPTY_SECTION_MARKER}`\n const header = '| Entity ID | Class | Table | Editable | CustomFields |'\n const divider = '|---|---|---|---|---|'\n const rows = entities.map(\n (entity) =>\n `| ${entity.id} | ${entity.class} | ${entity.table} | ${entity.editable ? 'yes' : 'no'} | ${entity.customFields ? 'yes' : 'no'} |`,\n )\n return ['## Entities', '', header, divider, ...rows].join('\\n')\n}\n\nfunction renderEventsSection(events: ModuleEventFact[]): string {\n const heading = `## Events (${events.length})`\n if (events.length === 0) return `${heading}\\n\\n${EMPTY_SECTION_MARKER}`\n const header = '| ID | Category | Entity |'\n const divider = '|---|---|---|'\n const rows = events.map((event) => `| ${event.id} | ${event.category ?? '\u2014'} | ${event.entity ?? '\u2014'} |`)\n return [heading, '', header, divider, ...rows].join('\\n')\n}\n\nfunction renderInlineListSection(heading: string, values: string[]): string {\n if (values.length === 0) return `${heading}\\n\\n${EMPTY_SECTION_MARKER}`\n return `${heading}\\n\\n${values.join(' \u00B7 ')}`\n}\n\nfunction describeAuthRule(rule: ApiRouteAuthRule | undefined): string {\n if (!rule) return 'public'\n if (rule.requireFeatures && rule.requireFeatures.length > 0) return rule.requireFeatures.join(', ')\n if (rule.requireRoles && rule.requireRoles.length > 0) return rule.requireRoles.join(', ')\n if (rule.requireAuth) return 'auth'\n return 'public'\n}\n\nfunction renderApiRouteAuthCell(route: ModuleApiRouteFact): string {\n if (route.methods.length === 0) return '\u2014'\n const groups: Array<{ label: string; methods: string[] }> = []\n for (const method of route.methods) {\n const label = describeAuthRule(route.auth[method])\n const existing = groups.find((group) => group.label === label)\n if (existing) existing.methods.push(method)\n else groups.push({ label, methods: [method] })\n }\n return groups.map((group) => `${group.methods.join('/')} \u2192 ${group.label}`).join(' \u00B7 ')\n}\n\nfunction renderApiRoutesSection(routes: ModuleApiRouteFact[]): string {\n if (routes.length === 0) return `## API routes\\n\\n${EMPTY_SECTION_MARKER}`\n const header = '| Path | Methods | Auth (per-method requireFeatures) |'\n const divider = '|---|---|---|'\n const rows = routes.map(\n (route) => `| ${route.path} | ${route.methods.join(' ')} | ${renderApiRouteAuthCell(route)} |`,\n )\n return ['## API routes', '', header, divider, ...rows].join('\\n')\n}\n\nfunction renderHostTokensSection(hostTokens: ModuleHostTokens): string {\n const entityIdsLine = hostTokens.entityIds.length > 0 ? hostTokens.entityIds.join(' \u00B7 ') : EMPTY_SECTION_MARKER\n const tableIdsLine = hostTokens.tableIds.length > 0 ? hostTokens.tableIds.join(' \u00B7 ') : EMPTY_SECTION_MARKER\n return ['## Host extension points', '', `- Entity IDs: ${entityIdsLine}`, `- Table IDs: ${tableIdsLine}`].join('\\n')\n}\n\nexport function renderModuleFactsMarkdown(facts: ModuleFacts): string {\n const sections = [\n `# ${facts.module} \u2014 module facts (generated, do not edit)`,\n renderVersionStamp(facts.coreVersion),\n '',\n renderEntitiesSection(facts.entities),\n '',\n renderEventsSection(facts.events),\n '',\n renderInlineListSection(`## ACL features (${facts.aclFeatures.length})`, facts.aclFeatures),\n '',\n renderApiRoutesSection(facts.apiRoutes),\n '',\n renderInlineListSection('## DI service tokens', facts.diTokens),\n '',\n renderInlineListSection('## Search entities', facts.searchEntities),\n '',\n renderHostTokensSection(facts.hostTokens),\n '',\n renderInlineListSection('## Notifications', facts.notifications),\n '',\n renderInlineListSection('## CLI', facts.cli),\n '',\n ]\n return sections.join('\\n')\n}\n\nexport function toModuleFactsJsonEntry(facts: ModuleFacts): ModuleFactsJsonEntry {\n return {\n title: facts.title,\n description: facts.description,\n coreVersion: facts.coreVersion,\n entities: facts.entities,\n events: facts.events.map((event) => ({ id: event.id, category: event.category, entity: event.entity })),\n aclFeatures: facts.aclFeatures,\n apiRoutes: facts.apiRoutes,\n diTokens: facts.diTokens,\n searchEntities: facts.searchEntities,\n hostTokens: facts.hostTokens,\n notifications: facts.notifications,\n cli: facts.cli,\n }\n}\n\nexport function buildModuleFactsJsonObject(\n factsByModule: Record<string, ModuleFacts>,\n): Record<string, ModuleFactsJsonEntry> {\n const result: Record<string, ModuleFactsJsonEntry> = {}\n for (const moduleId of Object.keys(factsByModule).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n result[moduleId] = toModuleFactsJsonEntry(factsByModule[moduleId])\n }\n return result\n}\n\nexport function renderModuleFactsJson(factsByModule: Record<string, ModuleFacts>): string {\n return `${JSON.stringify(buildModuleFactsJsonObject(factsByModule), null, 2)}\\n`\n}\n\nexport interface ExtractAllModuleFactsOptions {\n /**\n * Discovered module sources (auto-discovery path). When provided, each entry's\n * explicit `moduleRoot` is used and `coreSrcRoot`/`moduleIds` are ignored.\n */\n sources?: readonly ModuleFactSource[]\n /** Legacy shared-root path. Used only when `sources` is not provided. */\n coreSrcRoot?: string\n registryPath?: string | null\n registrySource?: string | null\n coreVersion?: string | null\n /** @deprecated Legacy explicit module-id list; only consulted when `sources` is absent. */\n moduleIds?: readonly string[]\n}\n\nexport interface ExtractAllModuleFactsResult {\n factsByModule: Record<string, ModuleFacts>\n markdownByModule: Record<string, string>\n warnings: string[]\n}\n\nexport function extractAllModuleFacts(options: ExtractAllModuleFactsOptions): ExtractAllModuleFactsResult {\n const sources: ModuleFactSource[] = options.sources\n ? [...options.sources]\n : (options.coreSrcRoot\n ? (options.moduleIds ?? []).map((moduleId) => ({\n moduleId,\n moduleRoot: path.join(options.coreSrcRoot as string, moduleId),\n }))\n : [])\n\n const factsByModule: Record<string, ModuleFacts> = {}\n const markdownByModule: Record<string, string> = {}\n const warnings: string[] = []\n for (const source of sources) {\n const facts = extractModuleFacts({\n moduleId: source.moduleId,\n moduleRoot: source.moduleRoot,\n coreVersion: options.coreVersion ?? null,\n registryPath: options.registryPath ?? null,\n registrySource: options.registrySource ?? null,\n })\n factsByModule[source.moduleId] = facts\n markdownByModule[source.moduleId] = renderModuleFactsMarkdown(facts)\n warnings.push(...facts.warnings)\n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,CAAC;AAAA,EACnE;AACA,SAAO;AACT;AAEO,SAAS,sBAAsB,eAAoD;AACxF,SAAO,GAAG,KAAK,UAAU,2BAA2B,aAAa,GAAG,MAAM,CAAC,CAAC;AAAA;AAC9E;AAuBO,SAAS,sBAAsB,SAAoE;AACxG,QAAM,UAA8B,QAAQ,UACxC,CAAC,GAAG,QAAQ,OAAO,IAClB,QAAQ,eACJ,QAAQ,aAAa,CAAC,GAAG,IAAI,CAAC,cAAc;AAAA,IAC3C;AAAA,IACA,YAAY,KAAK,KAAK,QAAQ,aAAuB,QAAQ;AAAA,EAC/D,EAAE,IACF,CAAC;AAET,QAAM,gBAA6C,CAAC;AACpD,QAAM,mBAA2C,CAAC;AAClD,QAAM,WAAqB,CAAC;AAC5B,aAAW,UAAU,SAAS;AAC5B,UAAM,QAAQ,mBAAmB;AAAA,MAC/B,UAAU,OAAO;AAAA,MACjB,YAAY,OAAO;AAAA,MACnB,aAAa,QAAQ,eAAe;AAAA,MACpC,cAAc,QAAQ,gBAAgB;AAAA,MACtC,gBAAgB,QAAQ,kBAAkB;AAAA,IAC5C,CAAC;AACD,kBAAc,OAAO,QAAQ,IAAI;AACjC,qBAAiB,OAAO,QAAQ,IAAI,0BAA0B,KAAK;AACnE,aAAS,KAAK,GAAG,MAAM,QAAQ;AAAA,EACjC;AACA,SAAO,EAAE,eAAe,kBAAkB,SAAS;AACrD;",
6
6
  "names": []
7
7
  }
package/dist/mercato.js CHANGED
@@ -34,6 +34,7 @@ import { resolveNextBuildIdCandidate } from "./lib/next-build-id.js";
34
34
  import { acquireServerStartLock } from "./lib/server-start-lock.js";
35
35
  import { assertSingleInstanceStrategies } from "./lib/single-instance-strategy-guard.js";
36
36
  import { createDevEnvReloader, watchDevEnvFiles } from "./lib/dev-env-reload.js";
37
+ import { quotePostgresIdentifier } from "./lib/db/identifiers.js";
37
38
  const lazyIntegration = () => import("./lib/testing/integration.js");
38
39
  import path from "node:path";
39
40
  import fs from "node:fs";
@@ -688,7 +689,7 @@ async function run(argv = process.argv) {
688
689
  await client.query("BEGIN");
689
690
  try {
690
691
  for (const t of dropTargets) {
691
- await client.query(`DROP TABLE IF EXISTS "${t}" CASCADE`);
692
+ await client.query(`DROP TABLE IF EXISTS ${quotePostgresIdentifier(t)} CASCADE`);
692
693
  dropped += 1;
693
694
  }
694
695
  await client.query("COMMIT");