UNPKG

@meta-aiml/parser

Version:

AIML Parser SDK v2.0.0 - Comprehensive schema validation for Meta-AIML.org entity schemas

704 lines (658 loc) 27.6 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.AIMLParser = factory()); })(this, (function () { 'use strict'; function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", { writable: false }), e; } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } /** * @typedef {Object} AIMLValidationError * @property {string} field - Field with error * @property {string} message - Error message * @property {'error'|'warning'|'info'} severity - Error severity * @property {'structure'|'schema'|'semantic'|'performance'|'best_practice'} category - Error category * @property {string} [suggestion] - Fix suggestion * @property {string} [documentation] - Documentation link * @property {number} [line] - Line number * @property {number} [column] - Column number */ /** * @typedef {Object} AIMLEntityInfo * @property {string} entityType - Entity type * @property {string} entityCategory - Entity category * @property {string} [subcategory] - Subcategory * @property {string} baseSchema - Base schema * @property {string[]} modules - Active modules * @property {string[]} contexts - Applied contexts * @property {boolean} hasSemanticProperties - Has semantic properties * @property {boolean} hasIntentContext - Has intent context */ /** * @typedef {Object} AIMLValidationResult * @property {boolean} isValid - Is schema valid * @property {AIMLValidationError[]} errors - Critical errors * @property {AIMLValidationError[]} warnings - Warnings * @property {AIMLValidationError[]} suggestions - Improvement suggestions * @property {AIMLEntityInfo} [entityInfo] - Entity information * @property {number} score - Quality score (0-100) * @property {number} completeness - Completeness score (0-100) * @property {Object} performance - Performance metrics * @property {number} performance.schemaSize - Schema size in bytes * @property {'low'|'medium'|'high'} performance.complexity - Complexity level * @property {number} performance.moduleCount - Number of modules */ /** * @typedef {Object} AIMLSchema * @property {string} [@context] - JSON-LD context * @property {string} [@id] - Unique identifier * @property {string} [@type] - Entity type * @property {string} [schemaVersion] - AIML schema version * @property {string} [entityType] - AIML entity type * @property {string} [entityCategory] - Top-level category * @property {string} [subcategory] - Subcategory * @property {string|Object} [name] - Name (string or multilingual) * @property {string|Object} [description] - Description (string or multilingual) * @property {string} [url] - URL * @property {string} [shortDescription] - Short description * @property {Object} [properties] - Entity properties * @property {Object} [modules] - Enabled modules * @property {Object} [semanticProperties] - Semantic properties * @property {Object} [intentContext] - Intent context * @property {string[]} [appliedContexts] - Applied contexts */ // AIML v2.0.0 specifications - Complete and accurate var AIML_CONTEXT = 'https://schemas.meta-aiml.org/v2.0.0/context.jsonld'; var AIML_VERSION = '2.0.0'; var BASE_CATEGORIES = ['organization', 'product_offering', 'service', 'creative_work', 'community', 'financial_product']; var ENTITY_TYPES = { organization: ['clinic', 'education_platform', 'fitness_platform', 'hotel', 'restaurant', 'store'], product_offering: ['ecommerce_store', 'marketplace', 'product', 'software_product'], service: ['business_services', 'generative_ai_platform', 'real_estate_platform', 'ridesharing_service', 'task_management_app', 'telemedicine_platform', 'virtual_event_platform', 'web_app', 'website_services'], creative_work: ['blog', 'event', 'file_hosting', 'gaming_platform', 'news', 'personal_website', 'photo_hosting', 'streaming_platform', 'video_hosting'], community: ['dating_platform', 'social_network'], financial_product: ['online_banking'] }; var SUBCATEGORIES = { ecommerce_platform: ['ecommerce_store', 'marketplace', 'store'], hospitality: ['hotel', 'restaurant'], healthcare_services: ['clinic', 'fitness_platform', 'telemedicine_platform'], education_services: ['education_platform'], ai_platform: ['generative_ai_platform'], professional_services: ['business_services'], ridesharing_services: ['ridesharing_service'], website_services: ['website_services'], property_services: ['real_estate_platform'], physical_product: ['product'], digital_product: ['file_hosting', 'personal_website', 'software_product', 'task_management_app', 'web_app'], media_entertainment: ['blog', 'gaming_platform', 'news', 'photo_hosting', 'streaming_platform', 'video_hosting'], social_platform: ['dating_platform', 'social_network'], event_platform: ['event', 'virtual_event_platform'], financial_services: ['online_banking'] }; // Enhanced subcategory validation rules var SUBCATEGORY_VALIDATION_RULES = { professional_services: { allowedCategories: ['service'], description: 'Professional and business services' }, event_platform: { allowedCategories: ['creative_work', 'service'], description: 'Event organization and management platforms' }, physical_product: { allowedCategories: ['product_offering'], description: 'Physical goods and products' }, website_services: { allowedCategories: ['service'], description: 'Website development and maintenance services' }, gaming_platform: { allowedCategories: ['creative_work'], description: 'Gaming and interactive entertainment platforms' } }; var AVAILABLE_MODULES = ['auth', 'compliance', 'location', 'logistics', 'multilingual', 'notification', 'payments', 'recommendations', 'search', 'security', 'streaming', 'subscription', 'user_management', 'warranty']; var AVAILABLE_CONTEXTS = ['cultural_context', 'geographical_context', 'regulatory_context']; /** * AIML Parser SDK v2.0.0 - Official Release * * Comprehensive validation library for AIML entity schemas * Supporting all 31 entity types across 6 categories. * * @class AIMLParser */ var AIMLParser = /*#__PURE__*/function () { /** * Initialize AIML Parser * * @param {Object} [options] - Parser configuration * @param {boolean} [options.debug=false] - Enable debug mode * @param {boolean} [options.strict=false] - Enable strict validation * @param {string} [options.version='2.0.0'] - Target AIML version */ function AIMLParser() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, AIMLParser); this.config = { debug: options.debug || false, strict: options.strict || false, version: options.version || AIML_VERSION }; // State for validation this.errors = []; this.warnings = []; this.suggestions = []; } /** * Validate AIML schema * * @param {string|Object} data - Schema to validate (JSON string or object) * @returns {AIMLValidationResult} Validation result * * @example * const parser = new AIMLParser(); * const result = parser.validate(mySchema); * if (result.isValid) { * console.log('Valid!', result.score); * } else { * console.log('Errors:', result.errors); * } */ return _createClass(AIMLParser, [{ key: "validate", value: function validate(data) { // Reset state this.errors = []; this.warnings = []; this.suggestions = []; var schema; try { schema = typeof data === 'string' ? JSON.parse(data) : data; } catch (error) { this._addError('JSON', 'Invalid JSON syntax', 'structure', 'Please check for missing commas, brackets, or quotes'); return this._buildResult(false, null); } // Core validation pipeline this._validateRequiredFields(schema); this._validateContext(schema); this._validateVersioning(schema); this._validateEntityStructure(schema); this._validateNames(schema); this._validateModules(schema); this._validateSemanticProperties(schema); this._validateBestPractices(schema); var entityInfo = this._extractEntityInfo(schema); var isValid = this.errors.length === 0; return this._buildResult(isValid, entityInfo, schema); } /** * Quick validation without detailed analysis * @param {string|Object} data - Schema to validate * @returns {boolean} True if valid */ }, { key: "isValid", value: function isValid(data) { return this.validate(data).isValid; } /** * Get detailed entity information * @param {string|Object} data - Schema to analyze * @returns {AIMLEntityInfo|null} Entity information */ }, { key: "getEntityInfo", value: function getEntityInfo(data) { var result = this.validate(data); return result.entityInfo; } /** * Validate required fields * @private */ }, { key: "_validateRequiredFields", value: function _validateRequiredFields(schema) { var _this = this; var required = ['@context', 'entityType', 'entityCategory', 'name', 'description']; required.forEach(function (field) { if (!schema[field]) { _this._addError(field, "Required field '".concat(field, "' is missing"), 'structure', "Add the ".concat(field, " field to your schema")); } }); // Check for recommended fields var recommended = ['@id', '@type', 'schemaVersion', 'url', 'shortDescription']; recommended.forEach(function (field) { if (!schema[field]) { _this._addWarning(field, "Recommended field '".concat(field, "' is missing"), 'best_practice', "Consider adding ".concat(field, " for better schema completeness")); } }); } /** * Validate @context * @private */ }, { key: "_validateContext", value: function _validateContext(schema) { if (schema['@context'] && schema['@context'] !== AIML_CONTEXT) { this._addError('@context', 'Invalid @context value', 'structure', "Use \"".concat(AIML_CONTEXT, "\" for AIML v2.0.0 schemas")); } } /** * Validate versioning * @private */ }, { key: "_validateVersioning", value: function _validateVersioning(schema) { if (schema.schemaVersion && schema.schemaVersion !== AIML_VERSION) { this._addWarning('schemaVersion', "Schema version ".concat(schema.schemaVersion, " might not be current"), 'schema', "Consider using version ".concat(AIML_VERSION, " for latest features")); } } /** * Validate entity structure * @private */ }, { key: "_validateEntityStructure", value: function _validateEntityStructure(schema) { // Validate entity category if (schema.entityCategory && !BASE_CATEGORIES.includes(schema.entityCategory)) { this._addError('entityCategory', "Invalid entity category: ".concat(schema.entityCategory), 'schema', "Use one of: ".concat(BASE_CATEGORIES.join(', '))); } // Validate entity type against category if (schema.entityType && schema.entityCategory) { var validTypes = ENTITY_TYPES[schema.entityCategory] || []; if (validTypes.length > 0 && !validTypes.includes(schema.entityType)) { this._addError('entityType', "Entity type '".concat(schema.entityType, "' is not valid for category '").concat(schema.entityCategory, "'"), 'schema', "Valid types for ".concat(schema.entityCategory, ": ").concat(validTypes.join(', '))); } } // Validate subcategory if (schema.subcategory) { var validSubcategories = Object.keys(SUBCATEGORIES); if (!validSubcategories.includes(schema.subcategory)) { this._addWarning('subcategory', "Subcategory '".concat(schema.subcategory, "' might not be standard"), 'schema', "Common subcategories: ".concat(validSubcategories.join(', '))); } // Validate subcategory against entity category using additional rules if (schema.entityCategory && SUBCATEGORY_VALIDATION_RULES[schema.subcategory]) { var rule = SUBCATEGORY_VALIDATION_RULES[schema.subcategory]; if (!rule.allowedCategories.includes(schema.entityCategory)) { this._addError('subcategory', "Subcategory '".concat(schema.subcategory, "' is not valid for category '").concat(schema.entityCategory, "'"), 'schema', "Valid categories for ".concat(schema.subcategory, ": ").concat(rule.allowedCategories.join(', '))); } } // Validate entity type against subcategory if (schema.entityType && SUBCATEGORIES[schema.subcategory]) { var validTypesForSubcategory = SUBCATEGORIES[schema.subcategory]; if (!validTypesForSubcategory.includes(schema.entityType)) { this._addError('entityType', "Entity type '".concat(schema.entityType, "' is not valid for subcategory '").concat(schema.subcategory, "'"), 'schema', "Valid types for ".concat(schema.subcategory, ": ").concat(validTypesForSubcategory.join(', '))); } } } } /** * Validate names * @private */ }, { key: "_validateNames", value: function _validateNames(schema) { var _this2 = this; // Validate name structure (can be string or multilingual object) if (schema.name) { if (_typeof(schema.name) === 'object') { if (!schema.name.en) { this._addWarning('name', 'English name (en) is recommended in multilingual names', 'best_practice', 'Add an "en" field for better international compatibility'); } Object.keys(schema.name).forEach(function (lang) { if (!/^[a-z]{2}(-[A-Z]{2})?$/.test(lang)) { _this2._addWarning('name', "Language code '".concat(lang, "' might not be valid ISO 639-1 format"), 'best_practice', 'Use ISO 639-1 language codes (e.g., "en", "es", "fr", "en-US")'); } }); } else if (typeof schema.name === 'string') { this._addSuggestion('name', 'Consider using multilingual name object for better i18n support', 'best_practice', 'Convert string to object: {"en": "Your Name"}'); } } // Same validation for description if (schema.description && _typeof(schema.description) === 'object') { if (!schema.description.en) { this._addWarning('description', 'English description (en) is recommended', 'best_practice'); } } } /** * Validate modules * @private */ }, { key: "_validateModules", value: function _validateModules(schema) { var _this3 = this; if (schema.modules) { Object.keys(schema.modules).forEach(function (moduleKey) { if (!AVAILABLE_MODULES.includes(moduleKey)) { _this3._addWarning('modules', "Module '".concat(moduleKey, "' is not a standard AIML module"), 'schema', "Standard modules: ".concat(AVAILABLE_MODULES.join(', '))); } var module = schema.modules[moduleKey]; if (module && _typeof(module) === 'object') { if (!module.version) { _this3._addWarning("modules.".concat(moduleKey), 'Module should include version field', 'best_practice', 'Add version field for better compatibility tracking'); } if (!module.enabled) { _this3._addSuggestion("modules.".concat(moduleKey), 'Consider adding enabled field to module', 'best_practice', 'Add "enabled": true/false for better module management'); } } }); } } /** * Validate semantic properties * @private */ }, { key: "_validateSemanticProperties", value: function _validateSemanticProperties(schema) { var _this4 = this; if (schema.semanticProperties) { var semantic = schema.semanticProperties; // Check for standard semantic properties if (semantic.subjectiveQualities) { Object.values(semantic.subjectiveQualities).forEach(function (quality) { if (quality && _typeof(quality) === 'object') { if (quality.rating && (quality.rating < 0 || quality.rating > 1)) { _this4._addError('semanticProperties', 'Semantic quality ratings should be between 0 and 1', 'semantic', 'Use decimal values between 0.0 and 1.0'); } } }); } if (semantic.intentAlignment) { Object.values(semantic.intentAlignment).forEach(function (intent) { if (intent && _typeof(intent) === 'object') { if (intent.alignment && (intent.alignment < 0 || intent.alignment > 1)) { _this4._addError('semanticProperties', 'Intent alignment should be between 0 and 1', 'semantic'); } } }); } } else { this._addSuggestion('semanticProperties', 'Consider adding semantic properties for better AI understanding', 'semantic', 'Add subjectiveQualities and intentAlignment for enhanced semantic analysis'); } } /** * Validate best practices * @private */ }, { key: "_validateBestPractices", value: function _validateBestPractices(schema) { var _this5 = this; // URL validation if (schema.url && !/^https?:\/\/.+/.test(schema.url)) { this._addWarning('url', 'URL should start with http:// or https://', 'best_practice'); } // Description length check if (schema.description) { var desc = typeof schema.description === 'string' ? schema.description : schema.description.en; if (desc && desc.length < 50) { this._addSuggestion('description', 'Description is quite short, consider adding more detail', 'best_practice', 'Aim for at least 50-100 characters for better SEO and understanding'); } } // Check for applied contexts if (schema.appliedContexts) { schema.appliedContexts.forEach(function (context) { if (!AVAILABLE_CONTEXTS.includes(context)) { _this5._addWarning('appliedContexts', "Context '".concat(context, "' is not a standard AIML context"), 'schema', "Available contexts: ".concat(AVAILABLE_CONTEXTS.join(', '))); } }); } } /** * Extract entity info * @private */ }, { key: "_extractEntityInfo", value: function _extractEntityInfo(schema) { if (!schema.entityType || !schema.entityCategory) return null; var modules = schema.modules ? Object.keys(schema.modules) : []; var contexts = schema.appliedContexts || []; return { entityType: schema.entityType, entityCategory: schema.entityCategory, subcategory: schema.subcategory, baseSchema: schema.entityCategory, modules: modules, contexts: contexts, hasSemanticProperties: !!schema.semanticProperties, hasIntentContext: !!schema.intentContext }; } /** * Build validation result * @private */ }, { key: "_buildResult", value: function _buildResult(isValid, entityInfo, schema) { var score = this._calculateScore(); var completeness = this._calculateCompleteness(schema); var performance = this._calculatePerformance(schema); return { isValid: isValid, errors: this.errors, warnings: this.warnings, suggestions: this.suggestions, entityInfo: entityInfo, score: score, completeness: completeness, performance: performance }; } /** * Calculate score * @private */ }, { key: "_calculateScore", value: function _calculateScore() { var errorWeight = 30; var warningWeight = 10; var suggestionWeight = 5; var deductions = this.errors.length * errorWeight + this.warnings.length * warningWeight + this.suggestions.length * suggestionWeight; return Math.max(0, 100 - deductions); } /** * Calculate completeness * @private */ }, { key: "_calculateCompleteness", value: function _calculateCompleteness(schema) { if (!schema) return 0; var fields = ['@context', '@id', '@type', 'schemaVersion', 'entityType', 'entityCategory', 'subcategory', 'name', 'description', 'url', 'shortDescription', 'properties', 'modules', 'semanticProperties', 'intentContext', 'appliedContexts']; var presentFields = fields.filter(function (field) { return schema[field] !== undefined; }); return Math.round(presentFields.length / fields.length * 100); } /** * Calculate performance * @private */ }, { key: "_calculatePerformance", value: function _calculatePerformance(schema) { if (!schema) return { schemaSize: 0, complexity: 'low', moduleCount: 0 }; var schemaSize = JSON.stringify(schema).length; var moduleCount = schema.modules ? Object.keys(schema.modules).length : 0; var complexity = 'low'; if (moduleCount > 5 || schemaSize > 5000) complexity = 'high';else if (moduleCount > 2 || schemaSize > 2000) complexity = 'medium'; return { schemaSize: schemaSize, complexity: complexity, moduleCount: moduleCount }; } /** * Add error * @private */ }, { key: "_addError", value: function _addError(field, message, category, suggestion) { this.errors.push({ field: field, message: message, severity: 'error', category: category, suggestion: suggestion }); } /** * Add warning * @private */ }, { key: "_addWarning", value: function _addWarning(field, message, category, suggestion) { this.warnings.push({ field: field, message: message, severity: 'warning', category: category, suggestion: suggestion }); } /** * Add suggestion * @private */ }, { key: "_addSuggestion", value: function _addSuggestion(field, message, category, suggestion) { this.suggestions.push({ field: field, message: message, severity: 'info', category: category, suggestion: suggestion }); } }]); }(); // Static validation method - convenience method AIMLParser.validate = function (data) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var parser = new AIMLParser(options); return parser.validate(data); }; // Static factory methods AIMLParser.createProduction = function () { return new AIMLParser({ debug: false, strict: true }); }; AIMLParser.createDevelopment = function () { return new AIMLParser({ debug: true, strict: false }); }; // Utility methods AIMLParser.getVersion = function () { return AIML_VERSION; }; AIMLParser.getEntityTypes = function () { var allTypes = []; Object.values(ENTITY_TYPES).forEach(function (types) { allTypes.push.apply(allTypes, _toConsumableArray(types)); }); return allTypes.sort(); }; AIMLParser.getEntityCategories = function () { return BASE_CATEGORIES; }; AIMLParser.getModules = function () { return AVAILABLE_MODULES; }; AIMLParser.getContexts = function () { return AVAILABLE_CONTEXTS; }; AIMLParser.getSubcategories = function () { return Object.keys(SUBCATEGORIES); }; AIMLParser.validateConfig = function (options) { return !!(options && _typeof(options) === 'object'); }; // Export var src = AIMLParser; var index = /*@__PURE__*/getDefaultExportFromCjs(src); return index; })); //# sourceMappingURL=aiml-parser.js.map