@famgia/omnify-core 0.0.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors/omnify-error.ts","../src/errors/formatter.ts","../src/errors/factories.ts","../src/schema/loader.ts","../src/validation/validator.ts","../src/plugins/manager.ts","../src/plugins/expander.ts","../src/api/omnify.ts","../src/api/metadata.ts"],"sourcesContent":["/**\n * @famgia/omnify-core\n * Schema loading, validation, and transformation\n *\n * This package provides the core functionality for omnify-schema:\n * - Error handling with file:line:message:suggestion format\n * - Schema loading and validation (coming soon)\n * - Plugin management (coming soon)\n * - Configuration loading (coming soon)\n */\n\n// ============================================================================\n// Re-export types from @famgia/omnify-types for convenience\n// ============================================================================\n\nexport type {\n // Schema types\n SchemaDefinition,\n PropertyDefinition,\n PropertyType,\n AssociationRelation,\n SchemaOptions,\n LoadedSchema,\n SchemaCollection,\n // Config types\n OmnifyConfig,\n DatabaseConfig,\n OutputConfig,\n // Plugin types\n OmnifyPlugin,\n CustomTypeDefinition,\n // Error types\n ErrorCode,\n ErrorLocation,\n OmnifyErrorInfo,\n Result,\n} from '@famgia/omnify-types';\n\nexport { ok, err } from '@famgia/omnify-types';\n\n// ============================================================================\n// Error handling\n// ============================================================================\n\nexport {\n // Error class\n OmnifyError,\n // Formatter\n formatError,\n formatErrorSummary,\n formatErrorPlain,\n getExitCode,\n type FormatOptions,\n // Factory functions - Config errors\n configError,\n configNotFoundError,\n invalidConfigError,\n missingConfigFieldError,\n // Factory functions - Schema parsing errors\n schemaParseError,\n schemaNotFoundError,\n yamlSyntaxError,\n jsonSyntaxError,\n // Factory functions - Validation errors\n validationError,\n invalidPropertyTypeError,\n missingFieldError,\n invalidAssociationTargetError,\n circularReferenceError,\n duplicateSchemaError,\n // Factory functions - Plugin errors\n pluginError,\n pluginNotFoundError,\n pluginTypeConflictError,\n // Factory functions - Atlas errors\n atlasError,\n atlasNotFoundError,\n // Factory functions - Generation errors\n generationError,\n outputWriteError,\n // Factory functions - Internal errors\n internalError,\n notImplementedError,\n} from './errors/index.js';\n\n// ============================================================================\n// Schema loading\n// ============================================================================\n\nexport {\n // Loader functions\n loadSchema,\n loadSchemas,\n // Parser utilities\n parseYamlSchema,\n parseJsonSchema,\n fileNameToSchemaName,\n // Types\n type LoadSchemaOptions,\n type LoadSchemasOptions,\n} from './schema/index.js';\n\n// ============================================================================\n// Schema validation\n// ============================================================================\n\nexport {\n // Main validation functions\n validateSchema,\n validateSchemas,\n // Individual validators\n validateProperties,\n validatePropertyType,\n validateAssociations,\n validateOptions,\n validateEnumSchema,\n // Types\n type SchemaValidationResult,\n type ValidationResult,\n type ValidationOptions,\n} from './validation/index.js';\n\n// ============================================================================\n// Plugin management\n// ============================================================================\n\nexport {\n // Plugin Manager\n PluginManager,\n createPluginManager,\n // Compound Type Expansion\n expandProperty,\n expandSchemaProperties,\n expandSchema,\n expandSchemas,\n getTypeInfo,\n isCompoundType,\n getCustomTypeNames,\n // Types\n type RegisteredType,\n type PluginRegistry,\n type PluginManagerOptions,\n type PluginRegistrationResult,\n type ExpandedProperty,\n} from './plugins/index.js';\n\n// ============================================================================\n// Programmatic API\n// ============================================================================\n\nexport {\n // Main API\n Omnify,\n createOmnify,\n // Types\n type OmnifyOptions,\n type OmnifyLogger,\n type LoadResult,\n type DiffOperationResult,\n type GenerateOptions,\n type GenerateResult,\n type GeneratedFile,\n type SchemaError,\n type SchemaWarning,\n type SchemaMetadata,\n type PropertyMetadata,\n type AssociationMetadata,\n type SchemaIntrospection,\n // Metadata utilities\n getSchemaMetadata,\n getPropertyMetadata,\n getAssociationMetadata,\n introspectSchema,\n introspectSchemas,\n getSchemaNames,\n getSchemasByKind,\n getEntitySchemas,\n getEnumSchemas,\n getSchemasByGroup,\n getGroups,\n findReferencingSchemas,\n findReferencedSchemas,\n getRelationshipGraph,\n hasCircularReferences,\n getTopologicalOrder,\n} from './api/index.js';\n","/**\n * @famgia/omnify-core - OmnifyError Class\n *\n * Base error class for all omnify errors with file:line:message:suggestion format.\n */\n\nimport type { ErrorCode, ErrorLocation, OmnifyErrorInfo } from '@famgia/omnify-types';\n\n/**\n * Base error class for omnify-schema.\n * Provides consistent error formatting with source location and suggestions.\n *\n * @example\n * ```typescript\n * throw new OmnifyError(\n * \"Invalid property type 'Stringg'\",\n * 'E201',\n * { file: 'schemas/User.yaml', line: 15, column: 10 },\n * \"Did you mean 'String'?\"\n * );\n * ```\n */\nexport class OmnifyError extends Error {\n /** Error code (e.g., 'E201') */\n readonly code: ErrorCode;\n\n /** Source location where the error occurred */\n readonly location?: ErrorLocation;\n\n /** Suggested fix for the error */\n readonly suggestion?: string;\n\n /** Additional context or details */\n readonly details?: Record<string, unknown>;\n\n /** Original error if this wraps another error */\n override readonly cause?: Error;\n\n constructor(\n message: string,\n code: ErrorCode,\n location?: ErrorLocation,\n suggestion?: string,\n options?: {\n details?: Record<string, unknown>;\n cause?: Error;\n }\n ) {\n super(message);\n this.name = 'OmnifyError';\n this.code = code;\n\n // Only assign optional properties when they have values\n // (required for exactOptionalPropertyTypes)\n if (location !== undefined) {\n this.location = location;\n }\n if (suggestion !== undefined) {\n this.suggestion = suggestion;\n }\n if (options?.details !== undefined) {\n this.details = options.details;\n }\n if (options?.cause !== undefined) {\n this.cause = options.cause;\n }\n\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, OmnifyError);\n }\n }\n\n /**\n * Creates an OmnifyError from an OmnifyErrorInfo object.\n */\n static fromInfo(info: OmnifyErrorInfo): OmnifyError {\n const options: { details?: Record<string, unknown>; cause?: Error } = {};\n if (info.details !== undefined) {\n options.details = info.details;\n }\n if (info.cause !== undefined) {\n options.cause = info.cause;\n }\n\n return new OmnifyError(\n info.message,\n info.code,\n info.location,\n info.suggestion,\n Object.keys(options).length > 0 ? options : undefined\n );\n }\n\n /**\n * Wraps an unknown error as an OmnifyError.\n * Useful for catching and re-throwing with context.\n */\n static wrap(\n error: unknown,\n code: ErrorCode = 'E901',\n location?: ErrorLocation\n ): OmnifyError {\n if (error instanceof OmnifyError) {\n return error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n\n if (error instanceof Error) {\n return new OmnifyError(message, code, location, undefined, { cause: error });\n }\n return new OmnifyError(message, code, location);\n }\n\n /**\n * Converts to OmnifyErrorInfo for serialization.\n */\n toInfo(): OmnifyErrorInfo {\n const info: OmnifyErrorInfo = {\n code: this.code,\n message: this.message,\n };\n\n // Only include optional properties if they have values\n if (this.location !== undefined) {\n (info as { location: ErrorLocation }).location = this.location;\n }\n if (this.suggestion !== undefined) {\n (info as { suggestion: string }).suggestion = this.suggestion;\n }\n if (this.details !== undefined) {\n (info as { details: Record<string, unknown> }).details = this.details;\n }\n if (this.cause !== undefined) {\n (info as { cause: Error }).cause = this.cause;\n }\n\n return info;\n }\n\n /**\n * Returns a formatted string representation.\n * Format: \"Error [CODE]: message\\n --> file:line:column\"\n */\n override toString(): string {\n const parts: string[] = [];\n\n // Header: Error [E201]: message\n parts.push(`Error [${this.code}]: ${this.message}`);\n\n // Location: --> file:line:column\n if (this.location?.file) {\n const loc = this.location;\n let locationStr = ` --> ${loc.file}`;\n if (loc.line !== undefined) {\n locationStr += `:${loc.line}`;\n if (loc.column !== undefined) {\n locationStr += `:${loc.column}`;\n }\n }\n parts.push(locationStr);\n }\n\n // Suggestion\n if (this.suggestion) {\n parts.push(` Suggestion: ${this.suggestion}`);\n }\n\n return parts.join('\\n');\n }\n\n /**\n * Returns the file path from location, if available.\n */\n get file(): string | undefined {\n return this.location?.file;\n }\n\n /**\n * Returns the line number from location, if available.\n */\n get line(): number | undefined {\n return this.location?.line;\n }\n\n /**\n * Returns the column number from location, if available.\n */\n get column(): number | undefined {\n return this.location?.column;\n }\n}\n","/**\n * @famgia/omnify-core - Error Formatter\n *\n * Formats errors for CLI output with optional ANSI colors.\n */\n\nimport type { OmnifyError } from './omnify-error.js';\n\n/**\n * ANSI color codes for terminal output.\n */\nconst colors = {\n reset: '\\x1b[0m',\n bold: '\\x1b[1m',\n dim: '\\x1b[2m',\n red: '\\x1b[31m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n cyan: '\\x1b[36m',\n gray: '\\x1b[90m',\n} as const;\n\n/**\n * Options for error formatting.\n */\nexport interface FormatOptions {\n /** Enable ANSI color codes */\n readonly color?: boolean;\n /** Show source context lines */\n readonly showContext?: boolean;\n /** Number of context lines to show */\n readonly contextLines?: number;\n /** Source file content (for showing context) */\n readonly sourceContent?: string;\n}\n\n/**\n * Applies color if enabled, otherwise returns the text as-is.\n */\nfunction colorize(\n text: string,\n colorCode: string,\n enabled: boolean\n): string {\n return enabled ? `${colorCode}${text}${colors.reset}` : text;\n}\n\n/**\n * Formats an OmnifyError for CLI output.\n *\n * @example Output:\n * ```\n * error[E201]: Invalid property type 'Stringg'\n * --> schemas/User.yaml:15:10\n * |\n * 15 | type: Stringg\n * | ^^^^^^^ Did you mean 'String'?\n * |\n * = suggestion: Use one of: String, Int, Boolean, Text, ...\n * ```\n */\nexport function formatError(\n error: OmnifyError,\n options: FormatOptions = {}\n): string {\n const {\n color = true,\n showContext = true,\n contextLines = 2,\n sourceContent,\n } = options;\n\n const lines: string[] = [];\n\n // Header: error[E201]: message\n const errorLabel = colorize('error', colors.red + colors.bold, color);\n const code = colorize(`[${error.code}]`, colors.red, color);\n const message = colorize(error.message, colors.bold, color);\n lines.push(`${errorLabel}${code}: ${message}`);\n\n // Location: --> file:line:column\n const locFile = error.location?.file;\n if (locFile !== undefined) {\n const loc = error.location;\n let locationStr = colorize(' --> ', colors.blue, color);\n locationStr += colorize(locFile, colors.cyan, color);\n if (loc?.line !== undefined) {\n locationStr += `:${loc.line}`;\n if (loc.column !== undefined) {\n locationStr += `:${loc.column}`;\n }\n }\n lines.push(locationStr);\n }\n\n // Source context\n if (\n showContext &&\n sourceContent &&\n error.location?.line !== undefined\n ) {\n const contextOutput = formatSourceContext(\n sourceContent,\n error.location.line,\n error.location.column,\n error.suggestion,\n contextLines,\n color\n );\n lines.push(contextOutput);\n }\n\n // Suggestion (if no source context shown)\n if (error.suggestion && (!showContext || !sourceContent)) {\n const suggestionLabel = colorize(' = suggestion:', colors.cyan, color);\n lines.push(`${suggestionLabel} ${error.suggestion}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats source context around the error location.\n */\nfunction formatSourceContext(\n source: string,\n errorLine: number,\n errorColumn: number | undefined,\n suggestion: string | undefined,\n contextCount: number,\n colorEnabled: boolean\n): string {\n const sourceLines = source.split('\\n');\n const startLine = Math.max(1, errorLine - contextCount);\n const endLine = Math.min(sourceLines.length, errorLine + contextCount);\n const gutterWidth = String(endLine).length;\n\n const output: string[] = [];\n\n // Empty gutter line\n output.push(colorize(`${' '.repeat(gutterWidth)} |`, colors.blue, colorEnabled));\n\n for (let i = startLine; i <= endLine; i++) {\n const lineContent = sourceLines[i - 1] ?? '';\n const lineNum = String(i).padStart(gutterWidth, ' ');\n const gutter = colorize(`${lineNum} |`, colors.blue, colorEnabled);\n\n output.push(`${gutter} ${lineContent}`);\n\n // Add underline on error line\n if (i === errorLine && errorColumn !== undefined) {\n const underlineGutter = colorize(\n `${' '.repeat(gutterWidth)} |`,\n colors.blue,\n colorEnabled\n );\n const spaces = ' '.repeat(errorColumn - 1);\n const underline = colorize('^', colors.red, colorEnabled);\n let underlineLine = `${underlineGutter} ${spaces}${underline}`;\n\n if (suggestion) {\n underlineLine += ` ${colorize(suggestion, colors.yellow, colorEnabled)}`;\n }\n\n output.push(underlineLine);\n }\n }\n\n // Empty gutter line\n output.push(colorize(`${' '.repeat(gutterWidth)} |`, colors.blue, colorEnabled));\n\n return output.join('\\n');\n}\n\n/**\n * Formats multiple errors as a summary.\n */\nexport function formatErrorSummary(\n errors: readonly OmnifyError[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n\n if (errors.length === 0) {\n return '';\n }\n\n const formattedErrors = errors.map((e) => formatError(e, options));\n const summary = colorize(\n `\\nFound ${errors.length} error${errors.length === 1 ? '' : 's'}`,\n colors.red + colors.bold,\n color\n );\n\n return formattedErrors.join('\\n\\n') + summary;\n}\n\n/**\n * Formats an error for plain text output (no colors).\n */\nexport function formatErrorPlain(error: OmnifyError): string {\n return formatError(error, { color: false, showContext: false });\n}\n\n/**\n * Gets the exit code for an error based on its code category.\n */\nexport function getExitCode(error: OmnifyError): number {\n const category = error.code.charAt(1);\n\n switch (category) {\n case '0': // Configuration errors\n return 3;\n case '2': // Validation errors\n return 2;\n default: // All other errors\n return 1;\n }\n}\n","/**\n * @famgia/omnify-core - Error Factory Functions\n *\n * Convenient factory functions for creating common error types.\n */\n\nimport type { ErrorCode, ErrorLocation } from '@famgia/omnify-types';\nimport { OmnifyError } from './omnify-error.js';\n\n/**\n * Helper to build ErrorLocation objects safely with exactOptionalPropertyTypes.\n */\nfunction buildLocation(\n file: string,\n line?: number,\n column?: number\n): ErrorLocation {\n const loc: ErrorLocation = { file };\n if (line !== undefined) {\n (loc as { line: number }).line = line;\n }\n if (column !== undefined) {\n (loc as { column: number }).column = column;\n }\n return loc;\n}\n\n/**\n * Helper to build options object safely.\n */\nfunction buildOptions(cause?: Error): { cause: Error } | undefined {\n return cause !== undefined ? { cause } : undefined;\n}\n\n// ============================================================================\n// Configuration Errors (E0xx)\n// ============================================================================\n\n/**\n * Creates a configuration error.\n */\nexport function configError(\n message: string,\n code: ErrorCode = 'E002',\n suggestion?: string\n): OmnifyError {\n return new OmnifyError(message, code, undefined, suggestion);\n}\n\n/**\n * Config file not found error.\n */\nexport function configNotFoundError(configPath: string): OmnifyError {\n return new OmnifyError(\n `Configuration file not found: ${configPath}`,\n 'E001',\n { file: configPath },\n 'Run `omnify init` to create a configuration file'\n );\n}\n\n/**\n * Invalid config format error.\n */\nexport function invalidConfigError(\n message: string,\n configPath: string\n): OmnifyError {\n return new OmnifyError(\n message,\n 'E002',\n { file: configPath },\n 'Check your omnify.config.ts for syntax errors'\n );\n}\n\n/**\n * Missing required config field error.\n */\nexport function missingConfigFieldError(\n field: string,\n configPath: string\n): OmnifyError {\n return new OmnifyError(\n `Missing required configuration field: ${field}`,\n 'E003',\n { file: configPath },\n `Add '${field}' to your configuration file`\n );\n}\n\n// ============================================================================\n// Schema Parsing Errors (E1xx)\n// ============================================================================\n\n/**\n * Creates a schema parsing error.\n */\nexport function schemaParseError(\n message: string,\n location: ErrorLocation,\n suggestion?: string\n): OmnifyError {\n return new OmnifyError(message, 'E102', location, suggestion);\n}\n\n/**\n * Schema file not found error.\n */\nexport function schemaNotFoundError(schemaPath: string): OmnifyError {\n return new OmnifyError(\n `Schema file not found: ${schemaPath}`,\n 'E101',\n { file: schemaPath },\n 'Check that the file exists and the path is correct'\n );\n}\n\n/**\n * Invalid YAML syntax error.\n */\nexport function yamlSyntaxError(\n message: string,\n file: string,\n line?: number,\n column?: number\n): OmnifyError {\n return new OmnifyError(\n `Invalid YAML syntax: ${message}`,\n 'E102',\n buildLocation(file, line, column),\n 'Check for proper indentation and YAML syntax'\n );\n}\n\n/**\n * Invalid JSON syntax error.\n */\nexport function jsonSyntaxError(\n message: string,\n file: string,\n line?: number,\n column?: number\n): OmnifyError {\n return new OmnifyError(\n `Invalid JSON syntax: ${message}`,\n 'E103',\n buildLocation(file, line, column),\n 'Check for proper JSON syntax (quotes, commas, brackets)'\n );\n}\n\n// ============================================================================\n// Schema Validation Errors (E2xx)\n// ============================================================================\n\n/**\n * Creates a schema validation error.\n */\nexport function validationError(\n message: string,\n location: ErrorLocation,\n suggestion?: string\n): OmnifyError {\n return new OmnifyError(message, 'E202', location, suggestion);\n}\n\n/**\n * Invalid property type error.\n */\nexport function invalidPropertyTypeError(\n typeName: string,\n location: ErrorLocation,\n validTypes?: readonly string[]\n): OmnifyError {\n const suggestion = validTypes\n ? `Use one of: ${validTypes.slice(0, 5).join(', ')}${validTypes.length > 5 ? ', ...' : ''}`\n : undefined;\n\n return new OmnifyError(\n `Invalid property type '${typeName}'`,\n 'E201',\n location,\n suggestion\n );\n}\n\n/**\n * Missing required field error.\n */\nexport function missingFieldError(\n field: string,\n location: ErrorLocation\n): OmnifyError {\n return new OmnifyError(\n `Missing required field: ${field}`,\n 'E202',\n location,\n `Add '${field}' to the schema definition`\n );\n}\n\n/**\n * Invalid association target error.\n */\nexport function invalidAssociationTargetError(\n target: string,\n location: ErrorLocation,\n availableSchemas?: readonly string[]\n): OmnifyError {\n const suggestion = availableSchemas\n ? `Available schemas: ${availableSchemas.slice(0, 5).join(', ')}${availableSchemas.length > 5 ? ', ...' : ''}`\n : 'Check that the target schema exists';\n\n return new OmnifyError(\n `Invalid association target '${target}'`,\n 'E203',\n location,\n suggestion\n );\n}\n\n/**\n * Circular reference error.\n */\nexport function circularReferenceError(\n path: readonly string[],\n location: ErrorLocation\n): OmnifyError {\n return new OmnifyError(\n `Circular reference detected: ${path.join(' -> ')}`,\n 'E204',\n location,\n 'Remove the circular dependency or use a unidirectional relationship'\n );\n}\n\n/**\n * Duplicate schema name error.\n */\nexport function duplicateSchemaError(\n name: string,\n location: ErrorLocation,\n existingLocation?: ErrorLocation\n): OmnifyError {\n const suggestion = existingLocation?.file\n ? `Schema already defined in ${existingLocation.file}`\n : 'Rename one of the schemas to avoid the conflict';\n\n return new OmnifyError(\n `Duplicate schema name '${name}'`,\n 'E205',\n location,\n suggestion\n );\n}\n\n// ============================================================================\n// Plugin Errors (E3xx)\n// ============================================================================\n\n/**\n * Creates a plugin error.\n */\nexport function pluginError(\n message: string,\n pluginName: string,\n cause?: Error\n): OmnifyError {\n return new OmnifyError(\n message,\n 'E302',\n undefined,\n `Check the plugin '${pluginName}' for issues`,\n buildOptions(cause)\n );\n}\n\n/**\n * Plugin not found error.\n */\nexport function pluginNotFoundError(pluginName: string): OmnifyError {\n return new OmnifyError(\n `Plugin not found: ${pluginName}`,\n 'E301',\n undefined,\n `Install the plugin with: npm install ${pluginName}`\n );\n}\n\n/**\n * Plugin type conflict error.\n */\nexport function pluginTypeConflictError(\n typeName: string,\n pluginA: string,\n pluginB: string\n): OmnifyError {\n return new OmnifyError(\n `Type '${typeName}' is defined by multiple plugins: ${pluginA}, ${pluginB}`,\n 'E304',\n undefined,\n 'Remove one of the conflicting plugins or rename the type'\n );\n}\n\n// ============================================================================\n// Atlas/Database Errors (E4xx)\n// ============================================================================\n\n/**\n * Creates an Atlas error.\n */\nexport function atlasError(\n message: string,\n cause?: Error\n): OmnifyError {\n return new OmnifyError(\n message,\n 'E402',\n undefined,\n 'Check Atlas CLI output for details',\n buildOptions(cause)\n );\n}\n\n/**\n * Atlas CLI not found error.\n */\nexport function atlasNotFoundError(): OmnifyError {\n return new OmnifyError(\n 'Atlas CLI not found',\n 'E401',\n undefined,\n 'Install Atlas CLI: https://atlasgo.io/getting-started'\n );\n}\n\n// ============================================================================\n// Generation Errors (E5xx)\n// ============================================================================\n\n/**\n * Creates a generation error.\n */\nexport function generationError(\n message: string,\n outputPath?: string,\n cause?: Error\n): OmnifyError {\n return new OmnifyError(\n message,\n 'E501',\n outputPath ? { file: outputPath } : undefined,\n undefined,\n buildOptions(cause)\n );\n}\n\n/**\n * Output write error.\n */\nexport function outputWriteError(\n outputPath: string,\n cause?: Error\n): OmnifyError {\n return new OmnifyError(\n `Failed to write output file: ${outputPath}`,\n 'E503',\n { file: outputPath },\n 'Check file permissions and disk space',\n buildOptions(cause)\n );\n}\n\n// ============================================================================\n// Internal Errors (E9xx)\n// ============================================================================\n\n/**\n * Creates an internal/unexpected error.\n */\nexport function internalError(\n message: string,\n cause?: Error\n): OmnifyError {\n return new OmnifyError(\n message,\n 'E901',\n undefined,\n 'This is a bug. Please report it at https://github.com/omnify/omnify-schema/issues',\n buildOptions(cause)\n );\n}\n\n/**\n * Not implemented error.\n */\nexport function notImplementedError(feature: string): OmnifyError {\n return new OmnifyError(\n `Feature not implemented: ${feature}`,\n 'E902',\n undefined,\n 'This feature is planned for a future release'\n );\n}\n","/**\n * @famgia/omnify-core - Schema Loader\n *\n * Load and parse YAML/JSON schema files into internal representation.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport yaml from 'js-yaml';\nimport type {\n SchemaDefinition,\n LoadedSchema,\n SchemaCollection,\n PropertyDefinition,\n SchemaOptions,\n} from '@famgia/omnify-types';\nimport {\n schemaNotFoundError,\n yamlSyntaxError,\n jsonSyntaxError,\n duplicateSchemaError,\n} from '../errors/index.js';\n\n/**\n * Options for loading schemas.\n */\nexport interface LoadSchemaOptions {\n /** Base directory for calculating relative paths */\n readonly baseDir?: string;\n}\n\n/**\n * Options for loading a directory of schemas.\n */\nexport interface LoadSchemasOptions {\n /** File extensions to include (default: ['.yaml', '.yml']) */\n readonly extensions?: readonly string[];\n /** Whether to load recursively from subdirectories (default: true) */\n readonly recursive?: boolean;\n}\n\n/**\n * Converts a file name to a schema name (PascalCase).\n *\n * @example\n * fileNameToSchemaName('user-profile.yaml') // 'UserProfile'\n * fileNameToSchemaName('User.yaml') // 'User'\n * fileNameToSchemaName('order_item.yml') // 'OrderItem'\n */\nexport function fileNameToSchemaName(fileName: string): string {\n const baseName = path.basename(fileName, path.extname(fileName));\n return baseName\n .split(/[-_]/)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())\n .join('');\n}\n\n/**\n * Parses YAML content into a SchemaDefinition.\n *\n * @param content - Raw YAML content\n * @param filePath - File path for error reporting\n * @returns Parsed schema definition\n * @throws OmnifyError if YAML is invalid\n */\nexport function parseYamlSchema(\n content: string,\n filePath: string\n): SchemaDefinition {\n try {\n const parsed = yaml.load(content) as Record<string, unknown> | null;\n\n if (parsed === null || typeof parsed !== 'object') {\n throw yamlSyntaxError('Schema must be a YAML object', filePath);\n }\n\n return buildSchemaDefinition(parsed);\n } catch (error) {\n if (error instanceof yaml.YAMLException) {\n const line = error.mark?.line !== undefined ? error.mark.line + 1 : undefined;\n const column = error.mark?.column !== undefined ? error.mark.column + 1 : undefined;\n throw yamlSyntaxError(error.reason || error.message, filePath, line, column);\n }\n throw error;\n }\n}\n\n/**\n * Parses JSON content into a SchemaDefinition.\n *\n * @param content - Raw JSON content\n * @param filePath - File path for error reporting\n * @returns Parsed schema definition\n * @throws OmnifyError if JSON is invalid\n */\nexport function parseJsonSchema(\n content: string,\n filePath: string\n): SchemaDefinition {\n try {\n const parsed = JSON.parse(content) as Record<string, unknown> | null;\n\n if (parsed === null || typeof parsed !== 'object') {\n throw jsonSyntaxError('Schema must be a JSON object', filePath);\n }\n\n return buildSchemaDefinition(parsed);\n } catch (error) {\n if (error instanceof SyntaxError) {\n // Try to extract line/column from error message\n const match = error.message.match(/position (\\d+)/);\n const positionStr = match?.[1];\n const position = positionStr !== undefined ? parseInt(positionStr, 10) : undefined;\n let line: number | undefined;\n let column: number | undefined;\n\n if (position !== undefined) {\n // Calculate line and column from position\n const beforeError = content.substring(0, position);\n const lines = beforeError.split('\\n');\n line = lines.length;\n const lastLine = lines[lines.length - 1];\n column = (lastLine !== undefined ? lastLine.length : 0) + 1;\n }\n\n throw jsonSyntaxError(error.message, filePath, line, column);\n }\n throw error;\n }\n}\n\n/**\n * Builds a SchemaDefinition from parsed YAML data.\n * Handles exactOptionalPropertyTypes correctly.\n */\nfunction buildSchemaDefinition(\n data: Record<string, unknown>\n): SchemaDefinition {\n const schema: SchemaDefinition = {};\n\n // Handle optional properties with conditional assignment\n if (data.kind !== undefined) {\n (schema as { kind: 'object' | 'enum' }).kind = data.kind as 'object' | 'enum';\n }\n\n if (data.displayName !== undefined && typeof data.displayName === 'string') {\n (schema as { displayName: string }).displayName = data.displayName;\n }\n\n if (data.titleIndex !== undefined && typeof data.titleIndex === 'string') {\n (schema as { titleIndex: string }).titleIndex = data.titleIndex;\n }\n\n if (data.group !== undefined && typeof data.group === 'string') {\n (schema as { group: string }).group = data.group;\n }\n\n // Parse options\n if (data.options !== undefined && typeof data.options === 'object') {\n const options = buildSchemaOptions(data.options as Record<string, unknown>);\n if (Object.keys(options).length > 0) {\n (schema as { options: SchemaOptions }).options = options;\n }\n }\n\n // Parse properties\n if (data.properties !== undefined && typeof data.properties === 'object') {\n const properties = buildProperties(data.properties as Record<string, unknown>);\n if (Object.keys(properties).length > 0) {\n (schema as { properties: Record<string, PropertyDefinition> }).properties = properties;\n }\n }\n\n // Parse enum values\n if (data.values !== undefined && Array.isArray(data.values)) {\n (schema as { values: readonly string[] }).values = data.values as string[];\n }\n\n return schema;\n}\n\n/**\n * Builds SchemaOptions from parsed data.\n */\nfunction buildSchemaOptions(data: Record<string, unknown>): SchemaOptions {\n const options: SchemaOptions = {};\n\n if (data.timestamps !== undefined && typeof data.timestamps === 'boolean') {\n (options as { timestamps: boolean }).timestamps = data.timestamps;\n }\n\n if (data.softDelete !== undefined && typeof data.softDelete === 'boolean') {\n (options as { softDelete: boolean }).softDelete = data.softDelete;\n }\n\n if (data.unique !== undefined) {\n (options as { unique: readonly string[] | readonly (readonly string[])[] }).unique =\n data.unique as readonly string[] | readonly (readonly string[])[];\n }\n\n if (data.indexes !== undefined && Array.isArray(data.indexes)) {\n (options as { indexes: SchemaOptions['indexes'] }).indexes =\n data.indexes as SchemaOptions['indexes'];\n }\n\n if (data.translations !== undefined && typeof data.translations === 'boolean') {\n (options as { translations: boolean }).translations = data.translations;\n }\n\n if (data.tableName !== undefined && typeof data.tableName === 'string') {\n (options as { tableName: string }).tableName = data.tableName;\n }\n\n if (data.primaryKeyType !== undefined) {\n (options as { primaryKeyType: 'Int' | 'BigInt' | 'Uuid' | 'String' }).primaryKeyType =\n data.primaryKeyType as 'Int' | 'BigInt' | 'Uuid' | 'String';\n }\n\n if (data.authenticatable !== undefined && typeof data.authenticatable === 'boolean') {\n (options as { authenticatable: boolean }).authenticatable = data.authenticatable;\n }\n\n if (data.authenticatableLoginIdField !== undefined && typeof data.authenticatableLoginIdField === 'string') {\n (options as { authenticatableLoginIdField: string }).authenticatableLoginIdField =\n data.authenticatableLoginIdField;\n }\n\n if (data.authenticatablePasswordField !== undefined && typeof data.authenticatablePasswordField === 'string') {\n (options as { authenticatablePasswordField: string }).authenticatablePasswordField =\n data.authenticatablePasswordField;\n }\n\n if (data.authenticatableGuardName !== undefined && typeof data.authenticatableGuardName === 'string') {\n (options as { authenticatableGuardName: string }).authenticatableGuardName =\n data.authenticatableGuardName;\n }\n\n return options;\n}\n\n/**\n * Builds property definitions from parsed data.\n */\nfunction buildProperties(\n data: Record<string, unknown>\n): Record<string, PropertyDefinition> {\n const properties: Record<string, PropertyDefinition> = {};\n\n for (const [name, value] of Object.entries(data)) {\n if (value !== undefined && typeof value === 'object' && value !== null) {\n properties[name] = buildPropertyDefinition(value as Record<string, unknown>);\n }\n }\n\n return properties;\n}\n\n/**\n * Builds a single PropertyDefinition from parsed data.\n * Uses a generic record to avoid exactOptionalPropertyTypes issues.\n */\nfunction buildPropertyDefinition(\n data: Record<string, unknown>\n): PropertyDefinition {\n // Build as a generic record first, then cast at the end\n const prop: Record<string, unknown> = {\n type: (data.type as string) || 'String',\n };\n\n // Common properties\n if (data.displayName !== undefined && typeof data.displayName === 'string') {\n prop.displayName = data.displayName;\n }\n\n if (data.nullable !== undefined && typeof data.nullable === 'boolean') {\n prop.nullable = data.nullable;\n }\n\n if (data.default !== undefined) {\n prop.default = data.default;\n }\n\n if (data.unique !== undefined && typeof data.unique === 'boolean') {\n prop.unique = data.unique;\n }\n\n if (data.description !== undefined && typeof data.description === 'string') {\n prop.description = data.description;\n }\n\n // String properties\n if (data.length !== undefined && typeof data.length === 'number') {\n prop.length = data.length;\n }\n\n // Numeric properties\n if (data.unsigned !== undefined && typeof data.unsigned === 'boolean') {\n prop.unsigned = data.unsigned;\n }\n\n if (data.precision !== undefined && typeof data.precision === 'number') {\n prop.precision = data.precision;\n }\n\n if (data.scale !== undefined && typeof data.scale === 'number') {\n prop.scale = data.scale;\n }\n\n // Enum properties\n if (data.enum !== undefined) {\n prop.enum = data.enum;\n }\n\n // Select/Lookup properties\n if (data.options !== undefined && Array.isArray(data.options)) {\n prop.options = data.options;\n }\n\n if (data.source !== undefined && typeof data.source === 'string') {\n prop.source = data.source;\n }\n\n // Association properties\n if (data.relation !== undefined && typeof data.relation === 'string') {\n prop.relation = data.relation;\n }\n\n if (data.target !== undefined && typeof data.target === 'string') {\n prop.target = data.target;\n }\n\n if (data.inversedBy !== undefined && typeof data.inversedBy === 'string') {\n prop.inversedBy = data.inversedBy;\n }\n\n if (data.mappedBy !== undefined && typeof data.mappedBy === 'string') {\n prop.mappedBy = data.mappedBy;\n }\n\n if (data.onDelete !== undefined && typeof data.onDelete === 'string') {\n prop.onDelete = data.onDelete;\n }\n\n if (data.onUpdate !== undefined && typeof data.onUpdate === 'string') {\n prop.onUpdate = data.onUpdate;\n }\n\n if (data.owning !== undefined && typeof data.owning === 'boolean') {\n prop.owning = data.owning;\n }\n\n if (data.joinTable !== undefined && typeof data.joinTable === 'string') {\n prop.joinTable = data.joinTable;\n }\n\n return prop as unknown as PropertyDefinition;\n}\n\n/**\n * Loads a single schema file.\n * Supports both YAML (.yaml, .yml) and JSON (.json) formats.\n *\n * @param filePath - Path to the schema file\n * @param options - Loading options\n * @returns Loaded schema with metadata\n * @throws OmnifyError if file not found or invalid syntax\n */\nexport async function loadSchema(\n filePath: string,\n options: LoadSchemaOptions = {}\n): Promise<LoadedSchema> {\n const absolutePath = path.resolve(filePath);\n const baseDir = options.baseDir ? path.resolve(options.baseDir) : path.dirname(absolutePath);\n\n // Check if file exists\n try {\n await fs.access(absolutePath);\n } catch {\n throw schemaNotFoundError(filePath);\n }\n\n // Read file content\n const content = await fs.readFile(absolutePath, 'utf-8');\n\n // Parse based on file extension\n const ext = path.extname(absolutePath).toLowerCase();\n const schemaDefinition = ext === '.json'\n ? parseJsonSchema(content, filePath)\n : parseYamlSchema(content, filePath);\n\n // Build LoadedSchema\n const name = fileNameToSchemaName(absolutePath);\n const relativePath = path.relative(baseDir, absolutePath);\n\n const loadedSchema: LoadedSchema = {\n ...schemaDefinition,\n name,\n filePath: absolutePath,\n relativePath,\n };\n\n return loadedSchema;\n}\n\n/**\n * Recursively finds all schema files in a directory.\n */\nasync function findSchemaFiles(\n dirPath: string,\n extensions: readonly string[],\n recursive: boolean\n): Promise<string[]> {\n const files: string[] = [];\n\n const entries = await fs.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory() && recursive) {\n const subFiles = await findSchemaFiles(fullPath, extensions, recursive);\n files.push(...subFiles);\n } else if (entry.isFile()) {\n const ext = path.extname(entry.name).toLowerCase();\n if (extensions.includes(ext)) {\n files.push(fullPath);\n }\n }\n }\n\n return files;\n}\n\n/**\n * Loads all schemas from a directory.\n *\n * @param directoryPath - Path to the schemas directory\n * @param options - Loading options\n * @returns Collection of loaded schemas indexed by name\n * @throws OmnifyError if duplicate schema names or invalid files\n */\nexport async function loadSchemas(\n directoryPath: string,\n options: LoadSchemasOptions = {}\n): Promise<SchemaCollection> {\n const {\n extensions = ['.yaml', '.yml', '.json'],\n recursive = true,\n } = options;\n\n const absoluteDir = path.resolve(directoryPath);\n\n // Check if directory exists\n try {\n const stat = await fs.stat(absoluteDir);\n if (!stat.isDirectory()) {\n throw schemaNotFoundError(directoryPath);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw schemaNotFoundError(directoryPath);\n }\n throw error;\n }\n\n // Find all schema files\n const schemaFiles = await findSchemaFiles(absoluteDir, extensions, recursive);\n\n // Load each schema\n const schemas: Record<string, LoadedSchema> = {};\n const schemaLocations: Record<string, string> = {};\n\n for (const filePath of schemaFiles) {\n const schema = await loadSchema(filePath, { baseDir: absoluteDir });\n\n // Check for duplicate names\n const existingLocation = schemaLocations[schema.name];\n if (existingLocation !== undefined) {\n throw duplicateSchemaError(\n schema.name,\n { file: filePath },\n { file: existingLocation }\n );\n }\n\n schemas[schema.name] = schema;\n schemaLocations[schema.name] = filePath;\n }\n\n return schemas;\n}\n","/**\n * @famgia/omnify-core - Schema Validator\n *\n * Validates schema definitions for correctness and consistency.\n */\n\nimport type {\n SchemaDefinition,\n LoadedSchema,\n SchemaCollection,\n PropertyDefinition,\n BuiltInPropertyType,\n AssociationRelation,\n} from '@famgia/omnify-types';\nimport {\n OmnifyError,\n validationError,\n invalidPropertyTypeError,\n missingFieldError,\n invalidAssociationTargetError,\n} from '../errors/index.js';\nimport type {\n SchemaValidationResult,\n ValidationResult,\n ValidationOptions,\n} from './types.js';\n\n/**\n * Built-in property types that are always valid.\n */\nconst BUILT_IN_TYPES: readonly BuiltInPropertyType[] = [\n 'String',\n 'Int',\n 'BigInt',\n 'Float',\n 'Boolean',\n 'Text',\n 'LongText',\n 'Date',\n 'Time',\n 'Timestamp',\n 'Json',\n 'Email',\n 'Password',\n 'File',\n 'MultiFile',\n 'Enum',\n 'Select',\n 'Lookup',\n 'Association',\n 'Polymorphic',\n];\n\n/**\n * Valid association relation types.\n */\nconst VALID_RELATIONS: readonly AssociationRelation[] = [\n 'OneToOne',\n 'OneToMany',\n 'ManyToOne',\n 'ManyToMany',\n];\n\n/**\n * Valid referential actions for foreign keys.\n */\nconst VALID_REFERENTIAL_ACTIONS = [\n 'CASCADE',\n 'SET NULL',\n 'SET DEFAULT',\n 'RESTRICT',\n 'NO ACTION',\n] as const;\n\n/**\n * Valid primary key types.\n */\nconst VALID_PRIMARY_KEY_TYPES = ['Int', 'BigInt', 'Uuid', 'String'] as const;\n\n/**\n * Helper to build ErrorLocation safely.\n */\nfunction buildLocation(file: string, line?: number, column?: number) {\n const loc: { file: string; line?: number; column?: number } = { file };\n if (line !== undefined) {\n loc.line = line;\n }\n if (column !== undefined) {\n loc.column = column;\n }\n return loc;\n}\n\n/**\n * Validates a property type.\n */\nexport function validatePropertyType(\n propertyName: string,\n property: PropertyDefinition,\n filePath: string,\n customTypes: readonly string[] = []\n): OmnifyError[] {\n const errors: OmnifyError[] = [];\n const validTypes = [...BUILT_IN_TYPES, ...customTypes];\n\n if (!property.type) {\n errors.push(\n missingFieldError('type', buildLocation(filePath))\n );\n return errors;\n }\n\n if (!validTypes.includes(property.type as BuiltInPropertyType)) {\n errors.push(\n invalidPropertyTypeError(\n property.type,\n buildLocation(filePath),\n BUILT_IN_TYPES\n )\n );\n }\n\n // Validate type-specific requirements\n if (property.type === 'Enum') {\n const enumProp = property as { enum?: unknown };\n if (enumProp.enum === undefined) {\n errors.push(\n validationError(\n `Property '${propertyName}' of type 'Enum' requires 'enum' field`,\n buildLocation(filePath),\n 'Add enum values: enum: [value1, value2]'\n )\n );\n }\n }\n\n if (property.type === 'Association') {\n const assocProp = property as { relation?: unknown; target?: unknown };\n if (assocProp.relation === undefined) {\n errors.push(\n validationError(\n `Property '${propertyName}' of type 'Association' requires 'relation' field`,\n buildLocation(filePath),\n 'Add relation: OneToOne, OneToMany, ManyToOne, or ManyToMany'\n )\n );\n }\n if (assocProp.target === undefined) {\n errors.push(\n validationError(\n `Property '${propertyName}' of type 'Association' requires 'target' field`,\n buildLocation(filePath),\n 'Add target schema name: target: User'\n )\n );\n }\n }\n\n return errors;\n}\n\n/**\n * Validates all properties in a schema.\n */\nexport function validateProperties(\n schema: SchemaDefinition,\n filePath: string,\n customTypes: readonly string[] = []\n): OmnifyError[] {\n const errors: OmnifyError[] = [];\n\n if (!schema.properties) {\n // No properties is valid for enum schemas\n if (schema.kind !== 'enum') {\n // Warning: object schema without properties\n }\n return errors;\n }\n\n for (const [name, property] of Object.entries(schema.properties)) {\n const propErrors = validatePropertyType(name, property, filePath, customTypes);\n errors.push(...propErrors);\n }\n\n return errors;\n}\n\n/**\n * Validates associations in a schema against available schemas.\n */\nexport function validateAssociations(\n schema: LoadedSchema,\n allSchemas: SchemaCollection\n): OmnifyError[] {\n const errors: OmnifyError[] = [];\n\n if (!schema.properties) {\n return errors;\n }\n\n const availableSchemas = Object.keys(allSchemas);\n\n for (const [name, property] of Object.entries(schema.properties)) {\n if (property.type !== 'Association') {\n continue;\n }\n\n const assocProp = property as {\n relation?: string;\n target?: string;\n inversedBy?: string;\n mappedBy?: string;\n onDelete?: string;\n onUpdate?: string;\n };\n\n // Validate relation type\n if (assocProp.relation && !VALID_RELATIONS.includes(assocProp.relation as AssociationRelation)) {\n errors.push(\n validationError(\n `Property '${name}' has invalid relation '${assocProp.relation}'`,\n buildLocation(schema.filePath),\n `Use one of: ${VALID_RELATIONS.join(', ')}`\n )\n );\n }\n\n // Validate target exists\n if (assocProp.target && !availableSchemas.includes(assocProp.target)) {\n errors.push(\n invalidAssociationTargetError(\n assocProp.target,\n buildLocation(schema.filePath),\n availableSchemas\n )\n );\n }\n\n // Validate inversedBy/mappedBy references exist\n if (assocProp.inversedBy && assocProp.target) {\n const targetSchema = allSchemas[assocProp.target];\n if (targetSchema?.properties) {\n const inverseProperty = targetSchema.properties[assocProp.inversedBy];\n if (!inverseProperty) {\n errors.push(\n validationError(\n `Property '${name}' references non-existent inverse property '${assocProp.inversedBy}' on '${assocProp.target}'`,\n buildLocation(schema.filePath),\n `Add property '${assocProp.inversedBy}' to ${assocProp.target} schema`\n )\n );\n }\n }\n }\n\n // Validate referential actions\n if (assocProp.onDelete && !VALID_REFERENTIAL_ACTIONS.includes(assocProp.onDelete as typeof VALID_REFERENTIAL_ACTIONS[number])) {\n errors.push(\n validationError(\n `Property '${name}' has invalid onDelete action '${assocProp.onDelete}'`,\n buildLocation(schema.filePath),\n `Use one of: ${VALID_REFERENTIAL_ACTIONS.join(', ')}`\n )\n );\n }\n\n if (assocProp.onUpdate && !VALID_REFERENTIAL_ACTIONS.includes(assocProp.onUpdate as typeof VALID_REFERENTIAL_ACTIONS[number])) {\n errors.push(\n validationError(\n `Property '${name}' has invalid onUpdate action '${assocProp.onUpdate}'`,\n buildLocation(schema.filePath),\n `Use one of: ${VALID_REFERENTIAL_ACTIONS.join(', ')}`\n )\n );\n }\n }\n\n return errors;\n}\n\n/**\n * Validates schema options.\n */\nexport function validateOptions(\n schema: SchemaDefinition,\n filePath: string\n): OmnifyError[] {\n const errors: OmnifyError[] = [];\n const options = schema.options;\n\n if (!options) {\n return errors;\n }\n\n // Validate primaryKeyType\n if (options.primaryKeyType !== undefined) {\n if (!VALID_PRIMARY_KEY_TYPES.includes(options.primaryKeyType as typeof VALID_PRIMARY_KEY_TYPES[number])) {\n errors.push(\n validationError(\n `Invalid primaryKeyType '${options.primaryKeyType}'`,\n buildLocation(filePath),\n `Use one of: ${VALID_PRIMARY_KEY_TYPES.join(', ')}`\n )\n );\n }\n }\n\n // Validate unique constraints reference existing properties\n if (options.unique && schema.properties) {\n const propertyNames = Object.keys(schema.properties);\n const uniqueConstraints = Array.isArray(options.unique[0])\n ? (options.unique as readonly (readonly string[])[])\n : [options.unique as readonly string[]];\n\n for (const constraint of uniqueConstraints) {\n for (const column of constraint) {\n if (!propertyNames.includes(column)) {\n errors.push(\n validationError(\n `Unique constraint references non-existent property '${column}'`,\n buildLocation(filePath),\n `Available properties: ${propertyNames.join(', ')}`\n )\n );\n }\n }\n }\n }\n\n // Validate indexes reference existing properties\n if (options.indexes && schema.properties) {\n const propertyNames = Object.keys(schema.properties);\n\n for (const index of options.indexes) {\n for (const column of index.columns) {\n if (!propertyNames.includes(column)) {\n errors.push(\n validationError(\n `Index references non-existent property '${column}'`,\n buildLocation(filePath),\n `Available properties: ${propertyNames.join(', ')}`\n )\n );\n }\n }\n }\n }\n\n // Validate authenticatable options\n if (options.authenticatable) {\n if (options.authenticatableLoginIdField && schema.properties) {\n if (!schema.properties[options.authenticatableLoginIdField]) {\n errors.push(\n validationError(\n `authenticatableLoginIdField references non-existent property '${options.authenticatableLoginIdField}'`,\n buildLocation(filePath)\n )\n );\n }\n }\n\n if (options.authenticatablePasswordField && schema.properties) {\n if (!schema.properties[options.authenticatablePasswordField]) {\n errors.push(\n validationError(\n `authenticatablePasswordField references non-existent property '${options.authenticatablePasswordField}'`,\n buildLocation(filePath)\n )\n );\n }\n }\n }\n\n return errors;\n}\n\n/**\n * Validates an enum schema.\n */\nexport function validateEnumSchema(\n schema: SchemaDefinition,\n filePath: string\n): OmnifyError[] {\n const errors: OmnifyError[] = [];\n\n if (schema.kind !== 'enum') {\n return errors;\n }\n\n if (!schema.values || schema.values.length === 0) {\n errors.push(\n validationError(\n 'Enum schema requires at least one value',\n buildLocation(filePath),\n 'Add values: [value1, value2, ...]'\n )\n );\n }\n\n // Check for duplicate values\n if (schema.values) {\n const seen = new Set<string>();\n for (const value of schema.values) {\n if (seen.has(value)) {\n errors.push(\n validationError(\n `Duplicate enum value '${value}'`,\n buildLocation(filePath)\n )\n );\n }\n seen.add(value);\n }\n }\n\n return errors;\n}\n\n/**\n * Validates a single schema.\n */\nexport function validateSchema(\n schema: LoadedSchema,\n options: ValidationOptions = {}\n): SchemaValidationResult {\n const errors: OmnifyError[] = [];\n const warnings: OmnifyError[] = [];\n const customTypes = options.customTypes ?? [];\n\n // Validate properties\n const propErrors = validateProperties(schema, schema.filePath, customTypes);\n errors.push(...propErrors);\n\n // Validate options\n const optErrors = validateOptions(schema, schema.filePath);\n errors.push(...optErrors);\n\n // Validate enum schema\n if (schema.kind === 'enum') {\n const enumErrors = validateEnumSchema(schema, schema.filePath);\n errors.push(...enumErrors);\n }\n\n // Validate titleIndex references existing property\n if (schema.titleIndex && schema.properties) {\n if (!schema.properties[schema.titleIndex]) {\n errors.push(\n validationError(\n `titleIndex references non-existent property '${schema.titleIndex}'`,\n buildLocation(schema.filePath),\n `Available properties: ${Object.keys(schema.properties).join(', ')}`\n )\n );\n }\n }\n\n return {\n schemaName: schema.name,\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Validates a collection of schemas.\n */\nexport function validateSchemas(\n schemas: SchemaCollection,\n options: ValidationOptions = {}\n): ValidationResult {\n const schemaResults: SchemaValidationResult[] = [];\n const allErrors: OmnifyError[] = [];\n const allWarnings: OmnifyError[] = [];\n const validateAssocs = options.validateAssociations ?? true;\n\n // First pass: validate each schema individually\n for (const schema of Object.values(schemas)) {\n const result = validateSchema(schema, options);\n schemaResults.push(result);\n allErrors.push(...result.errors);\n allWarnings.push(...result.warnings);\n }\n\n // Second pass: validate associations across schemas\n if (validateAssocs) {\n for (const schema of Object.values(schemas)) {\n const assocErrors = validateAssociations(schema, schemas);\n allErrors.push(...assocErrors);\n\n // Update the schema result\n const existingResult = schemaResults.find(r => r.schemaName === schema.name);\n if (existingResult && assocErrors.length > 0) {\n const updatedResult: SchemaValidationResult = {\n ...existingResult,\n valid: false,\n errors: [...existingResult.errors, ...assocErrors],\n };\n const index = schemaResults.indexOf(existingResult);\n schemaResults[index] = updatedResult;\n }\n }\n }\n\n return {\n valid: allErrors.length === 0,\n errorCount: allErrors.length,\n warningCount: allWarnings.length,\n schemas: schemaResults,\n errors: allErrors,\n warnings: allWarnings,\n };\n}\n","/**\n * @famgia/omnify-core - Plugin Manager\n *\n * Manages plugin registration and type resolution.\n */\n\nimport type {\n OmnifyPlugin,\n CustomTypeDefinition,\n PluginContext,\n PluginLogger,\n} from '@famgia/omnify-types';\nimport type {\n RegisteredType,\n PluginRegistry,\n PluginManagerOptions,\n PluginRegistrationResult,\n} from './types.js';\nimport { pluginError, pluginTypeConflictError, pluginNotFoundError } from '../errors/index.js';\n\n/**\n * Default logger that does nothing.\n */\nconst nullLogger: PluginLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Console logger for verbose mode.\n */\nconst consoleLogger: PluginLogger = {\n debug: (msg) => console.log(`[plugin:debug] ${msg}`),\n info: (msg) => console.log(`[plugin:info] ${msg}`),\n warn: (msg) => console.warn(`[plugin:warn] ${msg}`),\n error: (msg) => console.error(`[plugin:error] ${msg}`),\n};\n\n/**\n * Plugin Manager class for managing plugin lifecycle.\n */\nexport class PluginManager {\n private readonly _plugins: Map<string, OmnifyPlugin> = new Map();\n private readonly _types: Map<string, RegisteredType> = new Map();\n private readonly _cwd: string;\n private readonly _verbose: boolean;\n private readonly _logger: PluginLogger;\n\n constructor(options: PluginManagerOptions = {}) {\n this._cwd = options.cwd ?? process.cwd();\n this._verbose = options.verbose ?? false;\n this._logger = options.logger ?? (this._verbose ? consoleLogger : nullLogger);\n }\n\n /**\n * Creates a plugin context for plugin setup.\n */\n private createContext(): PluginContext {\n return {\n cwd: this._cwd,\n verbose: this._verbose,\n logger: this._logger,\n };\n }\n\n /**\n * Registers a single plugin.\n */\n async register(plugin: OmnifyPlugin): Promise<PluginRegistrationResult> {\n const warnings: string[] = [];\n const registeredTypes: RegisteredType[] = [];\n\n // Check for duplicate plugin\n if (this._plugins.has(plugin.name)) {\n return {\n success: false,\n types: [],\n warnings: [],\n error: `Plugin '${plugin.name}' is already registered`,\n };\n }\n\n this._logger.debug(`Registering plugin: ${plugin.name}@${plugin.version}`);\n\n // Run setup if provided\n if (plugin.setup) {\n try {\n await plugin.setup(this.createContext());\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n types: [],\n warnings: [],\n error: `Plugin setup failed: ${message}`,\n };\n }\n }\n\n // Register types\n if (plugin.types) {\n for (const typeDef of plugin.types) {\n // Check for type conflicts\n const existing = this._types.get(typeDef.name);\n if (existing) {\n throw pluginTypeConflictError(\n typeDef.name,\n existing.pluginName,\n plugin.name\n );\n }\n\n // Validate type definition\n const validationError = this.validateTypeDefinition(typeDef);\n if (validationError) {\n warnings.push(`Type '${typeDef.name}': ${validationError}`);\n continue;\n }\n\n const registeredType: RegisteredType = {\n ...typeDef,\n pluginName: plugin.name,\n pluginVersion: plugin.version,\n };\n\n this._types.set(typeDef.name, registeredType);\n registeredTypes.push(registeredType);\n\n this._logger.debug(` Registered type: ${typeDef.name}`);\n }\n }\n\n // Store plugin\n this._plugins.set(plugin.name, plugin);\n\n this._logger.info(`Plugin registered: ${plugin.name} (${registeredTypes.length} types)`);\n\n return {\n success: true,\n types: registeredTypes,\n warnings,\n };\n }\n\n /**\n * Registers multiple plugins.\n */\n async registerAll(plugins: readonly OmnifyPlugin[]): Promise<void> {\n for (const plugin of plugins) {\n const result = await this.register(plugin);\n if (!result.success) {\n throw pluginError(result.error ?? 'Unknown error', plugin.name);\n }\n }\n }\n\n /**\n * Validates a type definition.\n */\n private validateTypeDefinition(typeDef: CustomTypeDefinition): string | undefined {\n if (!typeDef.name || typeDef.name.length === 0) {\n return 'Type name is required';\n }\n\n if (typeDef.compound) {\n if (!typeDef.expand || typeDef.expand.length === 0) {\n return 'Compound type must have expand definitions';\n }\n\n for (const field of typeDef.expand) {\n if (!field.suffix) {\n return 'Expanded field must have a suffix';\n }\n if (!field.sql || !field.sql.sqlType) {\n return `Expanded field '${field.suffix}' must have SQL type`;\n }\n if (!field.typescript || !field.typescript.type) {\n return `Expanded field '${field.suffix}' must have TypeScript type`;\n }\n }\n } else {\n if (!typeDef.sql || !typeDef.sql.sqlType) {\n return 'Non-compound type must have SQL definition';\n }\n if (!typeDef.typescript || !typeDef.typescript.type) {\n return 'Non-compound type must have TypeScript type';\n }\n }\n\n return undefined;\n }\n\n /**\n * Unregisters a plugin and its types.\n */\n async unregister(pluginName: string): Promise<void> {\n const plugin = this._plugins.get(pluginName);\n if (!plugin) {\n throw pluginNotFoundError(pluginName);\n }\n\n // Run teardown if provided\n if (plugin.teardown) {\n try {\n await plugin.teardown();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this._logger.warn(`Plugin teardown failed: ${message}`);\n }\n }\n\n // Remove types from this plugin\n for (const [typeName, type] of this._types) {\n if (type.pluginName === pluginName) {\n this._types.delete(typeName);\n }\n }\n\n // Remove plugin\n this._plugins.delete(pluginName);\n\n this._logger.info(`Plugin unregistered: ${pluginName}`);\n }\n\n /**\n * Gets a registered type by name.\n */\n getType(typeName: string): RegisteredType | undefined {\n return this._types.get(typeName);\n }\n\n /**\n * Checks if a type is registered.\n */\n hasType(typeName: string): boolean {\n return this._types.has(typeName);\n }\n\n /**\n * Gets all registered types.\n */\n getAllTypes(): ReadonlyMap<string, RegisteredType> {\n return this._types;\n }\n\n /**\n * Gets all registered type names.\n */\n getTypeNames(): readonly string[] {\n return Array.from(this._types.keys());\n }\n\n /**\n * Gets a registered plugin by name.\n */\n getPlugin(pluginName: string): OmnifyPlugin | undefined {\n return this._plugins.get(pluginName);\n }\n\n /**\n * Gets all registered plugins.\n */\n getAllPlugins(): ReadonlyMap<string, OmnifyPlugin> {\n return this._plugins;\n }\n\n /**\n * Gets the current registry state.\n */\n getRegistry(): PluginRegistry {\n return {\n plugins: this._plugins,\n types: this._types,\n };\n }\n\n /**\n * Clears all registered plugins and types.\n */\n async clear(): Promise<void> {\n // Teardown all plugins\n for (const plugin of this._plugins.values()) {\n if (plugin.teardown) {\n try {\n await plugin.teardown();\n } catch {\n // Ignore teardown errors during clear\n }\n }\n }\n\n this._plugins.clear();\n this._types.clear();\n\n this._logger.debug('Plugin registry cleared');\n }\n}\n\n/**\n * Creates a new plugin manager instance.\n */\nexport function createPluginManager(options?: PluginManagerOptions): PluginManager {\n return new PluginManager(options);\n}\n","/**\n * @famgia/omnify-core - Compound Type Expander\n *\n * Expands compound types into multiple fields.\n */\n\nimport type {\n LoadedSchema,\n SchemaCollection,\n PropertyDefinition,\n} from '@famgia/omnify-types';\nimport type { RegisteredType, PluginRegistry } from './types.js';\n\n/**\n * Expanded property with original property name.\n */\nexport interface ExpandedProperty {\n /** Original property name */\n originalName: string;\n /** Expanded column name (originalName + suffix) */\n expandedName: string;\n /** The expanded field definition */\n property: PropertyDefinition;\n /** Whether this is from a compound type */\n isCompound: boolean;\n /** Source type name if from plugin */\n sourceType?: string;\n}\n\n/**\n * Expands a single property if it's a compound type.\n */\nexport function expandProperty(\n propertyName: string,\n property: PropertyDefinition,\n registry: PluginRegistry\n): ExpandedProperty[] {\n const typeName = property.type;\n const registeredType = registry.types.get(typeName);\n\n // If not a registered type or not compound, return as-is\n if (!registeredType || !registeredType.compound || !registeredType.expand) {\n return [{\n originalName: propertyName,\n expandedName: propertyName,\n property,\n isCompound: false,\n }];\n }\n\n // Expand compound type\n const expanded: ExpandedProperty[] = [];\n\n for (const field of registeredType.expand) {\n const expandedName = `${propertyName}${field.suffix}`;\n\n // Create property definition for expanded field\n const expandedProperty: PropertyDefinition = {\n type: 'String', // Use String as placeholder, actual SQL type is in field.sql\n // Copy nullable from original property\n ...((property as { nullable?: boolean }).nullable !== undefined\n ? { nullable: (property as { nullable?: boolean }).nullable }\n : {}),\n };\n\n expanded.push({\n originalName: propertyName,\n expandedName,\n property: expandedProperty,\n isCompound: true,\n sourceType: typeName,\n });\n }\n\n return expanded;\n}\n\n/**\n * Expands all compound types in a schema's properties.\n */\nexport function expandSchemaProperties(\n schema: LoadedSchema,\n registry: PluginRegistry\n): Map<string, ExpandedProperty[]> {\n const expandedMap = new Map<string, ExpandedProperty[]>();\n\n if (!schema.properties) {\n return expandedMap;\n }\n\n for (const [propName, property] of Object.entries(schema.properties)) {\n const expanded = expandProperty(propName, property, registry);\n expandedMap.set(propName, expanded);\n }\n\n return expandedMap;\n}\n\n/**\n * Creates a new schema with compound types expanded.\n */\nexport function expandSchema(\n schema: LoadedSchema,\n registry: PluginRegistry\n): LoadedSchema {\n if (!schema.properties || schema.kind === 'enum') {\n return schema;\n }\n\n const expandedProperties: Record<string, PropertyDefinition> = {};\n let hasExpansion = false;\n\n for (const [propName, property] of Object.entries(schema.properties)) {\n const expanded = expandProperty(propName, property, registry);\n\n const firstExpanded = expanded[0];\n if (expanded.length === 1 && firstExpanded && !firstExpanded.isCompound) {\n // Not a compound type, keep original\n expandedProperties[propName] = property;\n } else {\n // Compound type expanded\n hasExpansion = true;\n for (const exp of expanded) {\n expandedProperties[exp.expandedName] = exp.property;\n }\n }\n }\n\n if (!hasExpansion) {\n return schema;\n }\n\n return {\n ...schema,\n properties: expandedProperties,\n };\n}\n\n/**\n * Expands compound types in all schemas.\n */\nexport function expandSchemas(\n schemas: SchemaCollection,\n registry: PluginRegistry\n): SchemaCollection {\n const expanded: Record<string, LoadedSchema> = {};\n\n for (const [name, schema] of Object.entries(schemas)) {\n expanded[name] = expandSchema(schema, registry);\n }\n\n return expanded;\n}\n\n/**\n * Gets the registered type info for a property type.\n */\nexport function getTypeInfo(\n typeName: string,\n registry: PluginRegistry\n): RegisteredType | undefined {\n return registry.types.get(typeName);\n}\n\n/**\n * Checks if a type is a compound type.\n */\nexport function isCompoundType(\n typeName: string,\n registry: PluginRegistry\n): boolean {\n const type = registry.types.get(typeName);\n return type?.compound === true;\n}\n\n/**\n * Gets all custom type names from the registry.\n */\nexport function getCustomTypeNames(registry: PluginRegistry): string[] {\n return Array.from(registry.types.keys());\n}\n","/**\n * @famgia/omnify-core - Omnify Programmatic API\n *\n * Main entry point for using omnify-schema programmatically.\n */\n\nimport { resolve } from 'node:path';\nimport type { SchemaCollection, OmnifyPlugin } from '@famgia/omnify-types';\nimport type {\n OmnifyOptions,\n OmnifyLogger,\n LoadResult,\n SchemaError,\n SchemaIntrospection,\n} from './types.js';\nimport { loadSchemas } from '../schema/index.js';\nimport { validateSchemas } from '../validation/index.js';\nimport { PluginManager, createPluginManager } from '../plugins/index.js';\nimport type { PluginRegistry } from '../plugins/types.js';\nimport { OmnifyError } from '../errors/index.js';\nimport {\n introspectSchema,\n introspectSchemas,\n getSchemaNames,\n getEntitySchemas,\n getEnumSchemas,\n getSchemasByGroup,\n getGroups,\n findReferencingSchemas,\n findReferencedSchemas,\n hasCircularReferences,\n getTopologicalOrder,\n} from './metadata.js';\n\n/**\n * Default logger that does nothing.\n */\nconst nullLogger: OmnifyLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Console logger for verbose mode.\n */\nconst consoleLogger: OmnifyLogger = {\n debug: (msg, ...args) => console.debug(`[omnify] ${msg}`, ...args),\n info: (msg, ...args) => console.info(`[omnify] ${msg}`, ...args),\n warn: (msg, ...args) => console.warn(`[omnify] ${msg}`, ...args),\n error: (msg, ...args) => console.error(`[omnify] ${msg}`, ...args),\n};\n\n/**\n * Main Omnify API class for programmatic usage.\n *\n * @example\n * ```typescript\n * import { Omnify } from '@famgia/omnify-core';\n *\n * const omnify = new Omnify({\n * schemaDir: './schemas',\n * plugins: [japanTypesPlugin],\n * });\n *\n * // Load and validate schemas\n * const { schemas, errors } = await omnify.load();\n *\n * // Get schema metadata\n * const users = omnify.getSchema('User');\n *\n * // Introspect schema\n * const introspection = omnify.introspect('User');\n * ```\n */\nexport class Omnify {\n private readonly options: OmnifyOptions;\n private readonly logger: OmnifyLogger;\n private readonly pluginManager: PluginManager;\n private schemas: SchemaCollection | null = null;\n private loaded = false;\n\n constructor(options: OmnifyOptions) {\n this.options = {\n ...options,\n schemaDir: resolve(options.schemaDir),\n };\n this.logger = options.logger ?? (options.verbose ? consoleLogger : nullLogger);\n this.pluginManager = createPluginManager({ logger: this.logger });\n }\n\n /**\n * Registers plugins with the plugin manager.\n */\n async registerPlugins(plugins: OmnifyPlugin[]): Promise<void> {\n for (const plugin of plugins) {\n this.logger.debug(`Registering plugin: ${plugin.name}`);\n const result = await this.pluginManager.register(plugin);\n if (!result.success) {\n throw new Error(`Failed to register plugin ${plugin.name}: ${result.error}`);\n }\n if (result.warnings.length > 0) {\n for (const warning of result.warnings) {\n this.logger.warn(warning);\n }\n }\n }\n }\n\n /**\n * Loads and validates schemas from the configured directory.\n */\n async load(): Promise<LoadResult> {\n this.logger.info(`Loading schemas from: ${this.options.schemaDir}`);\n\n // Register plugins if provided\n if (this.options.plugins?.length) {\n await this.registerPlugins(this.options.plugins);\n }\n\n const errors: SchemaError[] = [];\n const warnings: { file: string; message: string }[] = [];\n\n try {\n // Load schemas\n const schemas = await loadSchemas(this.options.schemaDir, {\n recursive: true,\n });\n this.logger.debug(`Loaded ${Object.keys(schemas).length} schemas`);\n\n // Get custom type names from plugin registry\n const customTypeNames = Array.from(this.pluginManager.getRegistry().types.keys());\n\n // Validate schemas\n const validationResult = validateSchemas(schemas, {\n customTypes: customTypeNames,\n });\n\n // Collect errors and warnings\n for (const error of validationResult.errors) {\n const schemaError: SchemaError = {\n file: error.file ?? 'unknown',\n message: error.message,\n };\n if (error.line !== undefined) {\n schemaError.line = error.line;\n }\n if (error.suggestion !== undefined) {\n schemaError.suggestion = error.suggestion;\n }\n errors.push(schemaError);\n }\n\n for (const warning of validationResult.warnings) {\n warnings.push({\n file: warning.file ?? 'unknown',\n message: warning.message,\n });\n }\n\n if (validationResult.valid) {\n this.schemas = schemas;\n this.loaded = true;\n }\n\n return {\n success: validationResult.valid,\n schemas: schemas,\n errors,\n warnings,\n };\n } catch (error) {\n if (error instanceof OmnifyError) {\n const schemaError: SchemaError = {\n file: error.file ?? 'unknown',\n message: error.message,\n };\n if (error.line !== undefined) {\n schemaError.line = error.line;\n }\n if (error.suggestion !== undefined) {\n schemaError.suggestion = error.suggestion;\n }\n errors.push(schemaError);\n } else {\n errors.push({\n file: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n });\n }\n\n return {\n success: false,\n schemas: {},\n errors,\n warnings,\n };\n }\n }\n\n /**\n * Gets loaded schemas. Throws if not loaded.\n */\n getSchemas(): SchemaCollection {\n if (!this.loaded || !this.schemas) {\n throw new Error('Schemas not loaded. Call load() first.');\n }\n return this.schemas;\n }\n\n /**\n * Gets a single schema by name.\n */\n getSchema(name: string): SchemaIntrospection | undefined {\n const schemas = this.getSchemas();\n const schema = schemas[name];\n if (!schema) return undefined;\n return introspectSchema(schema, this.pluginManager.getRegistry());\n }\n\n /**\n * Gets all schema names.\n */\n getSchemaNames(): string[] {\n return getSchemaNames(this.getSchemas());\n }\n\n /**\n * Gets entity schemas (non-enum).\n */\n getEntitySchemas(): SchemaIntrospection[] {\n const schemas = getEntitySchemas(this.getSchemas());\n return schemas.map((s) =>\n introspectSchema(s, this.pluginManager.getRegistry())\n );\n }\n\n /**\n * Gets enum schemas.\n */\n getEnumSchemas(): SchemaIntrospection[] {\n const schemas = getEnumSchemas(this.getSchemas());\n return schemas.map((s) =>\n introspectSchema(s, this.pluginManager.getRegistry())\n );\n }\n\n /**\n * Gets schemas by group.\n */\n getSchemasByGroup(group: string): SchemaIntrospection[] {\n const schemas = getSchemasByGroup(this.getSchemas(), group);\n return schemas.map((s) =>\n introspectSchema(s, this.pluginManager.getRegistry())\n );\n }\n\n /**\n * Gets all unique group names.\n */\n getGroups(): string[] {\n return getGroups(this.getSchemas());\n }\n\n /**\n * Introspects a specific schema.\n */\n introspect(name: string): SchemaIntrospection | undefined {\n return this.getSchema(name);\n }\n\n /**\n * Introspects all schemas.\n */\n introspectAll(): Map<string, SchemaIntrospection> {\n return introspectSchemas(this.getSchemas(), this.pluginManager.getRegistry());\n }\n\n /**\n * Finds schemas that reference a target schema.\n */\n findReferencingSchemas(targetName: string): SchemaIntrospection[] {\n const schemas = findReferencingSchemas(this.getSchemas(), targetName);\n return schemas.map((s) =>\n introspectSchema(s, this.pluginManager.getRegistry())\n );\n }\n\n /**\n * Finds schemas referenced by a source schema.\n */\n findReferencedSchemas(sourceName: string): SchemaIntrospection[] {\n const schemas = findReferencedSchemas(this.getSchemas(), sourceName);\n return schemas.map((s) =>\n introspectSchema(s, this.pluginManager.getRegistry())\n );\n }\n\n /**\n * Checks if schemas have circular references.\n */\n hasCircularReferences(): boolean {\n return hasCircularReferences(this.getSchemas());\n }\n\n /**\n * Gets topological order of schemas (dependencies first).\n */\n getTopologicalOrder(): string[] {\n return getTopologicalOrder(this.getSchemas());\n }\n\n /**\n * Gets the plugin registry.\n */\n getPluginRegistry(): PluginRegistry {\n return this.pluginManager.getRegistry();\n }\n\n /**\n * Checks if a type is registered (from plugin).\n */\n hasType(typeName: string): boolean {\n return this.pluginManager.hasType(typeName);\n }\n\n /**\n * Gets custom type names from all registered plugins.\n */\n getCustomTypeNames(): string[] {\n return Array.from(this.pluginManager.getRegistry().types.keys());\n }\n}\n\n/**\n * Creates an Omnify instance.\n *\n * @example\n * ```typescript\n * const omnify = createOmnify({\n * schemaDir: './schemas',\n * });\n *\n * const { schemas } = await omnify.load();\n * ```\n */\nexport function createOmnify(options: OmnifyOptions): Omnify {\n return new Omnify(options);\n}\n","/**\n * @famgia/omnify-core - Schema Metadata Access\n *\n * Utilities for accessing schema metadata programmatically.\n */\n\nimport type {\n LoadedSchema,\n SchemaCollection,\n PropertyDefinition,\n AssociationDefinition,\n} from '@famgia/omnify-types';\nimport type {\n SchemaMetadata,\n PropertyMetadata,\n AssociationMetadata,\n SchemaIntrospection,\n} from './types.js';\nimport type { PluginRegistry } from '../plugins/types.js';\n\n/**\n * Type guard to check if a property is an association.\n */\nfunction isAssociation(prop: PropertyDefinition): prop is AssociationDefinition {\n return prop.type === 'Association';\n}\n\n/**\n * Extracts metadata from a loaded schema.\n */\nexport function getSchemaMetadata(schema: LoadedSchema): SchemaMetadata {\n const propertyNames: string[] = [];\n const associationNames: string[] = [];\n\n if (schema.properties) {\n for (const [name, prop] of Object.entries(schema.properties)) {\n if (isAssociation(prop)) {\n associationNames.push(name);\n } else {\n propertyNames.push(name);\n }\n }\n }\n\n // Map 'object' to 'entity' for our API\n const kind = schema.kind === 'enum' ? 'enum' : 'entity';\n\n const result: SchemaMetadata = {\n name: schema.name,\n kind,\n filePath: schema.filePath,\n propertyNames,\n associationNames,\n hasTimestamps: schema.options?.timestamps ?? false,\n hasSoftDelete: schema.options?.softDelete ?? false,\n primaryKeyType: schema.options?.primaryKeyType ?? 'Int',\n };\n\n if (schema.displayName !== undefined) {\n result.displayName = schema.displayName;\n }\n if (schema.group !== undefined) {\n result.group = schema.group;\n }\n\n return result;\n}\n\n/**\n * Extracts property metadata.\n */\nexport function getPropertyMetadata(\n name: string,\n property: PropertyDefinition,\n registry?: PluginRegistry\n): PropertyMetadata {\n // Associations are handled separately\n if (isAssociation(property)) {\n return {\n name,\n type: 'Association',\n nullable: false,\n unique: false,\n hasDefault: false,\n isPluginType: false,\n };\n }\n\n const isPluginType = registry?.types.has(property.type) ?? false;\n const pluginType = registry?.types.get(property.type);\n\n const result: PropertyMetadata = {\n name,\n type: property.type,\n nullable: (property as { nullable?: boolean }).nullable ?? false,\n unique: (property as { unique?: boolean }).unique ?? false,\n hasDefault: 'default' in property && (property as { default?: unknown }).default !== undefined,\n isPluginType,\n };\n\n if ('default' in property && (property as { default?: unknown }).default !== undefined) {\n result.defaultValue = (property as { default?: unknown }).default;\n }\n\n if (pluginType?.pluginName !== undefined) {\n result.pluginName = pluginType.pluginName;\n }\n\n return result;\n}\n\n/**\n * Extracts association metadata.\n */\nexport function getAssociationMetadata(\n name: string,\n association: AssociationDefinition\n): AssociationMetadata {\n const result: AssociationMetadata = {\n name,\n relation: association.relation,\n target: association.target,\n };\n\n if (association.inversedBy !== undefined) {\n result.inversedBy = association.inversedBy;\n }\n if (association.mappedBy !== undefined) {\n result.mappedBy = association.mappedBy;\n }\n if (association.onDelete !== undefined) {\n result.onDelete = association.onDelete;\n }\n if (association.onUpdate !== undefined) {\n result.onUpdate = association.onUpdate;\n }\n\n return result;\n}\n\n/**\n * Full schema introspection.\n */\nexport function introspectSchema(\n schema: LoadedSchema,\n registry?: PluginRegistry\n): SchemaIntrospection {\n const metadata = getSchemaMetadata(schema);\n\n const properties: PropertyMetadata[] = [];\n const associations: AssociationMetadata[] = [];\n\n if (schema.properties) {\n for (const [name, prop] of Object.entries(schema.properties)) {\n if (isAssociation(prop)) {\n associations.push(getAssociationMetadata(name, prop));\n } else {\n properties.push(getPropertyMetadata(name, prop, registry));\n }\n }\n }\n\n return {\n metadata,\n properties,\n associations,\n schema,\n };\n}\n\n/**\n * Introspects all schemas in a collection.\n */\nexport function introspectSchemas(\n schemas: SchemaCollection,\n registry?: PluginRegistry\n): Map<string, SchemaIntrospection> {\n const result = new Map<string, SchemaIntrospection>();\n\n for (const [name, schema] of Object.entries(schemas)) {\n result.set(name, introspectSchema(schema, registry));\n }\n\n return result;\n}\n\n/**\n * Gets all schema names from a collection.\n */\nexport function getSchemaNames(schemas: SchemaCollection): string[] {\n return Object.keys(schemas);\n}\n\n/**\n * Gets schemas by kind.\n */\nexport function getSchemasByKind(\n schemas: SchemaCollection,\n kind: 'entity' | 'enum'\n): LoadedSchema[] {\n return Object.values(schemas).filter((schema) => {\n const schemaKind = schema.kind === 'enum' ? 'enum' : 'entity';\n return schemaKind === kind;\n });\n}\n\n/**\n * Gets entity schemas (non-enum).\n */\nexport function getEntitySchemas(schemas: SchemaCollection): LoadedSchema[] {\n return getSchemasByKind(schemas, 'entity');\n}\n\n/**\n * Gets enum schemas.\n */\nexport function getEnumSchemas(schemas: SchemaCollection): LoadedSchema[] {\n return getSchemasByKind(schemas, 'enum');\n}\n\n/**\n * Gets schemas by group.\n */\nexport function getSchemasByGroup(\n schemas: SchemaCollection,\n group: string\n): LoadedSchema[] {\n return Object.values(schemas).filter((schema) => schema.group === group);\n}\n\n/**\n * Gets all unique group names.\n */\nexport function getGroups(schemas: SchemaCollection): string[] {\n const groups = new Set<string>();\n\n for (const schema of Object.values(schemas)) {\n if (schema.group) {\n groups.add(schema.group);\n }\n }\n\n return Array.from(groups).sort();\n}\n\n/**\n * Gets associations from a schema.\n */\nfunction getSchemaAssociations(schema: LoadedSchema): AssociationDefinition[] {\n if (!schema.properties) return [];\n\n const associations: AssociationDefinition[] = [];\n for (const prop of Object.values(schema.properties)) {\n if (isAssociation(prop)) {\n associations.push(prop);\n }\n }\n return associations;\n}\n\n/**\n * Finds schemas that reference a target schema.\n */\nexport function findReferencingSchemas(\n schemas: SchemaCollection,\n targetName: string\n): LoadedSchema[] {\n const result: LoadedSchema[] = [];\n\n for (const schema of Object.values(schemas)) {\n const associations = getSchemaAssociations(schema);\n for (const association of associations) {\n if (association.target === targetName) {\n result.push(schema);\n break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Finds schemas referenced by a source schema.\n */\nexport function findReferencedSchemas(\n schemas: SchemaCollection,\n sourceName: string\n): LoadedSchema[] {\n const source = schemas[sourceName];\n if (!source) return [];\n\n const associations = getSchemaAssociations(source);\n const targetNames = new Set(associations.map((a) => a.target));\n\n return Object.values(schemas).filter((s) => targetNames.has(s.name));\n}\n\n/**\n * Gets the relationship graph as adjacency list.\n */\nexport function getRelationshipGraph(\n schemas: SchemaCollection\n): Map<string, string[]> {\n const graph = new Map<string, string[]>();\n\n for (const schema of Object.values(schemas)) {\n const targets: string[] = [];\n const associations = getSchemaAssociations(schema);\n\n for (const association of associations) {\n if (!targets.includes(association.target)) {\n targets.push(association.target);\n }\n }\n\n graph.set(schema.name, targets);\n }\n\n return graph;\n}\n\n/**\n * Checks if schemas form a valid DAG (no circular references).\n */\nexport function hasCircularReferences(schemas: SchemaCollection): boolean {\n const graph = getRelationshipGraph(schemas);\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n\n function hasCycle(node: string): boolean {\n if (recursionStack.has(node)) return true;\n if (visited.has(node)) return false;\n\n visited.add(node);\n recursionStack.add(node);\n\n const neighbors = graph.get(node) ?? [];\n for (const neighbor of neighbors) {\n if (hasCycle(neighbor)) return true;\n }\n\n recursionStack.delete(node);\n return false;\n }\n\n for (const schemaName of graph.keys()) {\n if (hasCycle(schemaName)) return true;\n }\n\n return false;\n}\n\n/**\n * Gets topological sort order for schemas (dependencies first).\n */\nexport function getTopologicalOrder(schemas: SchemaCollection): string[] {\n const graph = getRelationshipGraph(schemas);\n const result: string[] = [];\n const visited = new Set<string>();\n\n function visit(node: string): void {\n if (visited.has(node)) return;\n visited.add(node);\n\n const neighbors = graph.get(node) ?? [];\n for (const neighbor of neighbors) {\n visit(neighbor);\n }\n\n result.push(node);\n }\n\n for (const schemaName of graph.keys()) {\n visit(schemaName);\n }\n\n return result.reverse();\n}\n"],"mappings":";AAsCA,SAAS,IAAI,WAAW;;;AChBjB,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA;AAAA,EAE5B;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGS;AAAA,EAElB,YACE,SACA,MACA,UACA,YACA,SAIA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAIZ,QAAI,aAAa,QAAW;AAC1B,WAAK,WAAW;AAAA,IAClB;AACA,QAAI,eAAe,QAAW;AAC5B,WAAK,aAAa;AAAA,IACpB;AACA,QAAI,SAAS,YAAY,QAAW;AAClC,WAAK,UAAU,QAAQ;AAAA,IACzB;AACA,QAAI,SAA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 "name": "@famgia/omnify-core",
3
+ "version": "0.0.1",
4
+ "description": "Core engine for omnify-schema",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "dependencies": {
20
+ "js-yaml": "^4.1.1",
21
+ "@famgia/omnify-types": "0.0.1"
22
+ },
23
+ "devDependencies": {
24
+ "@types/js-yaml": "^4.0.9"
25
+ },
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "clean": "rm -rf dist",
29
+ "test": "vitest run --passWithNoTests",
30
+ "test:watch": "vitest",
31
+ "lint": "eslint src"
32
+ }
33
+ }