@happyvertical/smrt-core 0.42.6 → 0.43.0

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 (134) hide show
  1. package/AGENTS.md +39 -43
  2. package/agents/collection-reads.md +40 -0
  3. package/agents/data-query.md +21 -0
  4. package/agents/latest-related.md +35 -0
  5. package/agents/memory.md +16 -0
  6. package/agents/schema-paths.md +29 -15
  7. package/dist/browser.js +2 -2
  8. package/dist/cascade.d.ts +7 -6
  9. package/dist/cascade.d.ts.map +1 -1
  10. package/dist/cascade.js +19 -21
  11. package/dist/cascade.js.map +1 -1
  12. package/dist/class.d.ts +17 -0
  13. package/dist/class.d.ts.map +1 -1
  14. package/dist/class.js +30 -0
  15. package/dist/class.js.map +1 -1
  16. package/dist/collection.d.ts +164 -3
  17. package/dist/collection.d.ts.map +1 -1
  18. package/dist/collection.js +345 -10
  19. package/dist/collection.js.map +1 -1
  20. package/dist/decorators/index.d.ts +33 -15
  21. package/dist/decorators/index.d.ts.map +1 -1
  22. package/dist/decorators/index.js +16 -11
  23. package/dist/decorators/index.js.map +1 -1
  24. package/dist/generators/rest.d.ts.map +1 -1
  25. package/dist/generators/rest.js +10 -2
  26. package/dist/generators/rest.js.map +1 -1
  27. package/dist/generators/tool-schema.d.ts +14 -0
  28. package/dist/generators/tool-schema.d.ts.map +1 -1
  29. package/dist/generators/tool-schema.js +13 -1
  30. package/dist/generators/tool-schema.js.map +1 -1
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +3 -2
  34. package/dist/interceptors.d.ts +2 -1
  35. package/dist/interceptors.d.ts.map +1 -1
  36. package/dist/interceptors.js.map +1 -1
  37. package/dist/manifest/static-manifest.d.ts.map +1 -1
  38. package/dist/manifest/static-manifest.js +53 -1
  39. package/dist/manifest/static-manifest.js.map +1 -1
  40. package/dist/manifest/store.js +1 -1
  41. package/dist/manifest/store.js.map +1 -1
  42. package/dist/manifest.json +62 -1
  43. package/dist/migrations/differ.d.ts +2 -0
  44. package/dist/migrations/differ.d.ts.map +1 -1
  45. package/dist/migrations/differ.js +75 -0
  46. package/dist/migrations/differ.js.map +1 -1
  47. package/dist/migrations/generator.d.ts.map +1 -1
  48. package/dist/migrations/generator.js +19 -2
  49. package/dist/migrations/generator.js.map +1 -1
  50. package/dist/migrations/orchestrate.d.ts.map +1 -1
  51. package/dist/migrations/orchestrate.js +4 -1
  52. package/dist/migrations/orchestrate.js.map +1 -1
  53. package/dist/object.d.ts +4 -4
  54. package/dist/object.js +4 -4
  55. package/dist/object.js.map +1 -1
  56. package/dist/prebuild/index.d.ts.map +1 -1
  57. package/dist/prebuild/index.js +9 -0
  58. package/dist/prebuild/index.js.map +1 -1
  59. package/dist/registry/schema-builder.d.ts +6 -0
  60. package/dist/registry/schema-builder.d.ts.map +1 -1
  61. package/dist/registry/schema-builder.js +78 -8
  62. package/dist/registry/schema-builder.js.map +1 -1
  63. package/dist/registry.d.ts +5 -7
  64. package/dist/registry.d.ts.map +1 -1
  65. package/dist/registry.js +6 -8
  66. package/dist/registry.js.map +1 -1
  67. package/dist/runtime/types.d.ts +2 -2
  68. package/dist/runtime/types.d.ts.map +1 -1
  69. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  70. package/dist/scanner/manifest-generator.js +62 -18
  71. package/dist/scanner/manifest-generator.js.map +1 -1
  72. package/dist/scanner/types.d.ts +5 -1
  73. package/dist/scanner/types.d.ts.map +1 -1
  74. package/dist/scanner/types.js.map +1 -1
  75. package/dist/schema/ddl/base-strategy.d.ts.map +1 -1
  76. package/dist/schema/ddl/base-strategy.js +2 -0
  77. package/dist/schema/ddl/base-strategy.js.map +1 -1
  78. package/dist/schema/ddl/duckdb-strategy.d.ts +1 -0
  79. package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
  80. package/dist/schema/ddl/duckdb-strategy.js +17 -1
  81. package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
  82. package/dist/schema/ddl/postgres-strategy.js +1 -1
  83. package/dist/schema/foreign-key-ddl.d.ts +9 -0
  84. package/dist/schema/foreign-key-ddl.d.ts.map +1 -0
  85. package/dist/schema/foreign-key-ddl.js +53 -0
  86. package/dist/schema/foreign-key-ddl.js.map +1 -0
  87. package/dist/schema/foreign-key-planner.d.ts +18 -0
  88. package/dist/schema/foreign-key-planner.d.ts.map +1 -0
  89. package/dist/schema/foreign-key-planner.js +109 -0
  90. package/dist/schema/foreign-key-planner.js.map +1 -0
  91. package/dist/schema/foreign-key-policy.d.ts +21 -0
  92. package/dist/schema/foreign-key-policy.d.ts.map +1 -0
  93. package/dist/schema/foreign-key-policy.js +41 -0
  94. package/dist/schema/foreign-key-policy.js.map +1 -0
  95. package/dist/schema/generator.d.ts +3 -0
  96. package/dist/schema/generator.d.ts.map +1 -1
  97. package/dist/schema/generator.js +54 -10
  98. package/dist/schema/generator.js.map +1 -1
  99. package/dist/schema/index.d.ts +3 -0
  100. package/dist/schema/index.d.ts.map +1 -1
  101. package/dist/schema/index.js +4 -1
  102. package/dist/schema/manifest-schema.d.ts.map +1 -1
  103. package/dist/schema/manifest-schema.js +20 -3
  104. package/dist/schema/manifest-schema.js.map +1 -1
  105. package/dist/schema/schema-aggregator.d.ts +7 -1
  106. package/dist/schema/schema-aggregator.d.ts.map +1 -1
  107. package/dist/schema/schema-aggregator.js +54 -9
  108. package/dist/schema/schema-aggregator.js.map +1 -1
  109. package/dist/schema/schema-manager.d.ts +1 -6
  110. package/dist/schema/schema-manager.d.ts.map +1 -1
  111. package/dist/schema/schema-manager.js +26 -30
  112. package/dist/schema/schema-manager.js.map +1 -1
  113. package/dist/schema/types.d.ts +8 -5
  114. package/dist/schema/types.d.ts.map +1 -1
  115. package/dist/schema/utils.d.ts.map +1 -1
  116. package/dist/schema/utils.js +14 -1
  117. package/dist/schema/utils.js.map +1 -1
  118. package/dist/schema.js +4 -1
  119. package/dist/smrt-knowledge.json +63 -8
  120. package/dist/testing/database.d.ts +11 -1
  121. package/dist/testing/database.d.ts.map +1 -1
  122. package/dist/testing/database.js +80 -9
  123. package/dist/testing/database.js.map +1 -1
  124. package/dist/vite-plugin/index.d.ts.map +1 -1
  125. package/dist/vite-plugin/index.js +12 -3
  126. package/dist/vite-plugin/index.js.map +1 -1
  127. package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
  128. package/dist/vite-plugin/sveltekit-generator.js +24 -3
  129. package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
  130. package/dist/vite-plugin/web-collections.d.ts +3 -1
  131. package/dist/vite-plugin/web-collections.d.ts.map +1 -1
  132. package/dist/vite-plugin/web-collections.js +24 -4
  133. package/dist/vite-plugin/web-collections.js.map +1 -1
  134. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/prebuild/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAQ5D,MAAM,WAAW,eAAe;IAC9B,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,GAAG,mBAAmB,CAAC;IACvC,2CAA2C;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,0CAA0C;IAC1C,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,sCAAsC;IACtC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,qDAAqD;IACrD,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,IAAI,CAAC,CAkCf;AAiYD;;GAEG;AACH,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,MAAM,EAAE,GACb,OAAO,CAAC,IAAI,CAAC,CAkBf"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/prebuild/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAQ5D,MAAM,WAAW,eAAe;IAC9B,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,GAAG,mBAAmB,CAAC;IACvC,2CAA2C;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,0CAA0C;IAC1C,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,sCAAsC;IACtC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,qDAAqD;IACrD,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,IAAI,CAAC,CAkCf;AA0YD;;GAEG;AACH,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,MAAM,EAAE,GACb,OAAO,CAAC,IAAI,CAAC,CAkBf"}
@@ -254,6 +254,14 @@ declare module '@smrt/web' {
254
254
  relatedCollection: string;
255
255
  }
256
256
 
257
+ export interface WebToolRouteDescriptor {
258
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
259
+ scope: 'item' | 'collection';
260
+ path: string[];
261
+ parameterAliases?: Record<string, string>;
262
+ optionsBag?: boolean;
263
+ }
264
+
257
265
  /** A WebMCP/MCP tool descriptor for one collection action (#1812). */
258
266
  export interface WebToolDescriptor {
259
267
  action: string;
@@ -261,6 +269,7 @@ declare module '@smrt/web' {
261
269
  description: string;
262
270
  inputSchema: Record<string, unknown>;
263
271
  readOnly: boolean;
272
+ route?: WebToolRouteDescriptor;
264
273
  }
265
274
 
266
275
  export interface SmrtWebCollectionDefinition<TData = Record<string, unknown>> {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/prebuild/index.ts"],"sourcesContent":["/**\n * Pre-build utilities for generating TypeScript declarations\n * Solves virtual module resolution by creating physical .d.ts files\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { SmartObjectManifest } from '../scanner/types';\nimport {\n renderApiClientCrudType,\n renderApiClientCustomMethodParameters,\n selectApiClientEntries,\n} from '../vite-plugin/api-client-entries.js';\nimport { selectWebCollectionEntries } from '../vite-plugin/web-collections.js';\n\nexport interface PrebuildOptions {\n /** Path to manifest file or manifest object */\n manifest: string | SmartObjectManifest;\n /** Output directory for generated types */\n outDir: string;\n /** Include virtual module declarations */\n includeVirtualModules?: boolean;\n /** Include object type definitions */\n includeObjectTypes?: boolean;\n /** Project root path for resolving relative paths */\n projectRoot?: string;\n}\n\n/**\n * Generate TypeScript declaration files from SMRT manifest\n */\nexport async function generateDeclarations(\n options: PrebuildOptions,\n): Promise<void> {\n const {\n manifest: manifestInput,\n outDir,\n includeVirtualModules = true,\n includeObjectTypes = true,\n projectRoot = process.cwd(),\n } = options;\n\n // Load manifest\n const manifest: SmartObjectManifest =\n typeof manifestInput === 'string'\n ? JSON.parse(fs.readFileSync(manifestInput, 'utf-8'))\n : manifestInput;\n\n // Ensure output directory exists\n const fullOutDir = path.isAbsolute(outDir)\n ? outDir\n : path.join(projectRoot, outDir);\n fs.mkdirSync(fullOutDir, { recursive: true });\n\n console.log(`[smrt:prebuild] Generating declarations to ${fullOutDir}`);\n\n if (includeObjectTypes) {\n await generateObjectTypeDeclarations(manifest, fullOutDir);\n }\n\n if (includeVirtualModules) {\n await generateVirtualModuleDeclarations(manifest, fullOutDir);\n }\n\n console.log(\n `[smrt:prebuild] Generated declarations for ${Object.keys(manifest.objects).length} SMRT objects`,\n );\n}\n\n/**\n * Generate TypeScript interfaces for SMRT objects\n */\nasync function generateObjectTypeDeclarations(\n manifest: SmartObjectManifest,\n outDir: string,\n): Promise<void> {\n const interfaces: string[] = [];\n\n // Generate interfaces for each discovered SMRT object\n for (const [_objectName, objectMeta] of Object.entries(manifest.objects)) {\n const fields = objectMeta.fields || {};\n const propertyLines: string[] = [];\n\n // Add standard SmrtObject properties\n propertyLines.push(' id?: string;');\n propertyLines.push(' created_at?: string;');\n propertyLines.push(' updated_at?: string;');\n\n // Add object-specific properties\n for (const [fieldName, fieldDef] of Object.entries(fields)) {\n const type = mapFieldTypeToTypeScript(fieldDef.type);\n const optional = !fieldDef.required ? '?' : '';\n propertyLines.push(` ${fieldName}${optional}: ${type};`);\n }\n\n const interfaceDef = `export interface ${objectMeta.className}Data {\n${propertyLines.join('\\n')}\n}`;\n interfaces.push(interfaceDef);\n }\n\n // Write object types file\n const objectTypesContent = `/**\n * Auto-generated TypeScript interfaces for SMRT objects\n * Generated at build time from @smrt() decorated classes\n *\n * DO NOT EDIT THIS FILE MANUALLY\n */\n\n${interfaces.join('\\n\\n')}\n`;\n\n fs.writeFileSync(path.join(outDir, 'smrt-objects.d.ts'), objectTypesContent);\n}\n\n/**\n * Generate virtual module declarations\n */\nasync function generateVirtualModuleDeclarations(\n manifest: SmartObjectManifest,\n outDir: string,\n): Promise<void> {\n // Generate manifest module declaration\n const manifestDeclaration = `/**\n * Auto-generated manifest module declaration\n */\ndeclare module '@smrt/manifest' {\n export interface SmrtObjectField {\n type: string;\n required?: boolean;\n default?: any;\n }\n\n export interface SmrtObjectMethod {\n name: string;\n parameters: Array<{\n name: string;\n type: string;\n optional?: boolean;\n default?: any;\n }>;\n returnType: string;\n async: boolean;\n isStatic: boolean;\n isPublic: boolean;\n }\n\n export interface SmrtObjectDefinition {\n name: string;\n className: string;\n collection: string;\n filePath: string;\n fields: Record<string, SmrtObjectField>;\n methods: Record<string, SmrtObjectMethod>;\n decoratorConfig: any;\n extends?: string;\n }\n\n export interface SmrtManifest {\n version: string;\n timestamp: number;\n objects: Record<string, SmrtObjectDefinition>;\n }\n\n export const manifest: SmrtManifest;\n export default manifest;\n}`;\n\n // Generate client module declaration\n const apiClientInterface = selectApiClientEntries(manifest)\n .map(({ clientKey, dataInterfaceName, crudMethods, customMethods }) => {\n const overriddenMethods = customMethods.map(({ name }) => name);\n const crudType = renderApiClientCrudType(\n dataInterfaceName,\n crudMethods,\n overriddenMethods,\n );\n const customSignatures = customMethods\n .map(\n (method) =>\n ` ${method.name}(${renderApiClientCustomMethodParameters(\n method,\n mapFieldTypeToTypeScript,\n )}): Promise<any>;`,\n )\n .join('\\n');\n\n if (customSignatures) {\n const intersection = crudType ? `${crudType} & ` : '';\n return ` ${JSON.stringify(clientKey)}: ${intersection}{\\n${customSignatures}\\n };`;\n }\n\n return ` ${JSON.stringify(clientKey)}: ${crudType ?? 'Record<string, never>'};`;\n })\n .join('\\n');\n\n // Wire-shape policy (#1797): the server returns BARE JSON — a bare array for\n // list/search, a bare object for get/create/update — with snake_case field\n // names (created_at, updated_at). These physical declarations share client\n // entry selection and method-signature rendering with the Vite declaration.\n // Fetchers reject on non-2xx with a SmrtClientError (#1796).\n const clientDeclaration = `/**\n * Auto-generated API client module declaration\n */\ndeclare module '@smrt/client' {\n /** Structured custom-action failure nested under an API error body's \\`error\\` key. */\n export interface SmrtClientFailure {\n ok: false;\n code: string;\n message: string;\n status?: number;\n }\n\n /** Shape of a JSON error body carried by a rejected request (SmrtClientError.body). */\n export interface ApiError {\n error?: string | SmrtClientFailure;\n message?: string;\n }\n\n /** Typed error thrown by every fetcher on a non-2xx response (#1796). */\n export interface SmrtClientError extends Error {\n name: 'SmrtClientError';\n status: number;\n /** Machine-readable code from a structured custom-action failure, when present. */\n code?: string;\n body?: ApiError | string;\n }\n\n export interface CrudOperations<T = any> {\n list(params?: Record<string, any>): Promise<T[]>;\n get(id: string): Promise<T>;\n create(data: Partial<T>): Promise<T>;\n update(id: string, data: Partial<T>): Promise<T>;\n delete(id: string): Promise<boolean>;\n search(query: string): Promise<T[]>;\n }\n\n export interface ApiClient {\n${apiClientInterface}\n }\n\n export function createClient(basePath?: string): ApiClient;\n export default createClient;\n}`;\n\n // Generate routes module declaration\n const routesDeclaration = `/**\n * Auto-generated routes module declaration\n */\ndeclare module '@smrt/routes' {\n export interface RouteApp {\n get(path: string, handler: (req: any, res: any) => void): void;\n post(path: string, handler: (req: any, res: any) => void): void;\n put(path: string, handler: (req: any, res: any) => void): void;\n delete(path: string, handler: (req: any, res: any) => void): void;\n }\n\n export function setupRoutes(app: RouteApp): void;\n export default setupRoutes;\n}`;\n\n // Generate MCP module declaration\n const mcpDeclaration = `/**\n * Auto-generated MCP module declaration\n */\ndeclare module '@smrt/mcp' {\n export interface McpTool {\n name: string;\n description: string;\n inputSchema: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n }\n\n export const tools: McpTool[];\n export function createMCPServer(): {\n name: string;\n version: string;\n tools: McpTool[]\n };\n export default createMCPServer;\n}`;\n\n // Generate types module declaration with object imports\n const objectImports = Object.values(manifest.objects)\n .map(\n (obj) =>\n ` export type ${obj.className}Data = import('./smrt-objects').${obj.className}Data;`,\n )\n .join('\\n');\n\n const typesDeclaration = `/**\n * Auto-generated types module declaration\n */\ndeclare module '@smrt/types' {\n${objectImports}\n\n export interface Request {\n params: Record<string, string>;\n query: Record<string, any>;\n json(): Promise<any>;\n }\n\n export interface Response {\n json(data: any, init?: { status?: number }): Response;\n status(code: number): Response;\n }\n}`;\n\n // Generate web collection-definition module declaration (#1761). Selection\n // shares selectWebCollectionEntries with the vite-plugin runtime module and\n // its virt-web d.ts, so this `tsc`-only consumer declaration cannot drift\n // from the emitted values.\n const webCollectionEntries = selectWebCollectionEntries(manifest)\n .map(\n ({ collection, obj }) =>\n ` ${JSON.stringify(collection)}: SmrtWebCollectionDefinition<import('./smrt-objects').${obj.className}Data>;`,\n )\n .join('\\n');\n\n const webDeclaration = `/**\n * Auto-generated web collection-definition module declaration (#1761)\n */\ndeclare module '@smrt/web' {\n export type SmrtWebFieldType =\n | 'text'\n | 'decimal'\n | 'boolean'\n | 'integer'\n | 'datetime'\n | 'json'\n | 'foreignKey'\n | 'crossPackageRef';\n\n /** Static \\`@field({ ui })\\` hints (#2046) — the field-policy rail seed. */\n export interface SmrtWebFieldUIHints {\n basic?: boolean;\n group?: string;\n order?: number;\n locked?: boolean;\n }\n\n export interface SmrtWebFieldDefinition {\n type: SmrtWebFieldType;\n required?: boolean;\n nullable?: boolean;\n default?: unknown;\n /** Developer-authored \\`@field({ description })\\` (#2046) — end-user help seed. */\n description?: string;\n /** Static \\`@field({ ui })\\` hints (#2046). */\n ui?: SmrtWebFieldUIHints;\n }\n\n export type SmrtWebRelationshipKind =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\n /**\n * A manifest-derived edge to a sibling REST collection. Mutating this\n * collection invalidates the caches of the collections named by these edges\n * (#1761 relationship-derived invalidation).\n */\n export interface SmrtWebRelationship {\n field: string;\n kind: SmrtWebRelationshipKind;\n relatedCollection: string;\n }\n\n /** A WebMCP/MCP tool descriptor for one collection action (#1812). */\n export interface WebToolDescriptor {\n action: string;\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n readOnly: boolean;\n }\n\n export interface SmrtWebCollectionDefinition<TData = Record<string, unknown>> {\n name: string;\n /** Canonical qualified model identity (\\`@package/name:ClassName\\`) for policy APIs. */\n objectRef: string;\n className: string;\n endpoint: string;\n idField: string;\n actions: string[];\n fields: Record<string, SmrtWebFieldDefinition>;\n /** Manifest-derived relationship edges to sibling REST collections. */\n relationships: SmrtWebRelationship[];\n /** WebMCP/MCP tool descriptors for the exposed actions (#1812). */\n toolDescriptors: WebToolDescriptor[];\n /** Phantom row-type carrier for inference — never present at runtime. */\n _row?: TData;\n }\n\n export interface SmrtWebCollectionDefinitions {\n${webCollectionEntries}\n }\n\n export const collectionDefinitions: SmrtWebCollectionDefinitions;\n export function getCollectionDefinition<\n K extends keyof SmrtWebCollectionDefinitions,\n >(name: K): SmrtWebCollectionDefinitions[K];\n /**\n * Build-time web-collection shape digest (#1764). A deterministic,\n * replica-stable hash of the emitted collection definitions; a change means\n * old persisted client rows may mis-hydrate. Consumers fold it into the\n * durable persistence namespace and the version-awareness updateAvailable\n * contract signal.\n */\n export const manifestHash: string;\n export default collectionDefinitions;\n}`;\n\n // Write all virtual module declarations\n fs.writeFileSync(\n path.join(outDir, 'smrt-manifest.d.ts'),\n manifestDeclaration,\n );\n fs.writeFileSync(path.join(outDir, 'smrt-client.d.ts'), clientDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-routes.d.ts'), routesDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-mcp.d.ts'), mcpDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-types.d.ts'), typesDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-web.d.ts'), webDeclaration);\n}\n\n/**\n * Map SMRT field types to TypeScript types\n */\nfunction mapFieldTypeToTypeScript(smrtType: string): string {\n switch (smrtType) {\n case 'text':\n return 'string';\n case 'decimal':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'datetime':\n return 'string | Date';\n case 'json':\n return 'any';\n case 'foreignKey':\n return 'string';\n default:\n return 'any';\n }\n}\n\n/**\n * CLI command for generating declarations\n */\nexport async function generateDeclarationsFromCLI(\n args: string[],\n): Promise<void> {\n const manifestPath = args[0];\n const outDir = args[1] || 'src/types/generated';\n\n if (!manifestPath) {\n console.error('Usage: generate-declarations <manifest-path> [output-dir]');\n process.exit(1);\n }\n\n if (!fs.existsSync(manifestPath)) {\n console.error(`Manifest file not found: ${manifestPath}`);\n process.exit(1);\n }\n\n await generateDeclarations({\n manifest: manifestPath,\n outDir,\n });\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,eAAsB,qBACpB,SACe;CACf,MAAM,EACJ,UAAU,eACV,QACA,wBAAwB,MACxB,qBAAqB,MACrB,cAAc,QAAQ,IAAI,MACxB;CAGJ,MAAM,WACJ,OAAO,kBAAkB,WACrB,KAAK,MAAM,GAAG,aAAa,eAAe,OAAO,CAAC,IAClD;CAGN,MAAM,aAAa,KAAK,WAAW,MAAM,IACrC,SACA,KAAK,KAAK,aAAa,MAAM;CACjC,GAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;CAE5C,QAAQ,IAAI,8CAA8C,YAAY;CAEtE,IAAI,oBACF,MAAM,+BAA+B,UAAU,UAAU;CAG3D,IAAI,uBACF,MAAM,kCA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K,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,cACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;AAKA,eAAsB,4BACpB,MACe;CACf,MAAM,eAAe,KAAK;CAC1B,MAAM,SAAS,KAAK,MAAM;CAE1B,IAAI,CAAC,cAAc;EACjB,QAAQ,MAAM,2DAA2D;EACzE,QAAQ,KAAK,CAAC;CAChB;CAEA,IAAI,CAAC,GAAG,WAAW,YAAY,GAAG;EAChC,QAAQ,MAAM,4BAA4B,cAAc;EACxD,QAAQ,KAAK,CAAC;CAChB;CAEA,MAAM,qBAAqB;EACzB,UAAU;EACV;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/prebuild/index.ts"],"sourcesContent":["/**\n * Pre-build utilities for generating TypeScript declarations\n * Solves virtual module resolution by creating physical .d.ts files\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { SmartObjectManifest } from '../scanner/types';\nimport {\n renderApiClientCrudType,\n renderApiClientCustomMethodParameters,\n selectApiClientEntries,\n} from '../vite-plugin/api-client-entries.js';\nimport { selectWebCollectionEntries } from '../vite-plugin/web-collections.js';\n\nexport interface PrebuildOptions {\n /** Path to manifest file or manifest object */\n manifest: string | SmartObjectManifest;\n /** Output directory for generated types */\n outDir: string;\n /** Include virtual module declarations */\n includeVirtualModules?: boolean;\n /** Include object type definitions */\n includeObjectTypes?: boolean;\n /** Project root path for resolving relative paths */\n projectRoot?: string;\n}\n\n/**\n * Generate TypeScript declaration files from SMRT manifest\n */\nexport async function generateDeclarations(\n options: PrebuildOptions,\n): Promise<void> {\n const {\n manifest: manifestInput,\n outDir,\n includeVirtualModules = true,\n includeObjectTypes = true,\n projectRoot = process.cwd(),\n } = options;\n\n // Load manifest\n const manifest: SmartObjectManifest =\n typeof manifestInput === 'string'\n ? JSON.parse(fs.readFileSync(manifestInput, 'utf-8'))\n : manifestInput;\n\n // Ensure output directory exists\n const fullOutDir = path.isAbsolute(outDir)\n ? outDir\n : path.join(projectRoot, outDir);\n fs.mkdirSync(fullOutDir, { recursive: true });\n\n console.log(`[smrt:prebuild] Generating declarations to ${fullOutDir}`);\n\n if (includeObjectTypes) {\n await generateObjectTypeDeclarations(manifest, fullOutDir);\n }\n\n if (includeVirtualModules) {\n await generateVirtualModuleDeclarations(manifest, fullOutDir);\n }\n\n console.log(\n `[smrt:prebuild] Generated declarations for ${Object.keys(manifest.objects).length} SMRT objects`,\n );\n}\n\n/**\n * Generate TypeScript interfaces for SMRT objects\n */\nasync function generateObjectTypeDeclarations(\n manifest: SmartObjectManifest,\n outDir: string,\n): Promise<void> {\n const interfaces: string[] = [];\n\n // Generate interfaces for each discovered SMRT object\n for (const [_objectName, objectMeta] of Object.entries(manifest.objects)) {\n const fields = objectMeta.fields || {};\n const propertyLines: string[] = [];\n\n // Add standard SmrtObject properties\n propertyLines.push(' id?: string;');\n propertyLines.push(' created_at?: string;');\n propertyLines.push(' updated_at?: string;');\n\n // Add object-specific properties\n for (const [fieldName, fieldDef] of Object.entries(fields)) {\n const type = mapFieldTypeToTypeScript(fieldDef.type);\n const optional = !fieldDef.required ? '?' : '';\n propertyLines.push(` ${fieldName}${optional}: ${type};`);\n }\n\n const interfaceDef = `export interface ${objectMeta.className}Data {\n${propertyLines.join('\\n')}\n}`;\n interfaces.push(interfaceDef);\n }\n\n // Write object types file\n const objectTypesContent = `/**\n * Auto-generated TypeScript interfaces for SMRT objects\n * Generated at build time from @smrt() decorated classes\n *\n * DO NOT EDIT THIS FILE MANUALLY\n */\n\n${interfaces.join('\\n\\n')}\n`;\n\n fs.writeFileSync(path.join(outDir, 'smrt-objects.d.ts'), objectTypesContent);\n}\n\n/**\n * Generate virtual module declarations\n */\nasync function generateVirtualModuleDeclarations(\n manifest: SmartObjectManifest,\n outDir: string,\n): Promise<void> {\n // Generate manifest module declaration\n const manifestDeclaration = `/**\n * Auto-generated manifest module declaration\n */\ndeclare module '@smrt/manifest' {\n export interface SmrtObjectField {\n type: string;\n required?: boolean;\n default?: any;\n }\n\n export interface SmrtObjectMethod {\n name: string;\n parameters: Array<{\n name: string;\n type: string;\n optional?: boolean;\n default?: any;\n }>;\n returnType: string;\n async: boolean;\n isStatic: boolean;\n isPublic: boolean;\n }\n\n export interface SmrtObjectDefinition {\n name: string;\n className: string;\n collection: string;\n filePath: string;\n fields: Record<string, SmrtObjectField>;\n methods: Record<string, SmrtObjectMethod>;\n decoratorConfig: any;\n extends?: string;\n }\n\n export interface SmrtManifest {\n version: string;\n timestamp: number;\n objects: Record<string, SmrtObjectDefinition>;\n }\n\n export const manifest: SmrtManifest;\n export default manifest;\n}`;\n\n // Generate client module declaration\n const apiClientInterface = selectApiClientEntries(manifest)\n .map(({ clientKey, dataInterfaceName, crudMethods, customMethods }) => {\n const overriddenMethods = customMethods.map(({ name }) => name);\n const crudType = renderApiClientCrudType(\n dataInterfaceName,\n crudMethods,\n overriddenMethods,\n );\n const customSignatures = customMethods\n .map(\n (method) =>\n ` ${method.name}(${renderApiClientCustomMethodParameters(\n method,\n mapFieldTypeToTypeScript,\n )}): Promise<any>;`,\n )\n .join('\\n');\n\n if (customSignatures) {\n const intersection = crudType ? `${crudType} & ` : '';\n return ` ${JSON.stringify(clientKey)}: ${intersection}{\\n${customSignatures}\\n };`;\n }\n\n return ` ${JSON.stringify(clientKey)}: ${crudType ?? 'Record<string, never>'};`;\n })\n .join('\\n');\n\n // Wire-shape policy (#1797): the server returns BARE JSON — a bare array for\n // list/search, a bare object for get/create/update — with snake_case field\n // names (created_at, updated_at). These physical declarations share client\n // entry selection and method-signature rendering with the Vite declaration.\n // Fetchers reject on non-2xx with a SmrtClientError (#1796).\n const clientDeclaration = `/**\n * Auto-generated API client module declaration\n */\ndeclare module '@smrt/client' {\n /** Structured custom-action failure nested under an API error body's \\`error\\` key. */\n export interface SmrtClientFailure {\n ok: false;\n code: string;\n message: string;\n status?: number;\n }\n\n /** Shape of a JSON error body carried by a rejected request (SmrtClientError.body). */\n export interface ApiError {\n error?: string | SmrtClientFailure;\n message?: string;\n }\n\n /** Typed error thrown by every fetcher on a non-2xx response (#1796). */\n export interface SmrtClientError extends Error {\n name: 'SmrtClientError';\n status: number;\n /** Machine-readable code from a structured custom-action failure, when present. */\n code?: string;\n body?: ApiError | string;\n }\n\n export interface CrudOperations<T = any> {\n list(params?: Record<string, any>): Promise<T[]>;\n get(id: string): Promise<T>;\n create(data: Partial<T>): Promise<T>;\n update(id: string, data: Partial<T>): Promise<T>;\n delete(id: string): Promise<boolean>;\n search(query: string): Promise<T[]>;\n }\n\n export interface ApiClient {\n${apiClientInterface}\n }\n\n export function createClient(basePath?: string): ApiClient;\n export default createClient;\n}`;\n\n // Generate routes module declaration\n const routesDeclaration = `/**\n * Auto-generated routes module declaration\n */\ndeclare module '@smrt/routes' {\n export interface RouteApp {\n get(path: string, handler: (req: any, res: any) => void): void;\n post(path: string, handler: (req: any, res: any) => void): void;\n put(path: string, handler: (req: any, res: any) => void): void;\n delete(path: string, handler: (req: any, res: any) => void): void;\n }\n\n export function setupRoutes(app: RouteApp): void;\n export default setupRoutes;\n}`;\n\n // Generate MCP module declaration\n const mcpDeclaration = `/**\n * Auto-generated MCP module declaration\n */\ndeclare module '@smrt/mcp' {\n export interface McpTool {\n name: string;\n description: string;\n inputSchema: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n }\n\n export const tools: McpTool[];\n export function createMCPServer(): {\n name: string;\n version: string;\n tools: McpTool[]\n };\n export default createMCPServer;\n}`;\n\n // Generate types module declaration with object imports\n const objectImports = Object.values(manifest.objects)\n .map(\n (obj) =>\n ` export type ${obj.className}Data = import('./smrt-objects').${obj.className}Data;`,\n )\n .join('\\n');\n\n const typesDeclaration = `/**\n * Auto-generated types module declaration\n */\ndeclare module '@smrt/types' {\n${objectImports}\n\n export interface Request {\n params: Record<string, string>;\n query: Record<string, any>;\n json(): Promise<any>;\n }\n\n export interface Response {\n json(data: any, init?: { status?: number }): Response;\n status(code: number): Response;\n }\n}`;\n\n // Generate web collection-definition module declaration (#1761). Selection\n // shares selectWebCollectionEntries with the vite-plugin runtime module and\n // its virt-web d.ts, so this `tsc`-only consumer declaration cannot drift\n // from the emitted values.\n const webCollectionEntries = selectWebCollectionEntries(manifest)\n .map(\n ({ collection, obj }) =>\n ` ${JSON.stringify(collection)}: SmrtWebCollectionDefinition<import('./smrt-objects').${obj.className}Data>;`,\n )\n .join('\\n');\n\n const webDeclaration = `/**\n * Auto-generated web collection-definition module declaration (#1761)\n */\ndeclare module '@smrt/web' {\n export type SmrtWebFieldType =\n | 'text'\n | 'decimal'\n | 'boolean'\n | 'integer'\n | 'datetime'\n | 'json'\n | 'foreignKey'\n | 'crossPackageRef';\n\n /** Static \\`@field({ ui })\\` hints (#2046) — the field-policy rail seed. */\n export interface SmrtWebFieldUIHints {\n basic?: boolean;\n group?: string;\n order?: number;\n locked?: boolean;\n }\n\n export interface SmrtWebFieldDefinition {\n type: SmrtWebFieldType;\n required?: boolean;\n nullable?: boolean;\n default?: unknown;\n /** Developer-authored \\`@field({ description })\\` (#2046) — end-user help seed. */\n description?: string;\n /** Static \\`@field({ ui })\\` hints (#2046). */\n ui?: SmrtWebFieldUIHints;\n }\n\n export type SmrtWebRelationshipKind =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\n /**\n * A manifest-derived edge to a sibling REST collection. Mutating this\n * collection invalidates the caches of the collections named by these edges\n * (#1761 relationship-derived invalidation).\n */\n export interface SmrtWebRelationship {\n field: string;\n kind: SmrtWebRelationshipKind;\n relatedCollection: string;\n }\n\n export interface WebToolRouteDescriptor {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n scope: 'item' | 'collection';\n path: string[];\n parameterAliases?: Record<string, string>;\n optionsBag?: boolean;\n }\n\n /** A WebMCP/MCP tool descriptor for one collection action (#1812). */\n export interface WebToolDescriptor {\n action: string;\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n readOnly: boolean;\n route?: WebToolRouteDescriptor;\n }\n\n export interface SmrtWebCollectionDefinition<TData = Record<string, unknown>> {\n name: string;\n /** Canonical qualified model identity (\\`@package/name:ClassName\\`) for policy APIs. */\n objectRef: string;\n className: string;\n endpoint: string;\n idField: string;\n actions: string[];\n fields: Record<string, SmrtWebFieldDefinition>;\n /** Manifest-derived relationship edges to sibling REST collections. */\n relationships: SmrtWebRelationship[];\n /** WebMCP/MCP tool descriptors for the exposed actions (#1812). */\n toolDescriptors: WebToolDescriptor[];\n /** Phantom row-type carrier for inference — never present at runtime. */\n _row?: TData;\n }\n\n export interface SmrtWebCollectionDefinitions {\n${webCollectionEntries}\n }\n\n export const collectionDefinitions: SmrtWebCollectionDefinitions;\n export function getCollectionDefinition<\n K extends keyof SmrtWebCollectionDefinitions,\n >(name: K): SmrtWebCollectionDefinitions[K];\n /**\n * Build-time web-collection shape digest (#1764). A deterministic,\n * replica-stable hash of the emitted collection definitions; a change means\n * old persisted client rows may mis-hydrate. Consumers fold it into the\n * durable persistence namespace and the version-awareness updateAvailable\n * contract signal.\n */\n export const manifestHash: string;\n export default collectionDefinitions;\n}`;\n\n // Write all virtual module declarations\n fs.writeFileSync(\n path.join(outDir, 'smrt-manifest.d.ts'),\n manifestDeclaration,\n );\n fs.writeFileSync(path.join(outDir, 'smrt-client.d.ts'), clientDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-routes.d.ts'), routesDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-mcp.d.ts'), mcpDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-types.d.ts'), typesDeclaration);\n fs.writeFileSync(path.join(outDir, 'smrt-web.d.ts'), webDeclaration);\n}\n\n/**\n * Map SMRT field types to TypeScript types\n */\nfunction mapFieldTypeToTypeScript(smrtType: string): string {\n switch (smrtType) {\n case 'text':\n return 'string';\n case 'decimal':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'datetime':\n return 'string | Date';\n case 'json':\n return 'any';\n case 'foreignKey':\n return 'string';\n default:\n return 'any';\n }\n}\n\n/**\n * CLI command for generating declarations\n */\nexport async function generateDeclarationsFromCLI(\n args: string[],\n): Promise<void> {\n const manifestPath = args[0];\n const outDir = args[1] || 'src/types/generated';\n\n if (!manifestPath) {\n console.error('Usage: generate-declarations <manifest-path> [output-dir]');\n process.exit(1);\n }\n\n if (!fs.existsSync(manifestPath)) {\n console.error(`Manifest file not found: ${manifestPath}`);\n process.exit(1);\n }\n\n await generateDeclarations({\n manifest: manifestPath,\n outDir,\n });\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,eAAsB,qBACpB,SACe;CACf,MAAM,EACJ,UAAU,eACV,QACA,wBAAwB,MACxB,qBAAqB,MACrB,cAAc,QAAQ,IAAI,MACxB;CAGJ,MAAM,WACJ,OAAO,kBAAkB,WACrB,KAAK,MAAM,GAAG,aAAa,eAAe,OAAO,CAAC,IAClD;CAGN,MAAM,aAAa,KAAK,WAAW,MAAM,IACrC,SACA,KAAK,KAAK,aAAa,MAAM;CACjC,GAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;CAE5C,QAAQ,IAAI,8CAA8C,YAAY;CAEtE,IAAI,oBACF,MAAM,+BAA+B,UAAU,UAAU;CAG3D,IAAI,uBACF,MAAM,kCAAkC,UAAU,UAAU;CAG9D,QAAQ,IACN,8CAA8C,OAAO,KAAK,SAAS,OAAO,CAAC,CAAC,OAAO,cACrF;AACF;;;;AAKA,eAAe,+BACb,UACA,QACe;CACf,MAAM,aAAuB,CAAC;CAG9B,KAAK,MAAM,CAAC,aAAa,eAAe,OAAO,QAAQ,SAAS,OAAO,GAAG;EACxE,MAAM,SAAS,WAAW,UAAU,CAAC;EACrC,MAAM,gBAA0B,CAAC;EAGjC,cAAc,KAAK,gBAAgB;EACnC,cAAc,KAAK,wBAAwB;EAC3C,cAAc,KAAK,wBAAwB;EAG3C,KAAK,MAAM,CAAC,WAAW,aAAa,OAAO,QA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AEA,MAAM,qBAAqB;EACzB,UAAU;EACV;CACF,CAAC;AACH"}
@@ -115,6 +115,12 @@ export interface FieldsToColumnsOptions {
115
115
  * Declared defaults are still emitted.
116
116
  */
117
117
  stiUnionColumns?: boolean;
118
+ /**
119
+ * Physical column names that form the table's natural conflict key.
120
+ * Undeclared delete actions on foreign-key members use the shared CASCADE
121
+ * default, matching app-side relationship cleanup.
122
+ */
123
+ conflictColumns?: readonly string[];
118
124
  }
119
125
  /**
120
126
  * Convert a Map of field definitions to column definitions
@@ -1 +1 @@
1
- {"version":3,"file":"schema-builder.d.ts","sourceRoot":"","sources":["../../src/registry/schema-builder.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAG3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAM7D,OAAO,KAAK,EACV,gBAAgB,EAEhB,gBAAgB,EAChB,WAAW,EACZ,MAAM,oBAAoB,CAAC;AAmL5B;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAIpE;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,cAAc,GACtB,MAAM,GAAG,SAAS,CAWpB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAkB7D;AAwTD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAC3B,MAAM,CAAC,EAAE,cAAc,GACtB,MAAM,CAAC,MAAM,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAmFxE;AAED;;;;;;;;;;GAUG;AACH,wBA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qBb"}
@@ -1,6 +1,8 @@
1
+ import { requireForeignKeyAction, resolveForeignKeyDeleteAction } from "../schema/foreign-key-policy.js";
1
2
  import { classnameToTablename, toSnakeCase } from "../utils/naming.js";
2
3
  import { formatDefaultValue as formatDefaultValue$1, quoteIdentifier } from "../schema/sql-identifiers.js";
3
4
  import { shortenIdentifier } from "../schema/index-utils.js";
5
+ import { renderForeignKeyConstraint, schemaForeignKeys } from "../schema/foreign-key-ddl.js";
4
6
  import { getDDLStrategy } from "../schema/ddl/index.js";
5
7
  import { getClasses, getCollectionTableNames } from "./shared-state.js";
6
8
  import { findClass } from "./name-resolver.js";
@@ -189,6 +191,53 @@ function withConflictIndex(tableName, columns, indexes, conflictColumns) {
189
191
  if (indexes.some((index) => index.name === name)) return indexes.map((index) => index.name === name ? conflictIndex : index);
190
192
  return [...indexes, conflictIndex];
191
193
  }
194
+ function applyContributorForeignKeys(tableSchema, contributor) {
195
+ const conflictColumns = new Set(tableSchema.conflictColumns);
196
+ for (const [fieldName, field] of contributor.registered.fields) {
197
+ if (field.type !== "foreignKey" || !field.related) continue;
198
+ const columnName = toSnakeCase(fieldName);
199
+ const column = tableSchema.columns[columnName];
200
+ if (!column) continue;
201
+ if (field._meta?.__tenancy?.isTenantIdField === true || field.__tenancy?.isTenantIdField === true) {
202
+ column.foreignKey = void 0;
203
+ continue;
204
+ }
205
+ const [targetName, declaredTargetColumn] = field.related.split(".");
206
+ const targetBase = ObjectRegistry.getSTIBase(targetName) || targetName;
207
+ const registeredTarget = ObjectRegistry.getClass(targetBase);
208
+ const targetColumn = declaredTargetColumn || Array.from(ObjectRegistry.getFields(targetBase).entries()).find(([, targetField]) => targetField._meta?.primaryKey === true)?.[0] || "id";
209
+ if (registeredTarget && !field._meta?.sqlType) {
210
+ const targetColumnName = toSnakeCase(targetColumn);
211
+ const targetColumnType = registeredTarget.schema?.columns?.[targetColumnName]?.type || (targetColumnName === "id" ? registeredTarget.config.idType === "text" ? "TEXT" : "UUID" : void 0);
212
+ if (targetColumnType) column.type = targetColumnType;
213
+ }
214
+ if (field._meta?.constraint === false) {
215
+ column.foreignKey = void 0;
216
+ continue;
217
+ }
218
+ const manifestForeignKey = contributor.registered.schema?.columns?.[columnName]?.foreignKey;
219
+ if (manifestForeignKey) {
220
+ column.foreignKey = manifestForeignKey;
221
+ continue;
222
+ }
223
+ if (!registeredTarget) {
224
+ column.foreignKey = void 0;
225
+ continue;
226
+ }
227
+ const targetTable = ObjectRegistry.getTableName(targetBase) || classnameToTablename(targetBase);
228
+ const { action } = resolveForeignKeyDeleteAction({
229
+ declared: field._meta?.onDelete,
230
+ isConflictColumn: conflictColumns.has(columnName),
231
+ isTenantIdField: false
232
+ });
233
+ column.foreignKey = {
234
+ table: targetTable,
235
+ column: toSnakeCase(targetColumn),
236
+ onDelete: action,
237
+ onUpdate: "CASCADE"
238
+ };
239
+ }
240
+ }
192
241
  /**
193
242
  * Resolve the physical table a registered class writes to.
194
243
  *
@@ -292,7 +341,11 @@ function buildMergedTableSchemas() {
292
341
  const tableSchemas = {};
293
342
  for (const [tableName, contributors] of contributorsByTable) for (const contributor of sortTableContributors(contributors)) {
294
343
  const { registered, simpleName, isSTI } = contributor;
295
- const columnsToUse = mergeRuntimeFieldColumns(simpleName, registered.schema?.columns, registered.fields, { stiUnionColumns: isSTI });
344
+ const conflictColumns = ObjectRegistry.getConflictColumns(contributor.conflictKey);
345
+ const columnsToUse = mergeRuntimeFieldColumns(simpleName, registered.schema?.columns, registered.fields, {
346
+ stiUnionColumns: isSTI,
347
+ conflictColumns
348
+ });
296
349
  let tableSchema = tableSchemas[tableName];
297
350
  if (!tableSchema) {
298
351
  tableSchema = {
@@ -304,10 +357,11 @@ function buildMergedTableSchemas() {
304
357
  indexes: [],
305
358
  ddl: registered.schema?.ddl || "",
306
359
  isSTI,
307
- conflictColumns: ObjectRegistry.getConflictColumns(contributor.conflictKey)
360
+ conflictColumns
308
361
  };
309
362
  tableSchemas[tableName] = tableSchema;
310
363
  } else for (const [colName, colDef] of Object.entries(columnsToUse)) if (!tableSchema.columns[colName]) tableSchema.columns[colName] = colDef;
364
+ applyContributorForeignKeys(tableSchema, contributor);
311
365
  const schemaIndexes = registered.schema?.indexes;
312
366
  if (schemaIndexes && schemaIndexes.length > 0) {
313
367
  const existingNames = new Set(tableSchema.indexes.map((index) => index.name));
@@ -352,6 +406,8 @@ function getAllSchemas(engine) {
352
406
  version: "",
353
407
  dependencies: []
354
408
  };
409
+ mergedSchema.foreignKeys = schemaForeignKeys(mergedSchema);
410
+ mergedSchema.dependencies = mergedSchema.foreignKeys.map((foreignKey) => foreignKey.referencesTable).filter((dependency) => dependency !== tableName);
355
411
  let ddl;
356
412
  if (Object.keys(tableSchema.columns).length === 0 && tableSchema.ddl) {
357
413
  if (engine) throw new Error(`Cannot materialize schema '${tableName}' for ${engine}: the manifest has no structured columns`);
@@ -389,15 +445,20 @@ function getAllSchemasAsDefinitions() {
389
445
  const schemas = {};
390
446
  for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {
391
447
  if (Object.keys(tableSchema.columns).length === 0) continue;
448
+ const ddl = generateDDLFromColumns(tableName, tableSchema.columns, tableSchema.isSTI);
449
+ const foreignKeys = schemaForeignKeys({
450
+ columns: tableSchema.columns,
451
+ foreignKeys: []
452
+ });
392
453
  schemas[tableName] = {
393
454
  tableName,
394
- ddl: generateDDLFromColumns(tableName, tableSchema.columns, tableSchema.isSTI),
455
+ ddl,
395
456
  columns: tableSchema.columns,
396
457
  indexes: withConflictIndex(tableName, tableSchema.columns, tableSchema.indexes, tableSchema.conflictColumns),
397
458
  triggers: [],
398
- foreignKeys: [],
459
+ foreignKeys,
399
460
  version: "",
400
- dependencies: []
461
+ dependencies: foreignKeys.map((foreignKey) => foreignKey.referencesTable).filter((dependency) => dependency !== tableName)
401
462
  };
402
463
  }
403
464
  return schemas;
@@ -429,6 +490,10 @@ function generateDDLFromColumns(tableName, columns, isSTI = false, engine) {
429
490
  }
430
491
  columnLines.push(parts.join(" "));
431
492
  }
493
+ for (const foreignKey of schemaForeignKeys({
494
+ columns,
495
+ foreignKeys: []
496
+ })) columnLines.push(` ${renderForeignKeyConstraint(tableName, foreignKey)}`);
432
497
  sql += columnLines.join(",\n");
433
498
  if (columns.slug && columns.context) if (isSTI && columns._meta_type) sql += ",\n UNIQUE(slug, context, _meta_type)";
434
499
  else sql += ",\n UNIQUE(slug, context)";
@@ -469,6 +534,7 @@ function formatDefaultValue(value, type) {
469
534
  */
470
535
  function fieldsToColumns(fields, options) {
471
536
  const columns = {};
537
+ const conflictColumns = new Set((options?.conflictColumns ?? []).map((column) => toSnakeCase(column)));
472
538
  for (const [fieldName, fieldDef] of fields) {
473
539
  if (fieldName === "id" || fieldName === "created_at" || fieldName === "updated_at" || fieldName === "slug" || fieldName === "context") continue;
474
540
  if (fieldDef.transient || fieldDef._meta?.transient) continue;
@@ -488,14 +554,18 @@ function fieldsToColumns(fields, options) {
488
554
  description
489
555
  };
490
556
  if (defaultValue !== void 0 && shouldEmitDefault(fieldDef, normalizedSqlType, defaultValue)) column.defaultValue = defaultValue;
491
- if (fieldDef.type === "foreignKey" && fieldDef.related) {
557
+ if (fieldDef.type === "foreignKey" && fieldDef.related && fieldDef._meta?.constraint !== false && fieldDef._meta?.__tenancy?.isTenantIdField !== true && !fieldDef.__tenancy?.isTenantIdField) {
492
558
  const [table, columnName = "id"] = fieldDef.related.split(".");
493
559
  const fieldMeta = fieldDef._meta;
494
560
  column.foreignKey = {
495
561
  table: classnameToTablename(table),
496
562
  column: columnName,
497
- onDelete: fieldMeta?.onDelete ?? "CASCADE",
498
- onUpdate: fieldMeta?.onUpdate ?? "CASCADE"
563
+ onDelete: resolveForeignKeyDeleteAction({
564
+ declared: fieldMeta?.onDelete,
565
+ isConflictColumn: conflictColumns.has(toSnakeCase(fieldName)),
566
+ isTenantIdField: false
567
+ }).action,
568
+ onUpdate: fieldMeta?.onUpdate === void 0 ? "CASCADE" : requireForeignKeyAction(fieldMeta.onUpdate, `${fieldName} ON UPDATE`)
499
569
  };
500
570
  }
501
571
  columns[toSnakeCase(fieldName)] = column;
@@ -1 +1 @@
1
- {"version":3,"file":"schema-builder.js","names":[],"sources":["../../src/registry/schema-builder.ts"],"sourcesContent":["/**\n * Schema building logic for the SMRT ObjectRegistry.\n *\n * Extracted from registry.ts as part of issue #1006.\n */\n\nimport { ObjectRegistry } from '../registry';\nimport type { FieldDefinition } from '../scanner/types.js';\nimport { conflictIndexName } from '../schema/conflict-target.js';\nimport { getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport { shortenIdentifier } from '../schema/index-utils.js';\nimport {\n formatDefaultValue as formatDefaultValueShared,\n quoteIdentifier,\n} from '../schema/sql-identifiers.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaDefinition,\n SQLDataType,\n} from '../schema/types.js';\nimport { classnameToTablename, toSnakeCase } from '../utils';\nimport {\n type CollectionRegistrationLookup,\n isCollectionRegistration,\n} from './collection-resolution';\nimport { readFieldAttribute } from './manifest-field-merge';\nimport { findClass } from './name-resolver';\nimport { getClasses, getCollectionTableNames } from './shared-state';\nimport type { RegisteredClass } from './types';\n\ntype ForeignKeyAction = NonNullable<\n NonNullable<ColumnDefinition['foreignKey']>['onDelete']\n>;\n\nconst collectionRegistrationLookup: CollectionRegistrationLookup = {\n findClass,\n findClassInPackage: (packageName, className) =>\n ObjectRegistry.getClassInPackage(packageName, className),\n getInheritanceChain: (className) =>\n ObjectRegistry.getInheritanceChain(className),\n};\n\nfunction applyDecoratorSqlTypeOverrides(\n className: string,\n columns: Record<string, ColumnDefinition>,\n): Record<string, ColumnDefinition> {\n const decorators = ObjectRegistry.getFieldDecorators(className);\n if (!decorators.size) {\n return columns;\n }\n\n for (const [fieldName, options] of decorators) {\n if (!options?.sqlType) {\n continue;\n }\n\n const columnName = toSnakeCase(fieldName);\n const existing = columns[columnName];\n if (!existing) {\n continue;\n }\n\n const referenceKind = getReferenceKind(options as FieldDefinition);\n columns[columnName] = {\n ...existing,\n type: String(options.sqlType).toUpperCase() as SQLDataType,\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n\n return columns;\n}\n\nfunction mergeRuntimeFieldColumns(\n className: string,\n schemaColumns: Record<string, ColumnDefinition> | undefined,\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columnsToUse = { ...(schemaColumns || {}) };\n\n if (fields.size > 0) {\n const fieldColumns = fieldsToColumns(fields, options);\n for (const [columnName, columnDef] of Object.entries(fieldColumns)) {\n if (!columnsToUse[columnName]) {\n columnsToUse[columnName] = columnDef;\n }\n }\n\n for (const [fieldName, fieldDef] of fields) {\n const columnName = toSnakeCase(fieldName);\n const existing = columnsToUse[columnName];\n if (!existing) {\n continue;\n }\n\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef as unknown as { sqlType?: string }).sqlType;\n const referenceKind = getReferenceKind(fieldDef);\n columnsToUse[columnName] = {\n ...existing,\n ...(sqlType\n ? { type: String(sqlType).toUpperCase() as SQLDataType }\n : {}),\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n }\n\n applyDecoratorSqlTypeOverrides(className, columnsToUse);\n return columnsToUse;\n}\n\nfunction getReferenceKind(\n fieldDef: FieldDefinition,\n): ColumnDefinition['referenceKind'] | undefined {\n if (\n (\n fieldDef as unknown as {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField ||\n fieldDef._meta?.__tenancy?.isTenantIdField\n ) {\n return 'tenantId';\n }\n\n if (fieldDef.type === 'foreignKey') {\n return 'foreignKey';\n }\n\n if (fieldDef.type === 'crossPackageRef') {\n return 'crossPackageRef';\n }\n\n return undefined;\n}\n\nfunction shouldEmitDefault(\n fieldDef: FieldDefinition,\n sqlType: SQLDataType,\n defaultValue: unknown,\n) {\n return !(\n getReferenceKind(fieldDef) === 'tenantId' &&\n sqlType === 'UUID' &&\n defaultValue === ''\n );\n}\n\n/**\n * Fallback base columns for a table whose contributing class carries no\n * manifest columns.\n *\n * These mirror what the manifest schema generators emit for the same table\n * (`generateSchemaFromManifest` / `generateSTISchemaFromManifest`), so a table\n * assembled from runtime field metadata alone has the same NOT NULL and\n * DEFAULT shape as one assembled from a manifest. Divergence here is what made\n * the merged table shape depend on which class registered first (#2372).\n */\nfunction createBaseColumns(\n registered: {\n config?: { idType?: 'uuid' | 'text' };\n },\n isSTI: boolean,\n): Record<string, ColumnDefinition> {\n const baseColumns: Record<string, ColumnDefinition> = {\n id: {\n type: registered.config?.idType === 'text' ? 'TEXT' : 'UUID',\n primaryKey: true,\n notNull: true,\n referenceKind: 'id',\n },\n slug: { type: 'TEXT', notNull: true },\n context: { type: 'TEXT', notNull: true, defaultValue: '' },\n created_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n updated_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n };\n\n // STI tables also carry the discriminator and the meta payload column\n // (issue #690: db:diff needs them to detect schema changes).\n if (isSTI) {\n baseColumns._meta_type = { type: 'TEXT', notNull: true };\n baseColumns._meta_data = { type: 'JSON', notNull: false };\n }\n\n return baseColumns;\n}\n\n/**\n * Get cached schema definition for a registered class\n *\n * @param name - Name of the registered class\n * @returns Schema definition or undefined if not found\n * @example\n * ```typescript\n * const schema = getSchema('Product');\n * console.log(schema.tableName); // 'products'\n * console.log(schema.ddl); // 'CREATE TABLE...'\n * ```\n */\nexport function getSchema(name: string): SchemaDefinition | undefined {\n // Issue #951: Use findClass for multi-strategy lookup\n const registered = findClass(name);\n return registered?.schema;\n}\n\n/**\n * Get SQL DDL statement for a registered class\n *\n * @param name - Name of the registered class\n * Cached manifest DDL contains abstract types and is not safe to execute on\n * PostgreSQL. New executable paths must pass a target engine. Omitting it is\n * retained for backward compatibility with consumers that only inspect the\n * legacy engine-neutral manifest string.\n *\n * @param engine - Database engine that will execute the DDL\n * @returns Engine-specific SQL DDL, or the legacy cached DDL when omitted\n * @example\n * ```typescript\n * const ddl = ObjectRegistry.getSchemaDDL('Product', 'postgres');\n * await db.query(ddl);\n * ```\n */\nexport function getSchemaDDL(\n name: string,\n engine?: DatabaseEngine,\n): string | undefined {\n const schema = getSchema(name);\n if (!schema) return undefined;\n if (engine && Object.keys(schema.columns).length === 0) {\n throw new Error(\n `Cannot materialize schema '${name}' for ${engine}: the manifest has no structured columns`,\n );\n }\n return engine\n ? getDDLStrategy(engine).generateCreateTable(schema)\n : schema.ddl;\n}\n\n/**\n * Get table name for a registered class\n *\n * @param name - Name of the registered class\n * @returns Table name or undefined if not found\n * @example\n * ```typescript\n * const tableName = getTableName('Product');\n * console.log(tableName); // 'products'\n * ```\n */\nexport function getTableName(name: string): string | undefined {\n // Check if this is a collection class - collections have their own tableName mapping\n const collectionTableName = getCollectionTableNames().get(name);\n if (collectionTableName) {\n return collectionTableName;\n }\n\n // For STI classes, return the STI base class's table name.\n // R5-canon: `getSTIBase` returns the qualified name; resolve `name`\n // (which may be simple) to its registration's qualified form for the\n // comparison.\n const stiBase = ObjectRegistry.getSTIBase(name);\n const registered = ObjectRegistry.getClass(name);\n const qualifiedName = registered?.qualifiedName ?? registered?.name ?? name;\n if (stiBase && stiBase !== qualifiedName) {\n return getSchema(stiBase)?.tableName;\n }\n return getSchema(name)?.tableName;\n}\n\nfunction withConflictIndex(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n indexes: IndexDefinition[],\n conflictColumns: string[],\n): IndexDefinition[] {\n if (\n conflictColumns.length === 0 ||\n !conflictColumns.every((column) => columns[column])\n ) {\n return indexes;\n }\n\n // `ON CONFLICT (id)` binds to the primary-key constraint itself; a second\n // unique index over the primary key column set adds nothing (#2359, A5).\n // Kept in step with SchemaGenerator.conflictColumnsArePrimaryKey().\n const primaryKeyColumns = Object.entries(columns)\n .filter(([, column]) => column.primaryKey === true)\n .map(([name]) => name);\n if (\n primaryKeyColumns.length > 0 &&\n primaryKeyColumns.length === conflictColumns.length &&\n primaryKeyColumns.every((column) => conflictColumns.includes(column))\n ) {\n return indexes;\n }\n\n const hasConflictIndex = indexes.some(\n (index) =>\n index.unique === true &&\n !index.where &&\n !index.jsonPath &&\n index.columns.length === conflictColumns.length &&\n index.columns.every((column) => conflictColumns.includes(column)),\n );\n if (hasConflictIndex) return indexes;\n\n // Same stable naming as SchemaGenerator (`schema/conflict-target.ts`), so\n // a manifest built before the runtime learned the tenant-aware default\n // (#2360) has its stale `<table>_slug_context_idx` REPLACED in place here\n // — the differ then swaps the live index by name — instead of a second,\n // suffixed unique index being appended beside the old global one.\n const tenantColumn = Object.entries(columns).find(\n ([, column]) => column.referenceKind === 'tenantId',\n )?.[0];\n // The composed name can exceed PostgreSQL's 63-byte limit on a long table.\n // Shortening here (rather than inside conflictIndexName) keeps the generator\n // paths, which run enforceIdentifierLimits() over their whole index list,\n // and this migrate leg agreeing on the final name (#2374).\n const name = shortenIdentifier(\n conflictIndexName(tableName, conflictColumns, tenantColumn),\n );\n const conflictIndex: IndexDefinition = {\n name,\n columns: conflictColumns,\n unique: true,\n };\n if (indexes.some((index) => index.name === name)) {\n return indexes.map((index) =>\n index.name === name ? conflictIndex : index,\n );\n }\n return [...indexes, conflictIndex];\n}\n\n/**\n * A registered class that contributes columns to one physical table.\n *\n * For a single-table-inheritance hierarchy every class in the hierarchy is a\n * contributor to the same table.\n */\ninterface TableContributor {\n registered: RegisteredClass;\n simpleName: string;\n qualifiedName: string;\n isSTI: boolean;\n /** True when this class is the STI base that owns the table. */\n isSTIBase: boolean;\n /** Inheritance depth; ancestors sort before descendants. */\n depth: number;\n /** Conflict-column lookup key (the STI base for STI members). */\n conflictKey: string;\n}\n\n/**\n * A merged physical table assembled from every class that contributes to it.\n */\ninterface MergedTableSchema {\n tableName: string;\n columns: Record<string, ColumnDefinition>;\n indexes: IndexDefinition[];\n ddl: string;\n isSTI: boolean;\n conflictColumns: string[];\n}\n\n/**\n * Resolve the physical table a registered class writes to.\n *\n * STI subclasses are folded onto their base's table. Returns `undefined` when\n * the class has no table (for example an unresolvable manifest stub).\n *\n * R5-canon: STI lookups use the qualified key so a colliding simple name in\n * another package cannot yield the wrong table strategy or STI base and move\n * this class's columns under that other package's table.\n */\nfunction resolveContributorTable(\n registered: RegisteredClass,\n fallbackName: string,\n): { tableName: string; contributor: TableContributor } | undefined {\n const simpleName = registered.name || fallbackName;\n const qualifiedName = registered.qualifiedName ?? simpleName;\n\n // STI subclasses loaded from external manifests can arrive with a null\n // tableName; registerFromManifest() then derives one from the class name.\n // Adopt the STI base's tableName instead so the subclass lands on the\n // shared table (issue #703).\n if (!registered.schema?.tableName && registered.extends) {\n if (ObjectRegistry.getTableStrategy(qualifiedName) === 'sti') {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName && stiBaseName !== qualifiedName) {\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n if (!registered.schema) {\n registered.schema = {\n tableName: '',\n ddl: '',\n columns: {},\n indexes: [],\n triggers: [],\n foreignKeys: [],\n dependencies: [],\n version: '',\n };\n }\n registered.schema.tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n if (!registered.schema?.tableName) {\n return undefined;\n }\n\n let tableName = registered.schema.tableName;\n const tableStrategy = ObjectRegistry.getTableStrategy(qualifiedName);\n const isSTI = tableStrategy === 'sti';\n let isSTIBase = isSTI;\n let conflictKey = qualifiedName;\n\n if (isSTI) {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName) {\n conflictKey = stiBaseName;\n if (stiBaseName !== qualifiedName) {\n isSTIBase = false;\n // STI subclasses serialize to the base class's table even when they\n // carry a tableName of their own (issue #693).\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n return {\n tableName,\n contributor: {\n registered,\n simpleName,\n qualifiedName,\n isSTI,\n isSTIBase,\n depth: ObjectRegistry.getInheritanceChain(qualifiedName).length,\n conflictKey,\n },\n };\n}\n\n/**\n * Order the classes that share one table deterministically.\n *\n * The first contributor seeds the table: it supplies the base columns, the\n * `idType`, the conflict columns and the cached DDL, and its columns win every\n * merge conflict. Registration order must not decide that, or the same\n * hierarchy yields a different table shape depending on which class a manifest\n * happens to list first — child-first dropped NOT NULL and DEFAULT from the\n * base columns (#2372).\n *\n * Order: the STI base first, then ancestors before descendants, then by\n * qualified name so the result is a total order.\n */\nfunction sortTableContributors(contributors: TableContributor[]) {\n return [...contributors].sort((a, b) => {\n if (a.isSTIBase !== b.isSTIBase) {\n return a.isSTIBase ? -1 : 1;\n }\n if (a.depth !== b.depth) {\n return a.depth - b.depth;\n }\n return a.qualifiedName.localeCompare(b.qualifiedName);\n });\n}\n\n/**\n * Assemble every physical table from the classes that contribute to it.\n *\n * Shared by {@link getAllSchemas} and {@link getAllSchemasAsDefinitions} so\n * both produce the same merged shape. The result depends only on what is\n * registered, never on the order it was registered in.\n */\nfunction buildMergedTableSchemas(): Record<string, MergedTableSchema> {\n // Pass 1: group contributing classes by physical table.\n const contributorsByTable = new Map<string, TableContributor[]>();\n\n for (const [className, registered] of getClasses()) {\n // Collection classes have no table of their own; their schemas carry\n // collection properties (loaded, options, ...) rather than columns.\n if (\n isCollectionRegistration(\n className,\n registered,\n collectionRegistrationLookup,\n )\n ) {\n continue;\n }\n\n const resolved = resolveContributorTable(registered, className);\n if (!resolved) {\n continue;\n }\n\n const existing = contributorsByTable.get(resolved.tableName);\n if (existing) {\n existing.push(resolved.contributor);\n } else {\n contributorsByTable.set(resolved.tableName, [resolved.contributor]);\n }\n }\n\n // Pass 2: merge each table's contributors in deterministic order.\n const tableSchemas: Record<string, MergedTableSchema> = {};\n\n for (const [tableName, contributors] of contributorsByTable) {\n for (const contributor of sortTableContributors(contributors)) {\n const { registered, simpleName, isSTI } = contributor;\n\n // The manifest schema stays authoritative for the columns it defines.\n // Runtime field metadata backfills columns the manifest never had (for\n // example tenantScoped injections) and applies explicit sqlType\n // overrides, without erasing richer manifest metadata.\n const columnsToUse = mergeRuntimeFieldColumns(\n simpleName,\n registered.schema?.columns,\n registered.fields,\n { stiUnionColumns: isSTI },\n );\n\n let tableSchema = tableSchemas[tableName];\n if (!tableSchema) {\n tableSchema = {\n tableName,\n columns: {\n ...createBaseColumns(registered, isSTI),\n ...columnsToUse,\n },\n indexes: [],\n ddl: registered.schema?.ddl || '',\n isSTI,\n conflictColumns: ObjectRegistry.getConflictColumns(\n contributor.conflictKey,\n ),\n };\n tableSchemas[tableName] = tableSchema;\n } else {\n // Another class sharing this table (STI): add only columns the\n // seeding contributor did not already define.\n for (const [colName, colDef] of Object.entries(columnsToUse)) {\n if (!tableSchema.columns[colName]) {\n tableSchema.columns[colName] = colDef;\n }\n }\n }\n\n // Merge indexes, keeping the first definition of each name.\n const schemaIndexes = registered.schema?.indexes;\n if (schemaIndexes && schemaIndexes.length > 0) {\n const existingNames = new Set(\n tableSchema.indexes.map((index) => index.name),\n );\n for (const index of schemaIndexes) {\n // Legacy string-format indexes carry no columns and cannot be merged.\n if (typeof index === 'string') {\n continue;\n }\n if (!existingNames.has(index.name)) {\n tableSchema.indexes.push(index);\n existingNames.add(index.name);\n }\n }\n }\n }\n }\n\n return tableSchemas;\n}\n\n/**\n * Get all pre-generated schemas for explicit adapter bootstrap paths.\n *\n * Returns schemas in SDK SchemaProvider format for all registered classes.\n * Tooling and test helpers can pass these to `getDatabase()` when they want\n * to bootstrap schema before runtime. Core runtime no longer does this\n * implicitly.\n *\n * @returns Record of table names to schema definitions\n * @example\n * ```typescript\n * const schemas = ObjectRegistry.getAllSchemas('json');\n * const db = await getDatabase({ type: 'json', url: './data', schemas });\n * ```\n */\nexport function getAllSchemas(\n engine?: DatabaseEngine,\n): Record<string, { tableName: string; ddl: string; indexes?: string[] }> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to output format, regenerating DDL for merged schemas\n const schemas: Record<\n string,\n { tableName: string; ddl: string; indexes?: string[] }\n > = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n const engineIndexes = engine\n ? withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n )\n : tableSchema.indexes;\n const mergedSchema: SchemaDefinition = {\n tableName,\n ddl: tableSchema.ddl,\n columns: tableSchema.columns,\n indexes: engineIndexes,\n triggers: [],\n foreignKeys: [],\n version: '',\n dependencies: [],\n };\n\n // Generate DDL from merged columns (or use original DDL if columns are empty)\n let ddl: string;\n if (Object.keys(tableSchema.columns).length === 0 && tableSchema.ddl) {\n if (engine) {\n throw new Error(\n `Cannot materialize schema '${tableName}' for ${engine}: the manifest has no structured columns`,\n );\n }\n // Preserve legacy inspection of cached engine-neutral DDL. Executable\n // target-engine paths fail above rather than returning unsafe SQL.\n ddl = tableSchema.ddl;\n } else if (Object.keys(tableSchema.columns).length === 0) {\n // Skip schemas with no columns and no original DDL\n continue;\n } else if (engine) {\n // Target-engine materialization must route the complete structured\n // schema through its strategy. In particular, DuckDB/JSON require\n // UNIQUE constraints inline for ON CONFLICT, and every strategy owns\n // CHECK/default/index-expression rendering.\n ddl = getDDLStrategy(engine).generateCreateTable(mergedSchema);\n } else {\n ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n }\n\n // Convert index definitions to SQL strings for SDK compatibility\n let indexSQL: string[] | undefined;\n if (engineIndexes.length > 0) {\n indexSQL = engine\n ? getDDLStrategy(engine).generateIndexes(mergedSchema)\n : engineIndexes.map((idx) => {\n const indexType = idx.unique ? 'UNIQUE INDEX' : 'INDEX';\n const columnList = idx.columns\n .map((col) => quoteIdentifier(col))\n .join(', ');\n return `CREATE ${indexType} IF NOT EXISTS ${quoteIdentifier(\n idx.name,\n )} ON ${quoteIdentifier(tableName)} (${columnList});`;\n });\n }\n\n schemas[tableName] = {\n tableName,\n ddl,\n indexes: indexSQL,\n };\n }\n\n return schemas;\n}\n\n/**\n * Get all registered schemas as SchemaDefinition objects\n *\n * Similar to getAllSchemas(), but returns SchemaDefinition format suitable\n * for use with SchemaComparer (migrations/differ.ts).\n *\n * Key difference: Indexes are kept as IndexDefinition objects instead of\n * being converted to SQL strings.\n *\n * @returns Map of tableName to SchemaDefinition\n */\nexport function getAllSchemasAsDefinitions(): Record<string, SchemaDefinition> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to SchemaDefinition format\n const schemas: Record<string, SchemaDefinition> = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n if (Object.keys(tableSchema.columns).length === 0) {\n continue;\n }\n\n // Generate DDL from columns\n const ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n\n schemas[tableName] = {\n tableName,\n ddl,\n columns: tableSchema.columns,\n indexes: withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n ),\n triggers: [],\n foreignKeys: [],\n version: '',\n dependencies: [],\n };\n }\n\n return schemas;\n}\n\n/**\n * Generate DDL CREATE TABLE statement from columns\n *\n * Used internally by getAllSchemas() to regenerate DDL after merging\n * columns from multiple STI subtypes that share the same table.\n *\n * @param tableName - Name of the table\n * @param columns - Column definitions\n * @returns DDL CREATE TABLE statement\n */\nexport function generateDDLFromColumns(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n isSTI = false,\n engine?: DatabaseEngine,\n): string {\n let sql = `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(tableName)} (\\n`;\n\n const columnLines: string[] = [];\n for (const [columnName, columnDef] of Object.entries(columns)) {\n const parts: string[] = [];\n\n // Column name and type\n const strategy = engine ? getDDLStrategy(engine) : undefined;\n const columnType = strategy\n ? strategy.mapType(columnDef.type)\n : columnDef.type;\n parts.push(` ${quoteIdentifier(columnName)} ${columnType}`);\n\n // Primary key\n if (columnDef.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // Not null constraint\n if (columnDef.notNull) {\n parts.push('NOT NULL');\n }\n\n // Unique constraint (skip if primary key already implies uniqueness)\n if (columnDef.unique && !columnDef.primaryKey) {\n parts.push('UNIQUE');\n }\n\n // Default value\n if (columnDef.defaultValue !== undefined) {\n const defaultSQL = strategy\n ? strategy.formatDefaultValue(columnDef.defaultValue, columnDef.type)\n : formatDefaultValue(columnDef.defaultValue, columnDef.type);\n parts.push(`DEFAULT ${defaultSQL}`);\n }\n\n columnLines.push(parts.join(' '));\n }\n\n sql += columnLines.join(',\\n');\n\n // Add UNIQUE constraint for UPSERT operations\n // For STI tables: UNIQUE(slug, context, _meta_type) - different types can have same slug+context\n // For non-STI tables: UNIQUE(slug, context)\n if (columns.slug && columns.context) {\n if (isSTI && columns._meta_type) {\n sql += ',\\n UNIQUE(slug, context, _meta_type)';\n } else {\n sql += ',\\n UNIQUE(slug, context)';\n }\n }\n\n sql += '\\n);';\n\n return sql;\n}\n\n/**\n * Format default value for SQL DDL.\n *\n * Thin wrapper over the shared, injection-safe formatter\n * (`schema/sql-identifiers.ts`) so the registry schema-builder uses the same\n * rules as the DDL strategies and schema generator: an allowlist of SQL\n * keyword/function defaults (not \"contains `(`\"), type-driven literal quoting,\n * and no folding of a literal string `\"null\"` into the SQL NULL keyword.\n *\n * @param value - Default value\n * @param type - Column SQL type\n * @returns Formatted SQL default value\n */\nexport function formatDefaultValue(value: unknown, type: string): string {\n return formatDefaultValueShared(value, type);\n}\n\n/**\n * Options for {@link fieldsToColumns}.\n */\nexport interface FieldsToColumnsOptions {\n /**\n * Shape the columns for a single-table-inheritance table.\n *\n * An STI table holds the union of every subtype's fields, so a column that\n * only one subtype declares must stay nullable — rows of sibling subtypes\n * never populate it. This matches `generateSTISchemaFromManifest`, which\n * emits `notNull: false` for every non-system column on an STI table.\n * Declared defaults are still emitted.\n */\n stiUnionColumns?: boolean;\n}\n\n/**\n * Convert a Map of field definitions to column definitions\n *\n * Used by getAllSchemas() to generate columns from fields when a class\n * has no pre-generated schema (e.g., STI subclasses registered from manifest).\n *\n * `required`, `default`, and `description` are read from either the top level\n * or `_meta`: registry-sourced fields normalize them into `_meta`, so reading\n * only the top level dropped NOT NULL and DEFAULT for every such field\n * (#2372).\n *\n * @param fields - Map of field name to field definition\n * @param options - Table-shape options (see {@link FieldsToColumnsOptions})\n * @returns Record of column name to column definition\n * @private\n */\nexport function fieldsToColumns(\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columns: Record<string, ColumnDefinition> = {};\n\n for (const [fieldName, fieldDef] of fields) {\n // Skip id, timestamps - they're on the base table\n if (\n fieldName === 'id' ||\n fieldName === 'created_at' ||\n fieldName === 'updated_at' ||\n fieldName === 'slug' ||\n fieldName === 'context'\n ) {\n continue;\n }\n\n // Skip transient fields (non-persisted)\n if (fieldDef.transient || fieldDef._meta?.transient) {\n continue;\n }\n\n // Skip relationship fields that don't create columns\n // oneToMany and manyToMany are relationship metadata, not actual database columns\n if (fieldDef.type === 'oneToMany' || fieldDef.type === 'manyToMany') {\n continue;\n }\n\n // Skip meta fields - they're stored in _meta_data JSONB column\n if (fieldDef.type === 'meta') {\n continue;\n }\n\n // Map field type to SQL type\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef.type === 'crossPackageRef' &&\n (fieldDef._meta?.idType === 'text' ||\n (fieldDef as unknown as { idType?: string }).idType === 'text')\n ? 'TEXT'\n : mapFieldTypeToSQL(fieldDef.type));\n const normalizedSqlType = String(sqlType).toUpperCase() as SQLDataType;\n const referenceKind = getReferenceKind(fieldDef);\n\n const required = readFieldAttribute(fieldDef, 'required');\n const defaultValue = readFieldAttribute(fieldDef, 'default');\n const description = readFieldAttribute(fieldDef, 'description');\n\n const column: ColumnDefinition = {\n type: normalizedSqlType,\n referenceKind,\n notNull: options?.stiUnionColumns\n ? false\n : fieldDef._meta?.nullable\n ? false\n : Boolean(required),\n unique: fieldDef._meta?.unique || false,\n description: description as string | undefined,\n };\n\n // Handle default values\n if (\n defaultValue !== undefined &&\n shouldEmitDefault(fieldDef, normalizedSqlType, defaultValue)\n ) {\n column.defaultValue = defaultValue;\n }\n\n // Handle foreign keys\n if (fieldDef.type === 'foreignKey' && fieldDef.related) {\n const [table, columnName = 'id'] = fieldDef.related.split('.');\n const fieldMeta = fieldDef._meta as\n | {\n onDelete?: ForeignKeyAction;\n onUpdate?: ForeignKeyAction;\n }\n | undefined;\n column.foreignKey = {\n table: classnameToTablename(table),\n column: columnName,\n onDelete: fieldMeta?.onDelete ?? 'CASCADE',\n onUpdate: fieldMeta?.onUpdate ?? 'CASCADE',\n };\n }\n\n // Use snake_case for column names\n columns[toSnakeCase(fieldName)] = column;\n }\n\n return columns;\n}\n\n/**\n * Map field type to SQL data type\n * @private\n */\nexport function mapFieldTypeToSQL(\n fieldType: FieldDefinition['type'],\n): SQLDataType {\n switch (fieldType) {\n case 'text':\n return 'TEXT';\n case 'integer':\n return 'INTEGER';\n case 'decimal':\n return 'REAL';\n case 'boolean':\n return 'BOOLEAN';\n case 'datetime':\n return 'TIMESTAMP';\n case 'json':\n return 'JSON';\n case 'foreignKey':\n return 'UUID';\n case 'crossPackageRef':\n return 'UUID';\n default:\n return 'TEXT';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoCA,IAAM,+BAA6D;CACjE;CACA,qBAAqB,aAAa,cAChC,eAAe,kBAAkB,aAAa,SAAS;CACzD,sBAAsB,cACpB,eAAe,oBAAoB,SAAS;AAChD;AAEA,SAAS,+BACP,WACA,SACkC;CAClC,MAAM,aAAa,eAAe,mBAAmB,SAAS;CAC9D,IAAI,CAAC,WAAW,MACd,OAAO;CAGT,KAAK,MAAM,CAAC,WAAW,YAAY,YAAY;EAC7C,IAAI,CAAC,SAAS,SACZ;EAGF,MAAM,aAAa,YAAY,SAAS;EACxC,MAAM,WAAW,Q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H,OAAO;EACT,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,cACH,OAAO;EACT,KAAK,mBACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
1
+ {"version":3,"file":"schema-builder.js","names":[],"sources":["../../src/registry/schema-builder.ts"],"sourcesContent":["/**\n * Schema building logic for the SMRT ObjectRegistry.\n *\n * Extracted from registry.ts as part of issue #1006.\n */\n\nimport { ObjectRegistry } from '../registry';\nimport type { FieldDefinition } from '../scanner/types.js';\nimport { conflictIndexName } from '../schema/conflict-target.js';\nimport { getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport {\n renderForeignKeyConstraint,\n schemaForeignKeys,\n} from '../schema/foreign-key-ddl.js';\nimport {\n requireForeignKeyAction,\n resolveForeignKeyDeleteAction,\n} from '../schema/foreign-key-policy.js';\nimport { shortenIdentifier } from '../schema/index-utils.js';\nimport {\n formatDefaultValue as formatDefaultValueShared,\n quoteIdentifier,\n} from '../schema/sql-identifiers.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaDefinition,\n SQLDataType,\n} from '../schema/types.js';\nimport { classnameToTablename, toSnakeCase } from '../utils';\nimport {\n type CollectionRegistrationLookup,\n isCollectionRegistration,\n} from './collection-resolution';\nimport { readFieldAttribute } from './manifest-field-merge';\nimport { findClass } from './name-resolver';\nimport { getClasses, getCollectionTableNames } from './shared-state';\nimport type { RegisteredClass } from './types';\n\ntype ForeignKeyAction = NonNullable<\n NonNullable<ColumnDefinition['foreignKey']>['onDelete']\n>;\n\nconst collectionRegistrationLookup: CollectionRegistrationLookup = {\n findClass,\n findClassInPackage: (packageName, className) =>\n ObjectRegistry.getClassInPackage(packageName, className),\n getInheritanceChain: (className) =>\n ObjectRegistry.getInheritanceChain(className),\n};\n\nfunction applyDecoratorSqlTypeOverrides(\n className: string,\n columns: Record<string, ColumnDefinition>,\n): Record<string, ColumnDefinition> {\n const decorators = ObjectRegistry.getFieldDecorators(className);\n if (!decorators.size) {\n return columns;\n }\n\n for (const [fieldName, options] of decorators) {\n if (!options?.sqlType) {\n continue;\n }\n\n const columnName = toSnakeCase(fieldName);\n const existing = columns[columnName];\n if (!existing) {\n continue;\n }\n\n const referenceKind = getReferenceKind(options as FieldDefinition);\n columns[columnName] = {\n ...existing,\n type: String(options.sqlType).toUpperCase() as SQLDataType,\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n\n return columns;\n}\n\nfunction mergeRuntimeFieldColumns(\n className: string,\n schemaColumns: Record<string, ColumnDefinition> | undefined,\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columnsToUse = { ...(schemaColumns || {}) };\n\n if (fields.size > 0) {\n const fieldColumns = fieldsToColumns(fields, options);\n for (const [columnName, columnDef] of Object.entries(fieldColumns)) {\n if (!columnsToUse[columnName]) {\n columnsToUse[columnName] = columnDef;\n }\n }\n\n for (const [fieldName, fieldDef] of fields) {\n const columnName = toSnakeCase(fieldName);\n const existing = columnsToUse[columnName];\n if (!existing) {\n continue;\n }\n\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef as unknown as { sqlType?: string }).sqlType;\n const referenceKind = getReferenceKind(fieldDef);\n columnsToUse[columnName] = {\n ...existing,\n ...(sqlType\n ? { type: String(sqlType).toUpperCase() as SQLDataType }\n : {}),\n ...(referenceKind ? { referenceKind } : {}),\n };\n }\n }\n\n applyDecoratorSqlTypeOverrides(className, columnsToUse);\n return columnsToUse;\n}\n\nfunction getReferenceKind(\n fieldDef: FieldDefinition,\n): ColumnDefinition['referenceKind'] | undefined {\n if (\n (\n fieldDef as unknown as {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField ||\n fieldDef._meta?.__tenancy?.isTenantIdField\n ) {\n return 'tenantId';\n }\n\n if (fieldDef.type === 'foreignKey') {\n return 'foreignKey';\n }\n\n if (fieldDef.type === 'crossPackageRef') {\n return 'crossPackageRef';\n }\n\n return undefined;\n}\n\nfunction shouldEmitDefault(\n fieldDef: FieldDefinition,\n sqlType: SQLDataType,\n defaultValue: unknown,\n) {\n return !(\n getReferenceKind(fieldDef) === 'tenantId' &&\n sqlType === 'UUID' &&\n defaultValue === ''\n );\n}\n\n/**\n * Fallback base columns for a table whose contributing class carries no\n * manifest columns.\n *\n * These mirror what the manifest schema generators emit for the same table\n * (`generateSchemaFromManifest` / `generateSTISchemaFromManifest`), so a table\n * assembled from runtime field metadata alone has the same NOT NULL and\n * DEFAULT shape as one assembled from a manifest. Divergence here is what made\n * the merged table shape depend on which class registered first (#2372).\n */\nfunction createBaseColumns(\n registered: {\n config?: { idType?: 'uuid' | 'text' };\n },\n isSTI: boolean,\n): Record<string, ColumnDefinition> {\n const baseColumns: Record<string, ColumnDefinition> = {\n id: {\n type: registered.config?.idType === 'text' ? 'TEXT' : 'UUID',\n primaryKey: true,\n notNull: true,\n referenceKind: 'id',\n },\n slug: { type: 'TEXT', notNull: true },\n context: { type: 'TEXT', notNull: true, defaultValue: '' },\n created_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n updated_at: {\n type: 'TIMESTAMP',\n notNull: true,\n defaultValue: 'current_timestamp',\n },\n };\n\n // STI tables also carry the discriminator and the meta payload column\n // (issue #690: db:diff needs them to detect schema changes).\n if (isSTI) {\n baseColumns._meta_type = { type: 'TEXT', notNull: true };\n baseColumns._meta_data = { type: 'JSON', notNull: false };\n }\n\n return baseColumns;\n}\n\n/**\n * Get cached schema definition for a registered class\n *\n * @param name - Name of the registered class\n * @returns Schema definition or undefined if not found\n * @example\n * ```typescript\n * const schema = getSchema('Product');\n * console.log(schema.tableName); // 'products'\n * console.log(schema.ddl); // 'CREATE TABLE...'\n * ```\n */\nexport function getSchema(name: string): SchemaDefinition | undefined {\n // Issue #951: Use findClass for multi-strategy lookup\n const registered = findClass(name);\n return registered?.schema;\n}\n\n/**\n * Get SQL DDL statement for a registered class\n *\n * @param name - Name of the registered class\n * Cached manifest DDL contains abstract types and is not safe to execute on\n * PostgreSQL. New executable paths must pass a target engine. Omitting it is\n * retained for backward compatibility with consumers that only inspect the\n * legacy engine-neutral manifest string.\n *\n * @param engine - Database engine that will execute the DDL\n * @returns Engine-specific SQL DDL, or the legacy cached DDL when omitted\n * @example\n * ```typescript\n * const ddl = ObjectRegistry.getSchemaDDL('Product', 'postgres');\n * await db.query(ddl);\n * ```\n */\nexport function getSchemaDDL(\n name: string,\n engine?: DatabaseEngine,\n): string | undefined {\n const schema = getSchema(name);\n if (!schema) return undefined;\n if (engine && Object.keys(schema.columns).length === 0) {\n throw new Error(\n `Cannot materialize schema '${name}' for ${engine}: the manifest has no structured columns`,\n );\n }\n return engine\n ? getDDLStrategy(engine).generateCreateTable(schema)\n : schema.ddl;\n}\n\n/**\n * Get table name for a registered class\n *\n * @param name - Name of the registered class\n * @returns Table name or undefined if not found\n * @example\n * ```typescript\n * const tableName = getTableName('Product');\n * console.log(tableName); // 'products'\n * ```\n */\nexport function getTableName(name: string): string | undefined {\n // Check if this is a collection class - collections have their own tableName mapping\n const collectionTableName = getCollectionTableNames().get(name);\n if (collectionTableName) {\n return collectionTableName;\n }\n\n // For STI classes, return the STI base class's table name.\n // R5-canon: `getSTIBase` returns the qualified name; resolve `name`\n // (which may be simple) to its registration's qualified form for the\n // comparison.\n const stiBase = ObjectRegistry.getSTIBase(name);\n const registered = ObjectRegistry.getClass(name);\n const qualifiedName = registered?.qualifiedName ?? registered?.name ?? name;\n if (stiBase && stiBase !== qualifiedName) {\n return getSchema(stiBase)?.tableName;\n }\n return getSchema(name)?.tableName;\n}\n\nfunction withConflictIndex(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n indexes: IndexDefinition[],\n conflictColumns: string[],\n): IndexDefinition[] {\n if (\n conflictColumns.length === 0 ||\n !conflictColumns.every((column) => columns[column])\n ) {\n return indexes;\n }\n\n // `ON CONFLICT (id)` binds to the primary-key constraint itself; a second\n // unique index over the primary key column set adds nothing (#2359, A5).\n // Kept in step with SchemaGenerator.conflictColumnsArePrimaryKey().\n const primaryKeyColumns = Object.entries(columns)\n .filter(([, column]) => column.primaryKey === true)\n .map(([name]) => name);\n if (\n primaryKeyColumns.length > 0 &&\n primaryKeyColumns.length === conflictColumns.length &&\n primaryKeyColumns.every((column) => conflictColumns.includes(column))\n ) {\n return indexes;\n }\n\n const hasConflictIndex = indexes.some(\n (index) =>\n index.unique === true &&\n !index.where &&\n !index.jsonPath &&\n index.columns.length === conflictColumns.length &&\n index.columns.every((column) => conflictColumns.includes(column)),\n );\n if (hasConflictIndex) return indexes;\n\n // Same stable naming as SchemaGenerator (`schema/conflict-target.ts`), so\n // a manifest built before the runtime learned the tenant-aware default\n // (#2360) has its stale `<table>_slug_context_idx` REPLACED in place here\n // — the differ then swaps the live index by name — instead of a second,\n // suffixed unique index being appended beside the old global one.\n const tenantColumn = Object.entries(columns).find(\n ([, column]) => column.referenceKind === 'tenantId',\n )?.[0];\n // The composed name can exceed PostgreSQL's 63-byte limit on a long table.\n // Shortening here (rather than inside conflictIndexName) keeps the generator\n // paths, which run enforceIdentifierLimits() over their whole index list,\n // and this migrate leg agreeing on the final name (#2374).\n const name = shortenIdentifier(\n conflictIndexName(tableName, conflictColumns, tenantColumn),\n );\n const conflictIndex: IndexDefinition = {\n name,\n columns: conflictColumns,\n unique: true,\n };\n if (indexes.some((index) => index.name === name)) {\n return indexes.map((index) =>\n index.name === name ? conflictIndex : index,\n );\n }\n return [...indexes, conflictIndex];\n}\n\n/**\n * A registered class that contributes columns to one physical table.\n *\n * For a single-table-inheritance hierarchy every class in the hierarchy is a\n * contributor to the same table.\n */\ninterface TableContributor {\n registered: RegisteredClass;\n simpleName: string;\n qualifiedName: string;\n isSTI: boolean;\n /** True when this class is the STI base that owns the table. */\n isSTIBase: boolean;\n /** Inheritance depth; ancestors sort before descendants. */\n depth: number;\n /** Conflict-column lookup key (the STI base for STI members). */\n conflictKey: string;\n}\n\n/**\n * A merged physical table assembled from every class that contributes to it.\n */\ninterface MergedTableSchema {\n tableName: string;\n columns: Record<string, ColumnDefinition>;\n indexes: IndexDefinition[];\n ddl: string;\n isSTI: boolean;\n conflictColumns: string[];\n}\n\nfunction applyContributorForeignKeys(\n tableSchema: MergedTableSchema,\n contributor: TableContributor,\n): void {\n const conflictColumns = new Set(tableSchema.conflictColumns);\n for (const [fieldName, field] of contributor.registered.fields) {\n if (field.type !== 'foreignKey' || !field.related) continue;\n const columnName = toSnakeCase(fieldName);\n const column = tableSchema.columns[columnName];\n if (!column) continue;\n if (\n field._meta?.__tenancy?.isTenantIdField === true ||\n (\n field as FieldDefinition & {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField === true\n ) {\n column.foreignKey = undefined;\n continue;\n }\n const [targetName, declaredTargetColumn] = field.related.split('.');\n const targetBase = ObjectRegistry.getSTIBase(targetName) || targetName;\n const registeredTarget = ObjectRegistry.getClass(targetBase);\n const targetColumn =\n declaredTargetColumn ||\n Array.from(ObjectRegistry.getFields(targetBase).entries()).find(\n ([, targetField]) => targetField._meta?.primaryKey === true,\n )?.[0] ||\n 'id';\n if (registeredTarget && !field._meta?.sqlType) {\n const targetColumnName = toSnakeCase(targetColumn);\n const targetColumnType =\n registeredTarget.schema?.columns?.[targetColumnName]?.type ||\n (targetColumnName === 'id'\n ? registeredTarget.config.idType === 'text'\n ? 'TEXT'\n : 'UUID'\n : undefined);\n if (targetColumnType) {\n column.type = targetColumnType;\n }\n }\n if (field._meta?.constraint === false) {\n column.foreignKey = undefined;\n continue;\n }\n // A manifest may carry explicit actions that predate or differ from the\n // runtime decorator defaults. Merging runtime fields must not erase them.\n // The fallback produced from runtime fields, however, must be replaced so\n // conflict columns receive the same default CASCADE as app-side cleanup.\n const manifestForeignKey =\n contributor.registered.schema?.columns?.[columnName]?.foreignKey;\n if (manifestForeignKey) {\n column.foreignKey = manifestForeignKey;\n continue;\n }\n // A decorator-only runtime field has no authoritative physical target\n // until that target is registered. Scanner-produced manifests clear this\n // shape too; only an explicit manifest FK above may survive unloaded\n // runtime classes (the manifest-authority contract from #1120).\n if (!registeredTarget) {\n column.foreignKey = undefined;\n continue;\n }\n const targetTable =\n ObjectRegistry.getTableName(targetBase) ||\n classnameToTablename(targetBase);\n const { action } = resolveForeignKeyDeleteAction({\n declared: field._meta?.onDelete,\n isConflictColumn: conflictColumns.has(columnName),\n isTenantIdField: false,\n });\n column.foreignKey = {\n table: targetTable,\n column: toSnakeCase(targetColumn),\n onDelete: action,\n onUpdate: 'CASCADE',\n };\n }\n}\n\n/**\n * Resolve the physical table a registered class writes to.\n *\n * STI subclasses are folded onto their base's table. Returns `undefined` when\n * the class has no table (for example an unresolvable manifest stub).\n *\n * R5-canon: STI lookups use the qualified key so a colliding simple name in\n * another package cannot yield the wrong table strategy or STI base and move\n * this class's columns under that other package's table.\n */\nfunction resolveContributorTable(\n registered: RegisteredClass,\n fallbackName: string,\n): { tableName: string; contributor: TableContributor } | undefined {\n const simpleName = registered.name || fallbackName;\n const qualifiedName = registered.qualifiedName ?? simpleName;\n\n // STI subclasses loaded from external manifests can arrive with a null\n // tableName; registerFromManifest() then derives one from the class name.\n // Adopt the STI base's tableName instead so the subclass lands on the\n // shared table (issue #703).\n if (!registered.schema?.tableName && registered.extends) {\n if (ObjectRegistry.getTableStrategy(qualifiedName) === 'sti') {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName && stiBaseName !== qualifiedName) {\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n if (!registered.schema) {\n registered.schema = {\n tableName: '',\n ddl: '',\n columns: {},\n indexes: [],\n triggers: [],\n foreignKeys: [],\n dependencies: [],\n version: '',\n };\n }\n registered.schema.tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n if (!registered.schema?.tableName) {\n return undefined;\n }\n\n let tableName = registered.schema.tableName;\n const tableStrategy = ObjectRegistry.getTableStrategy(qualifiedName);\n const isSTI = tableStrategy === 'sti';\n let isSTIBase = isSTI;\n let conflictKey = qualifiedName;\n\n if (isSTI) {\n const stiBaseName = ObjectRegistry.getSTIBase(qualifiedName);\n if (stiBaseName) {\n conflictKey = stiBaseName;\n if (stiBaseName !== qualifiedName) {\n isSTIBase = false;\n // STI subclasses serialize to the base class's table even when they\n // carry a tableName of their own (issue #693).\n const stiBaseClass = findClass(stiBaseName);\n if (stiBaseClass?.schema?.tableName) {\n tableName = stiBaseClass.schema.tableName;\n }\n }\n }\n }\n\n return {\n tableName,\n contributor: {\n registered,\n simpleName,\n qualifiedName,\n isSTI,\n isSTIBase,\n depth: ObjectRegistry.getInheritanceChain(qualifiedName).length,\n conflictKey,\n },\n };\n}\n\n/**\n * Order the classes that share one table deterministically.\n *\n * The first contributor seeds the table: it supplies the base columns, the\n * `idType`, the conflict columns and the cached DDL, and its columns win every\n * merge conflict. Registration order must not decide that, or the same\n * hierarchy yields a different table shape depending on which class a manifest\n * happens to list first — child-first dropped NOT NULL and DEFAULT from the\n * base columns (#2372).\n *\n * Order: the STI base first, then ancestors before descendants, then by\n * qualified name so the result is a total order.\n */\nfunction sortTableContributors(contributors: TableContributor[]) {\n return [...contributors].sort((a, b) => {\n if (a.isSTIBase !== b.isSTIBase) {\n return a.isSTIBase ? -1 : 1;\n }\n if (a.depth !== b.depth) {\n return a.depth - b.depth;\n }\n return a.qualifiedName.localeCompare(b.qualifiedName);\n });\n}\n\n/**\n * Assemble every physical table from the classes that contribute to it.\n *\n * Shared by {@link getAllSchemas} and {@link getAllSchemasAsDefinitions} so\n * both produce the same merged shape. The result depends only on what is\n * registered, never on the order it was registered in.\n */\nfunction buildMergedTableSchemas(): Record<string, MergedTableSchema> {\n // Pass 1: group contributing classes by physical table.\n const contributorsByTable = new Map<string, TableContributor[]>();\n\n for (const [className, registered] of getClasses()) {\n // Collection classes have no table of their own; their schemas carry\n // collection properties (loaded, options, ...) rather than columns.\n if (\n isCollectionRegistration(\n className,\n registered,\n collectionRegistrationLookup,\n )\n ) {\n continue;\n }\n\n const resolved = resolveContributorTable(registered, className);\n if (!resolved) {\n continue;\n }\n\n const existing = contributorsByTable.get(resolved.tableName);\n if (existing) {\n existing.push(resolved.contributor);\n } else {\n contributorsByTable.set(resolved.tableName, [resolved.contributor]);\n }\n }\n\n // Pass 2: merge each table's contributors in deterministic order.\n const tableSchemas: Record<string, MergedTableSchema> = {};\n\n for (const [tableName, contributors] of contributorsByTable) {\n for (const contributor of sortTableContributors(contributors)) {\n const { registered, simpleName, isSTI } = contributor;\n const conflictColumns = ObjectRegistry.getConflictColumns(\n contributor.conflictKey,\n );\n\n // The manifest schema stays authoritative for the columns it defines.\n // Runtime field metadata backfills columns the manifest never had (for\n // example tenantScoped injections) and applies explicit sqlType\n // overrides, without erasing richer manifest metadata.\n const columnsToUse = mergeRuntimeFieldColumns(\n simpleName,\n registered.schema?.columns,\n registered.fields,\n { stiUnionColumns: isSTI, conflictColumns },\n );\n\n let tableSchema = tableSchemas[tableName];\n if (!tableSchema) {\n tableSchema = {\n tableName,\n columns: {\n ...createBaseColumns(registered, isSTI),\n ...columnsToUse,\n },\n indexes: [],\n ddl: registered.schema?.ddl || '',\n isSTI,\n conflictColumns,\n };\n tableSchemas[tableName] = tableSchema;\n } else {\n // Another class sharing this table (STI): add only columns the\n // seeding contributor did not already define.\n for (const [colName, colDef] of Object.entries(columnsToUse)) {\n if (!tableSchema.columns[colName]) {\n tableSchema.columns[colName] = colDef;\n }\n }\n }\n\n applyContributorForeignKeys(tableSchema, contributor);\n\n // Merge indexes, keeping the first definition of each name.\n const schemaIndexes = registered.schema?.indexes;\n if (schemaIndexes && schemaIndexes.length > 0) {\n const existingNames = new Set(\n tableSchema.indexes.map((index) => index.name),\n );\n for (const index of schemaIndexes) {\n // Legacy string-format indexes carry no columns and cannot be merged.\n if (typeof index === 'string') {\n continue;\n }\n if (!existingNames.has(index.name)) {\n tableSchema.indexes.push(index);\n existingNames.add(index.name);\n }\n }\n }\n }\n }\n\n return tableSchemas;\n}\n\n/**\n * Get all pre-generated schemas for explicit adapter bootstrap paths.\n *\n * Returns schemas in SDK SchemaProvider format for all registered classes.\n * Tooling and test helpers can pass these to `getDatabase()` when they want\n * to bootstrap schema before runtime. Core runtime no longer does this\n * implicitly.\n *\n * @returns Record of table names to schema definitions\n * @example\n * ```typescript\n * const schemas = ObjectRegistry.getAllSchemas('json');\n * const db = await getDatabase({ type: 'json', url: './data', schemas });\n * ```\n */\nexport function getAllSchemas(\n engine?: DatabaseEngine,\n): Record<string, { tableName: string; ddl: string; indexes?: string[] }> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to output format, regenerating DDL for merged schemas\n const schemas: Record<\n string,\n { tableName: string; ddl: string; indexes?: string[] }\n > = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n const engineIndexes = engine\n ? withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n )\n : tableSchema.indexes;\n const mergedSchema: SchemaDefinition = {\n tableName,\n ddl: tableSchema.ddl,\n columns: tableSchema.columns,\n indexes: engineIndexes,\n triggers: [],\n foreignKeys: [],\n version: '',\n dependencies: [],\n };\n mergedSchema.foreignKeys = schemaForeignKeys(mergedSchema);\n mergedSchema.dependencies = mergedSchema.foreignKeys\n .map((foreignKey) => foreignKey.referencesTable)\n .filter((dependency) => dependency !== tableName);\n\n // Generate DDL from merged columns (or use original DDL if columns are empty)\n let ddl: string;\n if (Object.keys(tableSchema.columns).length === 0 && tableSchema.ddl) {\n if (engine) {\n throw new Error(\n `Cannot materialize schema '${tableName}' for ${engine}: the manifest has no structured columns`,\n );\n }\n // Preserve legacy inspection of cached engine-neutral DDL. Executable\n // target-engine paths fail above rather than returning unsafe SQL.\n ddl = tableSchema.ddl;\n } else if (Object.keys(tableSchema.columns).length === 0) {\n // Skip schemas with no columns and no original DDL\n continue;\n } else if (engine) {\n // Target-engine materialization must route the complete structured\n // schema through its strategy. In particular, DuckDB/JSON require\n // UNIQUE constraints inline for ON CONFLICT, and every strategy owns\n // CHECK/default/index-expression rendering.\n ddl = getDDLStrategy(engine).generateCreateTable(mergedSchema);\n } else {\n ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n }\n\n // Convert index definitions to SQL strings for SDK compatibility\n let indexSQL: string[] | undefined;\n if (engineIndexes.length > 0) {\n indexSQL = engine\n ? getDDLStrategy(engine).generateIndexes(mergedSchema)\n : engineIndexes.map((idx) => {\n const indexType = idx.unique ? 'UNIQUE INDEX' : 'INDEX';\n const columnList = idx.columns\n .map((col) => quoteIdentifier(col))\n .join(', ');\n return `CREATE ${indexType} IF NOT EXISTS ${quoteIdentifier(\n idx.name,\n )} ON ${quoteIdentifier(tableName)} (${columnList});`;\n });\n }\n\n schemas[tableName] = {\n tableName,\n ddl,\n indexes: indexSQL,\n };\n }\n\n return schemas;\n}\n\n/**\n * Get all registered schemas as SchemaDefinition objects\n *\n * Similar to getAllSchemas(), but returns SchemaDefinition format suitable\n * for use with SchemaComparer (migrations/differ.ts).\n *\n * Key difference: Indexes are kept as IndexDefinition objects instead of\n * being converted to SQL strings.\n *\n * @returns Map of tableName to SchemaDefinition\n */\nexport function getAllSchemasAsDefinitions(): Record<string, SchemaDefinition> {\n // Step 1: Assemble every table from its contributing classes. The merge is\n // deterministic, so the shape does not depend on registration order (#2372).\n const tableSchemas = buildMergedTableSchemas();\n\n // Step 2: Convert to SchemaDefinition format\n const schemas: Record<string, SchemaDefinition> = {};\n\n for (const [tableName, tableSchema] of Object.entries(tableSchemas)) {\n if (Object.keys(tableSchema.columns).length === 0) {\n continue;\n }\n\n // Generate DDL from columns\n const ddl = generateDDLFromColumns(\n tableName,\n tableSchema.columns,\n tableSchema.isSTI,\n );\n const foreignKeys = schemaForeignKeys({\n columns: tableSchema.columns,\n foreignKeys: [],\n });\n\n schemas[tableName] = {\n tableName,\n ddl,\n columns: tableSchema.columns,\n indexes: withConflictIndex(\n tableName,\n tableSchema.columns,\n tableSchema.indexes,\n tableSchema.conflictColumns,\n ),\n triggers: [],\n foreignKeys,\n version: '',\n dependencies: foreignKeys\n .map((foreignKey) => foreignKey.referencesTable)\n .filter((dependency) => dependency !== tableName),\n };\n }\n\n return schemas;\n}\n\n/**\n * Generate DDL CREATE TABLE statement from columns\n *\n * Used internally by getAllSchemas() to regenerate DDL after merging\n * columns from multiple STI subtypes that share the same table.\n *\n * @param tableName - Name of the table\n * @param columns - Column definitions\n * @returns DDL CREATE TABLE statement\n */\nexport function generateDDLFromColumns(\n tableName: string,\n columns: Record<string, ColumnDefinition>,\n isSTI = false,\n engine?: DatabaseEngine,\n): string {\n let sql = `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(tableName)} (\\n`;\n\n const columnLines: string[] = [];\n for (const [columnName, columnDef] of Object.entries(columns)) {\n const parts: string[] = [];\n\n // Column name and type\n const strategy = engine ? getDDLStrategy(engine) : undefined;\n const columnType = strategy\n ? strategy.mapType(columnDef.type)\n : columnDef.type;\n parts.push(` ${quoteIdentifier(columnName)} ${columnType}`);\n\n // Primary key\n if (columnDef.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // Not null constraint\n if (columnDef.notNull) {\n parts.push('NOT NULL');\n }\n\n // Unique constraint (skip if primary key already implies uniqueness)\n if (columnDef.unique && !columnDef.primaryKey) {\n parts.push('UNIQUE');\n }\n\n // Default value\n if (columnDef.defaultValue !== undefined) {\n const defaultSQL = strategy\n ? strategy.formatDefaultValue(columnDef.defaultValue, columnDef.type)\n : formatDefaultValue(columnDef.defaultValue, columnDef.type);\n parts.push(`DEFAULT ${defaultSQL}`);\n }\n\n columnLines.push(parts.join(' '));\n }\n for (const foreignKey of schemaForeignKeys({ columns, foreignKeys: [] })) {\n columnLines.push(` ${renderForeignKeyConstraint(tableName, foreignKey)}`);\n }\n\n sql += columnLines.join(',\\n');\n\n // Add UNIQUE constraint for UPSERT operations\n // For STI tables: UNIQUE(slug, context, _meta_type) - different types can have same slug+context\n // For non-STI tables: UNIQUE(slug, context)\n if (columns.slug && columns.context) {\n if (isSTI && columns._meta_type) {\n sql += ',\\n UNIQUE(slug, context, _meta_type)';\n } else {\n sql += ',\\n UNIQUE(slug, context)';\n }\n }\n\n sql += '\\n);';\n\n return sql;\n}\n\n/**\n * Format default value for SQL DDL.\n *\n * Thin wrapper over the shared, injection-safe formatter\n * (`schema/sql-identifiers.ts`) so the registry schema-builder uses the same\n * rules as the DDL strategies and schema generator: an allowlist of SQL\n * keyword/function defaults (not \"contains `(`\"), type-driven literal quoting,\n * and no folding of a literal string `\"null\"` into the SQL NULL keyword.\n *\n * @param value - Default value\n * @param type - Column SQL type\n * @returns Formatted SQL default value\n */\nexport function formatDefaultValue(value: unknown, type: string): string {\n return formatDefaultValueShared(value, type);\n}\n\n/**\n * Options for {@link fieldsToColumns}.\n */\nexport interface FieldsToColumnsOptions {\n /**\n * Shape the columns for a single-table-inheritance table.\n *\n * An STI table holds the union of every subtype's fields, so a column that\n * only one subtype declares must stay nullable — rows of sibling subtypes\n * never populate it. This matches `generateSTISchemaFromManifest`, which\n * emits `notNull: false` for every non-system column on an STI table.\n * Declared defaults are still emitted.\n */\n stiUnionColumns?: boolean;\n /**\n * Physical column names that form the table's natural conflict key.\n * Undeclared delete actions on foreign-key members use the shared CASCADE\n * default, matching app-side relationship cleanup.\n */\n conflictColumns?: readonly string[];\n}\n\n/**\n * Convert a Map of field definitions to column definitions\n *\n * Used by getAllSchemas() to generate columns from fields when a class\n * has no pre-generated schema (e.g., STI subclasses registered from manifest).\n *\n * `required`, `default`, and `description` are read from either the top level\n * or `_meta`: registry-sourced fields normalize them into `_meta`, so reading\n * only the top level dropped NOT NULL and DEFAULT for every such field\n * (#2372).\n *\n * @param fields - Map of field name to field definition\n * @param options - Table-shape options (see {@link FieldsToColumnsOptions})\n * @returns Record of column name to column definition\n * @private\n */\nexport function fieldsToColumns(\n fields: Map<string, FieldDefinition>,\n options?: FieldsToColumnsOptions,\n): Record<string, ColumnDefinition> {\n const columns: Record<string, ColumnDefinition> = {};\n const conflictColumns = new Set(\n (options?.conflictColumns ?? []).map((column) => toSnakeCase(column)),\n );\n\n for (const [fieldName, fieldDef] of fields) {\n // Skip id, timestamps - they're on the base table\n if (\n fieldName === 'id' ||\n fieldName === 'created_at' ||\n fieldName === 'updated_at' ||\n fieldName === 'slug' ||\n fieldName === 'context'\n ) {\n continue;\n }\n\n // Skip transient fields (non-persisted)\n if (fieldDef.transient || fieldDef._meta?.transient) {\n continue;\n }\n\n // Skip relationship fields that don't create columns\n // oneToMany and manyToMany are relationship metadata, not actual database columns\n if (fieldDef.type === 'oneToMany' || fieldDef.type === 'manyToMany') {\n continue;\n }\n\n // Skip meta fields - they're stored in _meta_data JSONB column\n if (fieldDef.type === 'meta') {\n continue;\n }\n\n // Map field type to SQL type\n const sqlType =\n fieldDef._meta?.sqlType ||\n (fieldDef.type === 'crossPackageRef' &&\n (fieldDef._meta?.idType === 'text' ||\n (fieldDef as unknown as { idType?: string }).idType === 'text')\n ? 'TEXT'\n : mapFieldTypeToSQL(fieldDef.type));\n const normalizedSqlType = String(sqlType).toUpperCase() as SQLDataType;\n const referenceKind = getReferenceKind(fieldDef);\n\n const required = readFieldAttribute(fieldDef, 'required');\n const defaultValue = readFieldAttribute(fieldDef, 'default');\n const description = readFieldAttribute(fieldDef, 'description');\n\n const column: ColumnDefinition = {\n type: normalizedSqlType,\n referenceKind,\n notNull: options?.stiUnionColumns\n ? false\n : fieldDef._meta?.nullable\n ? false\n : Boolean(required),\n unique: fieldDef._meta?.unique || false,\n description: description as string | undefined,\n };\n\n // Handle default values\n if (\n defaultValue !== undefined &&\n shouldEmitDefault(fieldDef, normalizedSqlType, defaultValue)\n ) {\n column.defaultValue = defaultValue;\n }\n\n // Handle foreign keys\n if (\n fieldDef.type === 'foreignKey' &&\n fieldDef.related &&\n fieldDef._meta?.constraint !== false &&\n fieldDef._meta?.__tenancy?.isTenantIdField !== true &&\n !(\n fieldDef as FieldDefinition & {\n __tenancy?: { isTenantIdField?: boolean };\n }\n ).__tenancy?.isTenantIdField\n ) {\n const [table, columnName = 'id'] = fieldDef.related.split('.');\n const fieldMeta = fieldDef._meta as\n | {\n onDelete?: ForeignKeyAction;\n onUpdate?: ForeignKeyAction;\n }\n | undefined;\n column.foreignKey = {\n table: classnameToTablename(table),\n column: columnName,\n onDelete: resolveForeignKeyDeleteAction({\n declared: fieldMeta?.onDelete,\n isConflictColumn: conflictColumns.has(toSnakeCase(fieldName)),\n isTenantIdField: false,\n }).action,\n onUpdate:\n fieldMeta?.onUpdate === undefined\n ? 'CASCADE'\n : requireForeignKeyAction(\n fieldMeta.onUpdate,\n `${fieldName} ON UPDATE`,\n ),\n };\n }\n\n // Use snake_case for column names\n columns[toSnakeCase(fieldName)] = column;\n }\n\n return columns;\n}\n\n/**\n * Map field type to SQL data type\n * @private\n */\nexport function mapFieldTypeToSQL(\n fieldType: FieldDefinition['type'],\n): SQLDataType {\n switch (fieldType) {\n case 'text':\n return 'TEXT';\n case 'integer':\n return 'INTEGER';\n case 'decimal':\n return 'REAL';\n case 'boolean':\n return 'BOOLEAN';\n case 'datetime':\n return 'TIMESTAMP';\n case 'json':\n return 'JSON';\n case 'foreignKey':\n return 'UUID';\n case 'crossPackageRef':\n return 'UUID';\n default:\n return 'TEXT';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4CA,IAAM,+BAA6D;CACjE;CACA,qBAAqB,aAAa,cAChC,eAAe,kBAAkB,aAAa,SAAS;CACzD,sBAAsB,cACpB,eAAe,oBAAoB,SAAS;AAChD;AAEA,SAAS,+BACP,WACA,SACkC;CAClC,MAAM,aAAa,eAAe,mBAAmB,SAAS;CAC9D,IAAI,CAAC,WAAW,MACd,OAAO;CAGT,KAAK,MAAM,CAAC,WAAW,YAAY,YAAY;EAC7C,IAAI,CAAC,SAAS,SACZ;EAGF,MAAM,aAAa,YAAY,S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AmB,UAAU,SAAS;EAC3D,MAAM,cAAc,mBAAmB,UAAU,aAAa;EAE9D,MAAM,SAA2B;GAC/B,MAAM;GACN;GACA,SAAS,SAAS,kBACd,QACA,SAAS,OAAO,WACd,QACA,QAAQ,QAAQ;GACtB,QAAQ,SAAS,OAAO,UAAU;GACrB;EACf;EAGA,IACE,iBAAiB,KAAA,KACjB,kBAAkB,UAAU,mBAAmB,YAAY,GAE3D,OAAO,eAAe;EAIxB,IACE,SAAS,SAAS,gBAClB,SAAS,WACT,SAAS,OAAO,eAAe,SAC/B,SAAS,OAAO,WAAW,oBAAoB,QAC/C,CACE,SAGA,WAAW,iBACb;GACA,MAAM,CAAC,OAAO,aAAa,QAAQ,SAAS,QAAQ,MAAM,GAAG;GAC7D,MAAM,YAAY,SAAS;GAM3B,OAAO,aAAa;IAClB,OAAO,qBAAqB,KAAK;IACjC,QAAQ;IACR,UAAU,8BAA8B;KACtC,UAAU,WAAW;KACrB,kBAAkB,gBAAgB,IAAI,YAAY,SAAS,CAAC;KAC5D,iBAAiB;IACnB,CAAC,CAAC,CAAC;IACH,UACE,WAAW,aAAa,KAAA,IACpB,YACA,wBACE,UAAU,UACV,GAAG,UAAU,WACf;GACR;EACF;EAGA,QAAQ,YAAY,SAAS,KAAK;CACpC;CAEA,OAAO;AACT;;;;;AAMA,SAAgB,kBACd,WACa;CACb,QAAQ,WAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,cACH,OAAO;EACT,KAAK,mBACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -792,13 +792,11 @@ export declare class ObjectRegistry {
792
792
  * Foreign-key cycles (e.g. smrt-chat's ChatMessage.threadId -> ChatThread
793
793
  * and ChatThread.rootMessageId -> ChatMessage) are BROKEN rather than
794
794
  * treated as a fatal error: when a back-edge is encountered the recursion
795
- * stops there, so every class still appears in the returned order. SMRT does
796
- * not emit real DB `FOREIGN KEY` constraints in its generated CREATE TABLE
797
- * DDL, so a table can be created before its cyclic reference target exists —
798
- * the reference is satisfied once both tables are present. This mirrors the
799
- * standard RDBMS approach (create tables first, wire cyclic references
800
- * afterward) and matches SchemaManager.sortByDependencies, which already
801
- * tolerates cycles. See issue #1333.
795
+ * stops there, so every class still appears in the returned order. The schema
796
+ * creation planner then handles physical constraints per engine: SQLite
797
+ * keeps cyclic constraints inline, PostgreSQL defers them until both tables
798
+ * exist, and DuckDB refuses unsupported cycles with actionable guidance.
799
+ * See issues #1333 and #2413.
802
800
  *
803
801
  * @returns Array of class names in initialization order. Every registered
804
802
  * class appears exactly once; cycle back-edges are dropped from the
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAIH,OAAO,EACL,cAAc,EAEd,KAAK,qBAAqB,EAC3B,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,EACV,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAUhD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAS3C,OAAO,EAIL,KAAK,kBAAkB,EAExB,MAAM,wBAAwB,CAAC;AA8DhC,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,EACrB,iBAAiB,EAClB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EACV,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,EACrB,mBAA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