UNPKG

credl-parser-evaluator

Version:

TypeScript-based CREDL Parser and Evaluator that processes CREDL files and outputs complete Intermediate Representations

436 lines 16.6 kB
"use strict"; /** * CREDL Parser and Evaluator - Main API Interface * * This module provides the main public API for parsing, validating, and generating * Intermediate Representation (IR) from CREDL (Commercial Real Estate Domain Language) files. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TemplateResolver = exports.PresetResolver = exports.IRBuilder = exports.SchemaValidator = exports.CREDLParser = void 0; exports.parse = parse; exports.parseStream = parseStream; exports.validate = validate; exports.generateIR = generateIR; exports.processFile = processFile; exports.processFileFromPath = processFileFromPath; exports.parseFileFromPath = parseFileFromPath; exports.writeIRToFile = writeIRToFile; exports.processMultipleFiles = processMultipleFiles; exports.checkFileExists = checkFileExists; exports.getFileStats = getFileStats; exports.processStream = processStream; exports.validateStream = validateStream; exports.createStreamFromString = createStreamFromString; exports.validateFile = validateFile; exports.getVersion = getVersion; const CREDLParser_1 = require("../parser/CREDLParser"); const SchemaValidator_1 = require("../parser/SchemaValidator"); const IRBuilder_1 = require("../engine/IRBuilder"); const stream_1 = require("stream"); /** * Parse a CREDL YAML string into typed objects * * @param yamlContent - The YAML content as a string * @returns Promise resolving to parsed CREDL file structure * @throws Error if parsing fails */ async function parse(yamlContent) { try { const result = CREDLParser_1.CREDLParser.parseString(yamlContent); if (!result.success) { const errorMessages = result.errors.map((e) => `${e.field}: ${e.message}`).join('; '); throw new Error(`CREDL parsing failed: ${errorMessages}`); } return result.data; } catch (error) { throw new Error(`Failed to parse CREDL content: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Parse CREDL content from a readable stream * * @param stream - Readable stream containing CREDL YAML content * @returns Promise resolving to parsed CREDL file structure * @throws Error if parsing fails */ async function parseStream(stream) { try { const result = await CREDLParser_1.CREDLParser.parseStream(stream); if (!result.success) { const errorMessages = result.errors.map((e) => `${e.field}: ${e.message}`).join('; '); throw new Error(`CREDL stream parsing failed: ${errorMessages}`); } return result.data; } catch (error) { throw new Error(`Failed to parse CREDL stream: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Validate a parsed CREDL file structure * * @param credlFile - The parsed CREDL file to validate * @param options - Optional validation options * @returns Promise resolving to validation result */ async function validate(credlFile, options) { try { return SchemaValidator_1.SchemaValidator.validate(credlFile, options); } catch (error) { return { isValid: false, errors: [{ field: 'validation', message: `Validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`, severity: 'error' }], warnings: [] }; } } /** * Generate complete IR from parsed and validated CREDL data * * @param credlFile - The parsed and validated CREDL file * @param options - Optional IR builder options * @returns Promise resolving to generated IR */ async function generateIR(credlFile, options) { try { return IRBuilder_1.IRBuilder.buildIR(credlFile, options); } catch (error) { throw new Error(`IR generation failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Parse, validate, and generate IR from CREDL content in one step * * @param yamlContent - The YAML content as a string * @param validationOptions - Optional validation options * @param irOptions - Optional IR builder options * @returns Promise resolving to generated IR */ async function processFile(yamlContent, validationOptions, irOptions) { try { // Step 1: Parse CREDL content const credlFile = await parse(yamlContent); // Step 2: Validate parsed content const validationResult = await validate(credlFile, validationOptions); // Step 3: Generate IR (even if validation has warnings) const ir = await generateIR(credlFile, irOptions); // Merge validation results into IR ir.validation.errors = [...ir.validation.errors, ...validationResult.errors]; ir.validation.warnings = [...ir.validation.warnings, ...validationResult.warnings]; ir.validation.isValid = ir.validation.isValid && validationResult.isValid; return ir; } catch (error) { throw new Error(`CREDL file processing failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Parse CREDL content from a file path using async file I/O (Node.js only) * * @param filePath - Path to the CREDL YAML file * @param validationOptions - Optional validation options * @param irOptions - Optional IR builder options * @returns Promise resolving to generated IR */ async function processFileFromPath(filePath, validationOptions, irOptions) { try { // Dynamic import to support both Node.js and browser environments const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const yamlContent = await fs.readFile(filePath, 'utf8'); return processFile(yamlContent, validationOptions, irOptions); } catch (error) { throw new Error(`Failed to process CREDL file from path "${filePath}": ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Read and parse CREDL content from a file path without full IR generation * * @param filePath - Path to the CREDL YAML file * @param options - Optional validation options * @returns Promise resolving to parsed and validated CREDL file */ async function parseFileFromPath(filePath, options) { try { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const yamlContent = await fs.readFile(filePath, 'utf8'); return validateFile(yamlContent, options); } catch (error) { return { isValid: false, errors: [{ field: 'file_parsing', message: `Failed to parse CREDL file from path "${filePath}": ${error instanceof Error ? error.message : 'Unknown error'}`, severity: 'error' }], warnings: [] }; } } /** * Write IR results to a JSON file using async file I/O (Node.js only) * * @param ir - The IR to write * @param outputPath - Path where to write the JSON file * @param pretty - Whether to format JSON with indentation (default: true) * @returns Promise resolving when file is written */ async function writeIRToFile(ir, outputPath, pretty = true) { try { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const jsonContent = pretty ? JSON.stringify(ir, null, 2) : JSON.stringify(ir); await fs.writeFile(outputPath, jsonContent, 'utf8'); } catch (error) { throw new Error(`Failed to write IR to file "${outputPath}": ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Process multiple CREDL files concurrently using async file I/O * * @param filePaths - Array of CREDL file paths to process * @param validationOptions - Optional validation options * @param irOptions - Optional IR builder options * @param maxConcurrency - Maximum number of files to process concurrently (default: 5) * @returns Promise resolving to array of IR results with file paths */ async function processMultipleFiles(filePaths, validationOptions, irOptions, maxConcurrency = 5) { const results = []; // Process files in batches to control concurrency for (let i = 0; i < filePaths.length; i += maxConcurrency) { const batch = filePaths.slice(i, i + maxConcurrency); const batchPromises = batch.map(async (filePath) => { try { const ir = await processFileFromPath(filePath, validationOptions, irOptions); return { filePath, ir }; } catch (error) { return { filePath, error: error instanceof Error ? error.message : 'Unknown error' }; } }); const batchResults = await Promise.all(batchPromises); results.push(...batchResults); } return results; } /** * Check if a file exists and is readable using async file I/O * * @param filePath - Path to check * @returns Promise resolving to true if file exists and is readable */ async function checkFileExists(filePath) { try { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); await fs.access(filePath, (await Promise.resolve().then(() => __importStar(require('fs')))).constants.R_OK); return true; } catch { return false; } } /** * Get file stats using async file I/O * * @param filePath - Path to get stats for * @returns Promise resolving to file stats or null if file doesn't exist */ async function getFileStats(filePath) { try { const fs = await Promise.resolve().then(() => __importStar(require('fs/promises'))); const stats = await fs.stat(filePath); return { size: stats.size, modified: stats.mtime }; } catch { return null; } } /** * Process CREDL content from a readable stream to generate IR * * @param stream - Readable stream containing CREDL YAML content * @param validationOptions - Optional validation options * @param irOptions - Optional IR builder options * @returns Promise resolving to generated IR */ async function processStream(stream, validationOptions, irOptions) { try { // Step 1: Parse CREDL content from stream const credlFile = await parseStream(stream); // Step 2: Validate parsed content const validationResult = await validate(credlFile, validationOptions); // Step 3: Generate IR (even if validation has warnings) const ir = await generateIR(credlFile, irOptions); // Merge validation results into IR ir.validation.errors = [...ir.validation.errors, ...validationResult.errors]; ir.validation.warnings = [...ir.validation.warnings, ...validationResult.warnings]; ir.validation.isValid = ir.validation.isValid && validationResult.isValid; return ir; } catch (error) { throw new Error(`CREDL stream processing failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Validate CREDL content from a readable stream without full IR generation * * @param stream - Readable stream containing CREDL YAML content * @param options - Optional validation options * @returns Promise resolving to validation result with parsed file */ async function validateStream(stream, options) { try { const credlFile = await parseStream(stream); const validationResult = await validate(credlFile, options); if (validationResult.isValid) { return { ...validationResult, credlFile: credlFile }; } else { return { ...validationResult }; } } catch (error) { return { isValid: false, errors: [{ field: 'stream_validation', message: `Stream validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`, severity: 'error' }], warnings: [] }; } } /** * Create a readable stream from a string (utility function) * * @param content - String content to convert to stream * @returns Readable stream containing the content */ function createStreamFromString(content) { const stream = new stream_1.Readable(); stream.push(content); stream.push(null); // End the stream return stream; } /** * Utility function to check if a CREDL file is valid without generating full IR * * @param yamlContent - The YAML content as a string * @param options - Optional validation options * @returns Promise resolving to validation result with parsed file */ async function validateFile(yamlContent, options) { try { const credlFile = await parse(yamlContent); const validationResult = await validate(credlFile, options); if (validationResult.isValid) { return { ...validationResult, credlFile: credlFile }; } else { return { ...validationResult }; } } catch (error) { return { isValid: false, errors: [{ field: 'file_validation', message: `File validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`, severity: 'error' }], warnings: [] }; } } /** * Get library version and metadata */ function getVersion() { return { version: '1.0.0', generator: 'CREDL Parser and Evaluator' }; } // Export all types for TypeScript users __exportStar(require("../types/CREDLTypes"), exports); // Export individual classes for advanced usage var CREDLParser_2 = require("../parser/CREDLParser"); Object.defineProperty(exports, "CREDLParser", { enumerable: true, get: function () { return CREDLParser_2.CREDLParser; } }); var SchemaValidator_2 = require("../parser/SchemaValidator"); Object.defineProperty(exports, "SchemaValidator", { enumerable: true, get: function () { return SchemaValidator_2.SchemaValidator; } }); var IRBuilder_2 = require("../engine/IRBuilder"); Object.defineProperty(exports, "IRBuilder", { enumerable: true, get: function () { return IRBuilder_2.IRBuilder; } }); var PresetResolver_1 = require("../engine/PresetResolver"); Object.defineProperty(exports, "PresetResolver", { enumerable: true, get: function () { return PresetResolver_1.PresetResolver; } }); var TemplateResolver_1 = require("../engine/TemplateResolver"); Object.defineProperty(exports, "TemplateResolver", { enumerable: true, get: function () { return TemplateResolver_1.TemplateResolver; } }); // Default export for convenience const credlApi = { parse, validate, generateIR, processFile }; exports.default = credlApi; //# sourceMappingURL=index.js.map