@kanonak-protocol/sdk 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,5 +1,5 @@
1
1
  var rr=Object.defineProperty;var nr=(p,e)=>()=>(p&&(e=p(p=0)),e);var or=(p,e)=>{for(var t in e)rr(p,t,{get:e[t],enumerable:!0})};var Dt={};or(Dt,{KanonakUri:()=>$});function sr(p,e,t){return{major:p,minor:e,patch:t,toString:()=>`${p}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===p&&r.minor===e&&r.patch===t,getHashCode:()=>p<<20|e<<10|t,compareTo:r=>p!==r.major?p-r.major:e!==r.minor?e-r.minor:t-r.patch}}var $,te=nr(()=>{"use strict";$=class p{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=n.indexOf("@");if(s===-1)return new p(r,n,o,void 0);let a=n.substring(0,s),i=n.substring(s+1);if(!a||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let c=i.split(".").map(Number),l=sr(c[0]||0,c[1]||0,c[2]||0);return new p(r,a,o,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});import*as Ue from"js-yaml";var E=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=Ue.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),Ue.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===s&&i.package_===o&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let c=0;c<s.length;c++)i=(i<<5)-i+s.charCodeAt(c);for(let c=0;c<o.length;c++)i=(i<<5)-i+o.charCodeAt(c);return i|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let i=0;i<o[1].length;i++)a=(a<<5)-a+o[1].charCodeAt(i);for(let i=0;i<o[2].length;i++)a=(a<<5)-a+o[2].charCodeAt(i);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),i=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:c,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let l={package:r,match:n,version:s.toString()};return c&&(l.alias=c),l},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let l=i[1].trim(),u=i[2],m=this.parseVersion(i[3].trim()),y=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:l,versionOperator:f,version:m,alias:y,minVersion:m,maxVersion:d,toEmbeddedObject:()=>{let g={package:l,match:u,version:m.toString()};return y&&(g.alias=y),g},toString:()=>`${l} ${u} ${m.toString()} as ${y}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let l=c[1].trim(),u=c[2],m=this.parseVersion(c[3].trim()),y=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:l,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:f,toEmbeddedObject:()=>({package:l,match:u,version:m.toString()}),toString:()=>`${l} ${u} ${m.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let i={package:o,match:s,version:n.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],i={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(i.alias=s.alias),i})};t.push(o)}return t}};var U=class{};var Y=class extends U{statement=[]};var C=class extends Y{namespace;name;icon};var T=class extends Y{name};te();var w=class p extends U{subject;static parse(e){let t=new p;return t.subject=$.parse(e),t}};var je=class extends U{value};var x=class{predicate;object};var L=class extends x{};var F=class p extends L{static parse(e,t){let r=new p;return r.predicate=w.parse(e),r.object=t,r}};var re=class p extends L{static parse(e,t){let r=new p;return r.predicate=w.parse(e),r.object=t,r}};var ne=class extends L{};var N=class p extends x{static parse(e,t){let r=new p;return r.predicate=w.parse(e),r.object=w.parse(t),r}};var B=class extends x{};var _=class extends x{};te();function S(p){if(Array.isArray(p))return p.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=p?.toString();return e?[e]:[]}var A=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new $(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:i,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((i,c)=>i+c.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[i,c]of Object.entries(e.metadata.imports))for(let l of c)try{this.logger?.debug?.(`Resolving import: ${i}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${l.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${i}/${l.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[i,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(i)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(i,{entityName:i,uri:new $(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,l),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((c,l)=>c+l.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(c,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,t,s),f=0;for(let[d,g]of y.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=S(s);for(let i of a)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=S(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var J=class p{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&p.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return p.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Ee=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new A(e),o=new J(n);for(let i of r){let c=i.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(i.body)){let m=new C,y=this.resolveCanonicalEntity(l,i,c);m.namespace=y.namespace,m.name=y.name,m.statement=[];let f=await this.parseStatements(u,i,n,o,e);m.statement.push(...f),t.push(m)}}let s=new Map,a=[];for(let i of t)if(i instanceof C){let c=`${i.namespace}/${i.name}`,l=s.get(c);l?l.statement.push(...i.statement):(s.set(c,i),a.push(i))}else a.push(i);return a}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let n=e.indexOf("."),o=e.substring(0,n),s=e.substring(n+1);for(let[a,i]of Object.entries(t.metadata.imports))for(let c of i)if((c.alias??c.packageName)===o){let u=c.version;return{namespace:`${a}/${c.packageName}@${u.major}.${u.minor}.${u.patch}`,name:s}}return{namespace:r,name:e}}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,i]of Object.entries(e))try{let c=await this.getPropertyMetadata(a,t,r,o,n);if(!c)continue;let l=await this.parsePropertyValue(a,i,c,t,r,n);l&&s.push(l)}catch(c){console.error(`Error parsing property ${a}:`,c)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,i=a.type?.toString()??"",c=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let u=o.getPropertyTypeClassification(i),m=a.range?.toString(),y;if(u==="ObjectProperty")y="ObjectProperty";else if(u==="DatatypeProperty")y="DatatypeProperty";else{let d=m&&m.includes(".")?m.substring(m.lastIndexOf(".")+1):m??"";(m?o.isKnownXsdDatatypeName(m):!1)||d==="Literal"?y="DatatypeProperty":y="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:y,range:m,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return F.parse(e,t.toISOString());if(typeof t=="string")return F.parse(e,t);if(typeof t=="number")return re.parse(e,t);if(typeof t=="boolean"){let n=new ne;return n.predicate=w.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let i=new N;return i.predicate=w.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new T;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let l=new B;return l.predicate=w.parse(e),l.object=a,l}let i=[];for(let[l,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new T;m.name=l,m.statement=await this.parseStatements(u,n,o,s,{}),i.push(m)}else if(typeof u=="string"){let m=await this.resolveReference(u,n,o);m&&i.push(m)}if(i.length>0){let l=new _;return l.predicate=w.parse(e),l.object=i,l}let c=new B;return c.predicate=w.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[],i=r.propertyType==="DatatypeProperty";for(let l of t){if(i&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new je;u.value=l,a.push(u);continue}if(i&&l instanceof Date){let u=new je;u.value=l.toISOString(),a.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,n,o);u&&a.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new T;u.statement=await this.parseStatements(l,n,o,s,{}),a.push(u)}}let c=new _;return c.predicate=w.parse(e),c.object=a,c}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new w;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(te(),Dt)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),l=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[m,y]of Object.entries(t.metadata.imports))for(let f of y)if((f.alias??f.packageName)===l){let g=new w;return g.subject=new s(m,f.packageName,u,f.version),g}}}let i=new w;return i.subject=new s(o.publisher,o.package_,e,a),i}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof C&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),a=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,a)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof C&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new E().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let i of s.statement){let[c,l]=this.convertStatementToProperty(i);c&&l!==null&&l!==void 0&&(a[c]=l),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof F)return[e.predicate.subject.name,e.object];if(e instanceof re)return[e.predicate.subject.name,e.object];if(e instanceof ne)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof _){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof B){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof w?t.push(r.subject.name):r instanceof T&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var Le=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as ar,LineCounter as ir,isMap as xe,isPair as V,isScalar as j,isSeq as Fe}from"yaml";var Oe=class p{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new p,r=new ir,n=ar(e,{lineCounter:r});if(n.errors.length>0||!xe(n.contents))return t;mt(n.contents,[],r,t);for(let o of n.contents.items){if(!V(o)||!j(o.key))continue;let s=String(o.key.value),a=o.key.range;if(!a)continue;t.entities.set(s,M(a,r));let i=o.value,c=i&&typeof i=="object"&&"range"in i?i.range:void 0;if(c?t.entityBlocks.set(s,M([a[0],a[1],c[2]],r)):t.entityBlocks.set(s,M(a,r)),xe(o.value)){let l=new Map,u=new Map,m=new Map;for(let f of o.value.items){if(!V(f)||!j(f.key))continue;let d=String(f.key.value),g=f.key.range;g&&l.set(d,M(g,r));let h=f.value;if(h&&typeof h=="object"&&"range"in h&&Array.isArray(h.range)){let b=h.range;u.set(d,M(b,r))}if(Fe(h)){let b=[];for(let R of h.items)R&&typeof R=="object"&&"range"in R&&Array.isArray(R.range)&&b.push(M(R.range,r));b.length>0&&m.set(d,b)}}l.size>0&&t.properties.set(s,l),u.size>0&&t.propertyValues.set(s,u),m.size>0&&t.valueListItems.set(s,m);let y=cr(o.value,r);y.length>0&&t.importPackages.set(s,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(ut(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,a;if(o)for(let[i,c]of o)ut(c,e,t)&&(!a||St(c,a))&&(s=i,a=c);if(n)for(let[i,c]of n)ut(c,e,t)&&(!a||St(c,a))&&(s=i,a=c);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function cr(p,e){let t=[];if(!xe(p))return t;let r=p.items.find(n=>V(n)&&j(n.key)&&String(n.key.value)==="imports");if(!r||!V(r)||!Fe(r.value))return t;for(let n of r.value.items){if(!xe(n))continue;let o=n.items.find(i=>V(i)&&j(i.key)&&String(i.key.value)==="publisher");if(!o||!V(o)||!j(o.value))continue;let s=String(o.value.value),a=n.items.find(i=>V(i)&&j(i.key)&&String(i.key.value)==="packages");if(!(!a||!V(a)||!Fe(a.value)))for(let i of a.value.items){if(!xe(i))continue;let c=i.items.find(g=>V(g)&&j(g.key)&&String(g.key.value)==="package");if(!c||!V(c)||!j(c.value)||!c.value.range)continue;let l=String(c.value.value),u=i.items.find(g=>V(g)&&j(g.key)&&String(g.key.value)==="version"),m=u&&V(u)&&j(u.value)?String(u.value.value):"",y=i.items.find(g=>V(g)&&j(g.key)&&String(g.key.value)==="alias"),f=y&&V(y)&&j(y.value)?String(y.value.value):void 0,d=f!==void 0?{publisher:s,package_:l,version:m,alias:f,position:M(c.value.range,e)}:{publisher:s,package_:l,version:m,position:M(c.value.range,e)};t.push(d)}}return t}function ut(p,e,t){return!(e<p.line||e>p.endLine||e===p.line&&t<p.column||e===p.endLine&&t>p.endColumn)}function St(p,e){let t=p.endLine-p.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=p.endLine===p.line?p.endColumn-p.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function mt(p,e,t,r){if(xe(p)){for(let n of p.items){if(!V(n)||!j(n.key))continue;let o=String(n.key.value),s=[...e,o],a=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(a,M(n.key.range,t));let i=n.value,c=Vt(i);c&&r.setNestedValuePosition(a,M(c,t)),mt(i,s,t,r)}return}if(Fe(p)){for(let n=0;n<p.items.length;n++){let o=p.items[n],s=[...e,n],a=JSON.stringify(s),i=Vt(o);i&&r.setNestedValuePosition(a,M(i,t)),mt(o,s,t,r)}return}}function Vt(p){if(!p||typeof p!="object"||!("range"in p))return;let e=p.range;return Array.isArray(e)&&e.length>=3?e:void 0}function M(p,e){let t=e.linePos(p[0]),r=e.linePos(p[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function Kt(p,e){let r=(e??new E).parse(p),n=Oe.fromContent(p);return{document:r,positions:n}}var pr=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),$t={Class:{publisher:"kanonak.org",package_:"core-owl"},ObjectProperty:{publisher:"kanonak.org",package_:"core-owl"},DatatypeProperty:{publisher:"kanonak.org",package_:"core-owl"},AnnotationProperty:{publisher:"kanonak.org",package_:"core-owl"},Property:{publisher:"kanonak.org",package_:"core-rdf"},Datatype:{publisher:"kanonak.org",package_:"core-rdfs"},Resource:{publisher:"kanonak.org",package_:"core-rdfs"},Literal:{publisher:"kanonak.org",package_:"core-rdfs"},Thing:{publisher:"kanonak.org",package_:"core-owl"},Nothing:{publisher:"kanonak.org",package_:"core-owl"}};function W(p){let e=p;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=$t[t];return r?{publisher:r.publisher,package_:r.package_,name:t}:{publisher:"",package_:"",name:t}}}if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t.object?.subject){let r=t.object.subject;if(!r.publisher&&!r.package_||r.publisher===""&&r.package_===""){let n=$t[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function G(p,e){return pr.has(`${p}/${e}`)}var I=class p{static getTypeUri(e){return W(e)}static isCoreOntologyType(e){return G(e.publisher,e.package_)}static isClassType(e){let t=W(e);return t?G(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=W(e);return t?G(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=W(e);return t?G(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=W(e);return t?G(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=W(e);return t?G(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=W(e);return t?G(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=W(e);return!t||!G(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=W(e);return!t||!G(t.publisher,t.package_)?!1:t.name==="Class"||t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"||t.name==="Datatype"}static isInstanceOfKnownClass(e,t){if(p.isSchemaDefinitionType(e))return!1;let r=W(e);return r?t.has(r.name):!1}};var ft=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(ft||{}),dt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(dt||{}),Be=class{static async buildFromRepository(e){let r=await new Ee().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,i=new Set,c=new Map;for(let u of r){let m=u;m.name&&(I.isClassType(m)&&a.add(m.name),(I.isObjectPropertyType(m)||I.isGenericPropertyType(m))&&i.add(m.name))}for(let u of n)for(let[m,y]of Object.entries(u.body))i.has(m)&&y?.range&&typeof y.range=="string"&&c.set(m,y.range);let l=new Map;for(let u of r){let m=u;m.name&&l.set(m.name,m)}for(let u of n){let m=u.metadata.namespace_,y=m?`${m.publisher}/${m.package_}`:"",f=m?.version?`${m.version.major}.${m.version.minor}.${m.version.patch}`:"",d=jt(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=l.get(g),R="Unknown";if(b){let K=b;I.isClassType(K)?R="Class":I.isObjectPropertyType(K)?R="ObjectProperty":I.isDatatypePropertyType(K)?R="DatatypeProperty":I.isAnnotationPropertyType(K)?R="AnnotationProperty":I.isDatatypeType(K)?R="Datatype":I.isGenericPropertyType(K)?R="ObjectProperty":I.isInstanceOfKnownClass(K,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,D={};for(let[K,lt]of Object.entries(h))K!=="type"&&(typeof lt!="object"||lt===null)&&(D[K]=lt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:D}),Et(v,h,R,a,i,s,y,f,d),yt(v,h,i,c,o,s,y,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,i=new Set,c=new Map,l=jt(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(ur(d,l)&&a.add(y),mr(d,l)&&(i.add(y),f.range&&typeof f.range=="string"&&c.set(y,f.range)))}for(let[y,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=yr(d,y,a,l),h=s&&o?`${s}/${y}@${o}`:y,b={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(b[R]=v);t.push({id:h,label:f.label??y,type:g,namespace:s,properties:b}),Et(h,f,g,a,i,r,s,o,l),yt(h,f,i,c,t,r,s,o,l)}let u=new Set(t.map(y=>y.id)),m=r.filter(y=>u.has(y.source)&&u.has(y.target));return{nodes:t,edges:m}}};function jt(p,e){let t=new Map;if(p.metadata?.imports)for(let[r,n]of Object.entries(p.metadata.imports))for(let o of n){let s=o.alias??o.packageName,a=o.version,i=`${a.major}.${a.minor}.${a.patch}`;t.set(s,{publisher:r,package_:o.packageName,version:i})}return t}var xt={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},lr=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function gt(p,e){if(p.includes(".")){let t=p.indexOf("."),r=p.substring(0,t),n=p.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function ur(p,e){let t=gt(p,e);return t?xt[t]==="Class":!1}function mr(p,e){let t=gt(p,e);return t?lr.has(t):!1}function yr(p,e,t,r){if(!p||p==="Package")return"Unknown";let n=gt(p,r);if(n){let s=xt[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=p.split(".").pop()??p;return t.has(o)?"Instance":"Unknown"}var Ot=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Et(p,e,t,r,n,o,s,a,i){let c=e.type,l=e.subClassOf;if(l){let f=Array.isArray(l)?l:[l];for(let d of f)typeof d=="string"&&o.push({source:p,target:Z(d,s,a,i),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let f=Array.isArray(u)?u:[u];for(let d of f)typeof d=="string"&&o.push({source:p,target:Z(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:p,target:Z(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Ot.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&fr(h)&&o.push({source:p,target:Z(h,s,a,i),type:"propertyValue",label:f,propertyId:Z(f,s,a,i)})}let m=t==="ObjectProperty"||t==="DatatypeProperty",y=e.domain&&e.range;if((m||y)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:Z(f,s,a,i),target:Z(d,s,a,i),type:"objectRelationship",label:e.label??p.split("/").pop()??"",propertyId:p})}}function yt(p,e,t,r,n,o,s,a,i){for(let[c,l]of Object.entries(e)){if(Ot.has(c)||typeof l!="object"||l===null||Array.isArray(l))continue;let u=l,m=`${p}/${c}`,y=r.get(c),f=y?y.split(".").pop()??y:"Unknown",d={};for(let[h,b]of Object.entries(u))(typeof b!="object"||b===null)&&(d[h]=b);n.push({id:m,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:p,target:m,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),y&&o.push({source:m,target:Z(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),yt(m,u,t,r,n,o,s,a,i)}}function fr(p){return!(!p||p.includes(" ")||p.includes(`
2
- `)||p.startsWith("http://")||p.startsWith("https://")||/^\d{4}-\d{2}/.test(p)||/^\d+(\.\d+)?$/.test(p))}function Z(p,e,t,r){if(p.includes("@")&&p.includes("/"))return p;if(p.includes(".")){let n=p.indexOf("."),o=p.substring(0,n),s=p.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${p}@${t}`:p}var oe=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var We=class p{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new p;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var se=class p{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&p.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=n,c.expectedValue=a,c.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var ae=class p{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){if(!r&&p.RESERVED_WORDS.has(n.toLowerCase())){let s=new k;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Entity name '${n}' is a reserved word and cannot be used.`,s.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(s);continue}if(!p.VALID_NAME_PATTERN.test(n)){let s;/^\d/.test(n)?s="Entity names must start with a letter, not a number.":n.includes(" ")?s="Entity names cannot contain spaces. Use camelCase or underscores instead.":s="Entity names must start with a letter and contain only letters, numbers, and underscores.";let a=new k;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Invalid entity name '${n}'. ${s}`,a.suggestion=s,t.push(a)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!p.VALID_PROPERTIES.has(n)&&!p.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var ie=class p{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let i=[];if(Array.isArray(a))for(let c of a){let l=c?.toString();l&&l==="Property"&&!r&&i.push(l)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let l=this.getPropertyValue(s,"range"),u=this.determinePropertyType(l),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=c,m.expectedValue=u,m.message=`Invalid property type '${c}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":p.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var ce=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let i=new k;i.ruleType=this.ruleName,i.severity="Error",i.entityName=r,i.propertyName="type",i.message=`Subject Kanonak '${r}' must have a 'type' property.`,i.suggestion=`Add a type statement like:
2
+ `)||p.startsWith("http://")||p.startsWith("https://")||/^\d{4}-\d{2}/.test(p)||/^\d+(\.\d+)?$/.test(p))}function Z(p,e,t,r){if(p.includes("@")&&p.includes("/"))return p;if(p.includes(".")){let n=p.indexOf("."),o=p.substring(0,n),s=p.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${p}@${t}`:p}var oe=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var We=class p{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new p;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var se=class p{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&p.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=n,c.expectedValue=a,c.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var ae=class p{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){let s=p.VALID_AUGMENTATION_PATTERN.test(n);if(!s&&!r&&p.RESERVED_WORDS.has(n.toLowerCase())){let a=new k;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Entity name '${n}' is a reserved word and cannot be used.`,a.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(a);continue}if(!s&&!p.VALID_NAME_PATTERN.test(n)){let a;/^\d/.test(n)?a="Entity names must start with a letter, not a number.":n.includes(" ")?a="Entity names cannot contain spaces. Use camelCase or underscores instead.":a="Entity names must start with a letter and contain only letters, numbers, and underscores.";let i=new k;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Invalid entity name '${n}'. ${a}`,i.suggestion=a,t.push(i)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!p.VALID_PROPERTIES.has(n)&&!p.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var ie=class p{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let i=[];if(Array.isArray(a))for(let c of a){let l=c?.toString();l&&l==="Property"&&!r&&i.push(l)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let l=this.getPropertyValue(s,"range"),u=this.determinePropertyType(l),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=c,m.expectedValue=u,m.message=`Invalid property type '${c}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":p.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var ce=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||r.includes("."))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let i=new k;i.ruleType=this.ruleName,i.severity="Error",i.entityName=r,i.propertyName="type",i.message=`Subject Kanonak '${r}' must have a 'type' property.`,i.suggestion=`Add a type statement like:
3
3
  type: Scene
4
4
 
5
5
  Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,i.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(i)}}return t}};var pe=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,t){let r=[],n=new A(t),o=await this.buildPropertyRangeMap(e,n);for(let[s,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.checkEmbeddedTypes(s,a,void 0,o,n,e,r,0);return r}async checkEmbeddedTypes(e,t,r,n,o,s,a,i){if(i>0){let c=t.type;if(c!=null){let l=await this.validateEmbeddedType(e,String(c),r,o,s);l&&a.push(l)}}for(let[c,l]of Object.entries(t)){let u=this.localName(c),m=n.has(u)?n.get(u):r;if(typeof l=="object"&&l!==null)if(Array.isArray(l))for(let y=0;y<l.length;y++){let f=l[y];typeof f=="object"&&f!==null&&!Array.isArray(f)&&await this.checkEmbeddedTypes(`${e}.${c}[${y}]`,f,m,n,o,s,a,i+1)}else await this.checkEmbeddedTypes(`${e}.${c}`,l,m,n,o,s,a,i+1)}}async validateEmbeddedType(e,t,r,n,o){if(t.length===0||!r)return null;let s=this.localName(t),a=this.localName(r);if(a==="Resource"||a==="Class")return null;let i=e.split(".")[0];if(s===a){let l=new k;return l.ruleType=this.ruleName,l.severity="Warning",l.entityName=i,l.propertyName=e,l.actualValue=t,l.expectedValue=r,l.message=`Embedded object at '${e}' declares 'type: ${t}', which equals the parent property's range '${r}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,l.suggestion=`Remove the 'type: ${t}' line, or keep it if explicitness is preferred over concision.`,l}if(await n.isSubclassOfAsync(t,r,o)||(s!==t||a!==r)&&await n.isSubclassOfAsync(s,a,o))return null;let c=new k;return c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=t,c.expectedValue=r,c.message=`Embedded object at '${e}' has 'type: ${t}', which is not a subclass of the parent property's range '${r}'.`,c.suggestion=`Either remove the 'type: ${t}' line (so the type is inferred from the property's range '${r}'), or add 'subClassOf: ${r}' to the '${t}' class definition so the relationship holds.`,c}localName(e){let t=e.lastIndexOf(".");return t<0||t===e.length-1?e:e.substring(t+1)}async buildPropertyRangeMap(e,t){let r=new Map,n=await t.buildEntityIndexAsync(e);for(let[o,s]of n){let a=s.entity.type;if(a==null)continue;let i=String(a),c=this.localName(i);if(!(c==="Property"||c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty"))continue;let u=s.entity.range;if(u==null)continue;let m=String(u);m.length!==0&&r.set(this.localName(o),m)}return r}};var le=class{ruleName="ImportExistence";async validateAsync(e,t){let r=[];if(!e.metadata?.imports)return r;let n=await t.getAllDocumentsAsync();for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!await t.getHighestCompatibleVersionAsync(o,a)){let c=await this.determineImportErrorAsync(t,o,a,n),l=new k;l.ruleType=this.ruleName,l.severity="Error",l.message=c.message,l.suggestion=c.suggestion,l.entityName=`Import: ${o}/${a.packageName}`,l.actualValue=a.toString(),l.expectedValue=c.expectedValue,r.push(l)}return r}async determineImportErrorAsync(e,t,r,n){let o=await e.getDocumentsByNamespaceAsync(t,r.packageName);if(o.length===0){let c=n.filter(y=>y.metadata.namespace_?.publisher===t).map(y=>y.metadata.namespace_.package_).filter((y,f,d)=>d.indexOf(y)===f),l=this.findSimilarPackages(r.packageName,c),u=`Import '${t}/${r.package_}' not found - package does not exist`,m=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:c.length>0?`Available packages in ${t}: ${c.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:u,suggestion:m,expectedValue:"Existing package"}}let a=o.filter(c=>c.metadata.namespace_?.version).map(c=>c.metadata.namespace_.version.toString()).sort().join(", "),i=this.getAcceptableVersionRange(r);return{message:`Import '${t}/${r.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${i}`,expectedValue:i}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let r=t.filter(s=>s.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(s.toLowerCase()));if(r.length>0)return r.sort((s,a)=>s.length-a.length);let n=t.map(s=>({package:s,distance:this.levenshteinDistance(e.toLowerCase(),s.toLowerCase())})).sort((s,a)=>s.distance-a.distance),o=Math.max(3,Math.floor(e.length*.4));return n.filter(s=>s.distance<=o).map(s=>s.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let r=e.length,n=t.length,o=Array(r+1).fill(null).map(()=>Array(n+1).fill(0));for(let s=0;s<=r;s++)o[s][0]=s;for(let s=0;s<=n;s++)o[0][s]=s;for(let s=1;s<=r;s++)for(let a=1;a<=n;a++){let i=e[s-1]===t[a-1]?0:1;o[s][a]=Math.min(Math.min(o[s-1][a]+1,o[s][a-1]+1),o[s-1][a-1]+i)}return o[r][n]}};var ue=class{ruleName="UnresolvedReference";async validateAsync(e,t){let r=[],n=new A(t),o=await n.buildEntityIndexAsync(e),s=new Set;for(let[a,i]of o.entries()){let c=i.entity.type;if(c){let l=c.toString();(l==="ObjectProperty"||l.endsWith(".ObjectProperty"))&&s.add(a)}}for(let[a,i]of Object.entries(e.body)){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,l=this.getPropertyValue(c,"type");if(!(!l||l==="Class"||l.endsWith("Property")||l==="AnnotationProperty"))for(let[u,m]of Object.entries(c))u==="type"||u==="label"||u==="comment"||!(s.has(u)||Array.from(s).some(f=>f.endsWith(`.${u}`)))||await this.validateReferenceValue(a,u,m,e,n,r)}return r}async validateReferenceValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string")await o.resolveEntityAsync(r,n)||s.push(this.createUnresolvedReferenceError(e,t,r));else if(Array.isArray(r))for(let a=0;a<r.length;a++){let i=r[a];typeof i=="string"&&(await o.resolveEntityAsync(i,n)||s.push(this.createUnresolvedReferenceError(e,`${t}[${a}]`,i)))}}}createUnresolvedReferenceError(e,t,r){let n=`The entity '${r}' cannot be found in the current document or any imported namespaces.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  var sn=Object.defineProperty;var an=(i,e)=>()=>(i&&(e=i(i=0)),e);var cn=(i,e)=>{for(var t in e)sn(i,t,{get:e[t],enumerable:!0})};var hr={};cn(hr,{KanonakUri:()=>T});function yn(i,e,t){return{major:i,minor:e,patch:t,toString:()=>`${i}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===i&&r.minor===e&&r.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:r=>i!==r.major?i-r.major:e!==r.minor?e-r.minor:t-r.patch}}var T,le=an(()=>{"use strict";T=class i{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=n.indexOf("@");if(s===-1)return new i(r,n,o,void 0);let a=n.substring(0,s),c=n.substring(s+1);if(!a||!c)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let p=c.split(".").map(Number),l=yn(p[0]||0,p[1]||0,p[2]||0);return new i(r,a,o,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});function F(i,e){return i.major!==e.major?i.major-e.major:i.minor!==e.minor?i.minor-e.minor:i.patch-e.patch}function _e(i,e){return i.major===e.major&&i.minor===e.minor&&i.patch===e.patch}function Gt(i){return`${i.major}.${i.minor}.${i.patch}`}function zt(i,e,t){let r=`${i}.${e}.${t}`;return{major:i,minor:e,patch:t,toString:()=>r,equals:n=>n?.major===i&&n?.minor===e&&n?.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:n=>i!==n.major?i-n.major:e!==n.minor?e-n.minor:t-n.patch}}function mr(i){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(i);return e?zt(Number(e[1]),Number(e[2]),Number(e[3])):null}function Ue(i,e){return F(i,e)>=0&&i.major===e.major&&i.minor===e.minor}function Le(i,e){return e.major===0?F(i,e)>=0&&i.major===0&&i.minor===e.minor:F(i,e)>=0&&i.major===e.major}function yr(i,e={}){let{requestedVersion:t}=e;if(i.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let n=i.find(o=>{let s=o.metadata.namespace_?.version;return!!s&&Gt(s)===t});return n?{chosen:n,alternatives:i.filter(o=>o!==n),multipleVersionsPresent:i.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:i,multipleVersionsPresent:i.length>1,exactRequestedVersionMissing:!0}}if(i.length===1)return{chosen:i[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let r=[...i].sort((n,o)=>{let s=n.metadata.namespace_?.version,a=o.metadata.namespace_?.version;return!s&&!a?0:s?a?F(a,s):-1:1});return{chosen:r[0],alternatives:r.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}var mt=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let r=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===e&&n.metadata?.namespace_?.package_===t&&r.push(n);return r}async getHighestCompatibleVersionAsync(e,t){let r=[];for(let o of this.documents.values())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t.packageName&&o.metadata?.namespace_?.version!==void 0&&r.push(o);if(r.length===0)return null;let n=r.filter(o=>{let s=o.metadata.namespace_.version;if(!s)return!1;switch(t.versionOperator){case 0:return _e(s,t.version);case 1:return Ue(s,t.version);case 2:return Le(s,t.version);case 3:return F(s,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((o,s)=>{let a=o.metadata.namespace_.version,c=s.metadata.namespace_.version;return!a&&!c?0:a?c?F(c,a):-1:1}),n[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let r=this.parser.save(e);this.documentContents.set(t,r)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let r=[];for(let[n,o]of this.documents.entries())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t&&r.push(n);for(let n of r)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let r=this.documents.get(e);return r!==void 0?this.parser.save(r):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}};import*as K from"fs/promises";import*as D from"path";import{pathToFileURL as fr}from"url";import*as yt from"js-yaml";var $=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=yt.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),yt.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:c=>!c||typeof c!="object"?!1:c.publisher===s&&c.package_===o&&(!a||!c.version||a.equals(c.version)),getHashCode:()=>{let c=0;for(let p=0;p<s.length;p++)c=(c<<5)-c+s.charCodeAt(p);for(let p=0;p<o.length;p++)c=(c<<5)-c+o.charCodeAt(p);return c|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<o[1].length;c++)a=(a<<5)-a+o[1].charCodeAt(c);for(let c=0;c<o[2].length;c++)a=(a<<5)-a+o[2].charCodeAt(c);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),c=this.calculateMaxVersion(n,s),p=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:p,minVersion:s,maxVersion:c,toEmbeddedObject:()=>{let l={package:r,match:n,version:s.toString()};return p&&(l.alias=p),l},toString:()=>p?`${r} ${n} ${s.toString()} as ${p}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let c=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(c){let l=c[1].trim(),u=c[2],m=this.parseVersion(c[3].trim()),y=c[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:l,versionOperator:f,version:m,alias:y,minVersion:m,maxVersion:d,toEmbeddedObject:()=>{let g={package:l,match:u,version:m.toString()};return y&&(g.alias=y),g},toString:()=>`${l} ${u} ${m.toString()} as ${y}`}}let p=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(p){let l=p[1].trim(),u=p[2],m=this.parseVersion(p[3].trim()),y=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:l,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:f,toEmbeddedObject:()=>({package:l,match:u,version:m.toString()}),toString:()=>`${l} ${u} ${m.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let c={package:o,match:s,version:n.toString()};return e.alias&&(c.alias=e.alias),c},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],c={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(c.alias=s.alias),c})};t.push(o)}return t}};var ce=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,r){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=D.resolve(e),this.recursive=t,this.parser=r??new $,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let r=D.join(this.rootPath,e);if(t=this.documentCache.get(r),t)return t;for(let n of[".kan.yml",".yml",".yaml"])if(!e.endsWith(n)){let o=e+n;if(t=this.documentCache.get(o),t)return t;let s=D.join(this.rootPath,o);if(t=this.documentCache.get(s),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values());return Array.from(r).filter(n=>n.metadata.namespace_?.publisher===e&&n.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values()),n=Array.from(r).filter(s=>s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0);if(n.length===0)return null;let o=n.filter(s=>{let a=s.metadata.namespace_.version;switch(t.versionOperator){case 0:return _e(a,t.version);case 1:return Ue(a,t.version);case 2:return Le(a,t.version);case 3:return F(a,t.minVersion)>=0;default:return!1}});return o.length===0?null:(o.sort((s,a)=>{let c=s.metadata.namespace_.version,p=a.metadata.namespace_.version;return F(p,c)}),o[0])}async saveDocumentAsync(e,t){let r,n=e.metadata.namespace_?.toString();if(n&&n.includes("@")&&n.includes("/")){let c=n.split("/"),p=c[0],u=c[1].replace("@","@")+".kan.yml";r=D.join(this.rootPath,p,u)}else r=D.join(this.rootPath,t),!r.endsWith(".yml")&&!r.endsWith(".yaml")&&!r.endsWith(".kan.yml")&&(r+=".kan.yml");let o=D.dirname(r);await K.mkdir(o,{recursive:!0});let s=this.parser.save(e);await K.writeFile(r,s,"utf8"),n&&this.documentCache.set(n,e),this.documentCache.set(r,e);let a=D.relative(this.rootPath,r);this.documentCache.set(a,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let r=this.filePathsByIdentifier.get(e);if(!r)return;try{await K.unlink(r)}catch{}let n=t.metadata.namespace_?.toString();n&&this.documentCache.delete(n),this.documentCache.delete(e),this.documentCache.delete(r);let o=D.relative(this.rootPath,r);this.documentCache.delete(o)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=[];for(let[o,s]of this.documentCache.entries()){let a=s.metadata.namespace_?.toString()||"";a.includes(e)&&a.includes(t)&&r.push([o,s])}let n=D.join(this.rootPath,e);try{let o=await K.readdir(n);for(let s of o)s.includes(t)&&s.endsWith(".kan.yml")&&await K.unlink(D.join(n,s))}catch{}for(let[o]of r)this.documentCache.delete(o)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let r of e){let n=fr(r).toString(),o;for(let[c,p]of this.documentCache.entries())if(this.filePathsByIdentifier.get(c)===r&&p.metadata.namespace_){o=p.metadata.namespace_.toString();break}let s=o??D.relative(this.rootPath,r),a=this.parsingErrors.has(r);t.push({identifier:s,uri:n,hasParseError:a})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await K.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await K.access(r),t=r}catch{return null}}try{return await K.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await K.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await K.access(r),t=r}catch{return null}}return fr(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await K.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async n=>{try{let o=await K.readFile(n,"utf8"),s=this.parser.parse(o);return{filePath:n,document:s,error:null}}catch(o){return{filePath:n,document:null,error:o instanceof Error?o.message:String(o)}}}),r=await Promise.all(t);for(let{filePath:n,document:o,error:s}of r){let a=D.relative(this.rootPath,n);if(o&&o.metadata.namespace_){let c=o.metadata.namespace_.toString();this.documentCache.set(c,o),this.documentCache.set(n,o),this.documentCache.set(a,o),this.filePathsByIdentifier.set(c,n),this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n)}else this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n);s&&this.parsingErrors.set(n,s)}}async findYamlFiles(e,t){let r=[];try{let n=await K.readdir(e,{withFileTypes:!0});for(let o of n){let s=D.join(e,o.name);if(o.isDirectory()&&t){let a=await this.findYamlFiles(s,t);r.push(...a)}else o.isFile()&&o.name.endsWith(".kan.yml")&&r.push(s)}}catch{}return r}};import*as Me from"fs";var Xt=(r=>(r.NotFound="NotFound",r.Workspace="Workspace",r.Cache="Cache",r))(Xt||{}),Fe=class{cache;workspace;constructor(e,t,r){let n=r??new $;Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0}),this.cache=new ce(e,!0,n),this.workspace=new ce(t,!0,n)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),r=new Map;for(let n of t)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}for(let n of e)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}return Array.from(r.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let r=await this.workspace.getDocumentsByNamespaceAsync(e,t),n=await this.cache.getDocumentsByNamespaceAsync(e,t),o=new Map;for(let s of n)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}for(let s of r)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}return Array.from(o.values())}async getHighestCompatibleVersionAsync(e,t){let r=await this.workspace.getHighestCompatibleVersionAsync(e,t);return r||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),r=[];return r.push(...e),r.push(...t),r}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as pn}from"os";import{join as ln}from"path";function Qe(){let i=process.env.KANONAK_PACKAGE_CACHE;return i||ln(pn(),".kanonak","packages")}var ft=class i{static createComposite(e,t,r){let n=e??Qe(),o=t??".";return new Fe(n,o,r)}static createFromEnvironment(e){let t=Qe(),r=process.env.KANONAK_WORKSPACE_PATH??".";return i.createComposite(t,r,e)}};import{VersionOperator as dt}from"@kanonak-protocol/types/document/models/enums";var un="https://{publisher}/index.txt",mn="https://{publisher}/{package}/{version}.kan.yml",dr={version:1},Be=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let r=await this.fetchConfig(e);return this.cache.set(e,r),r}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await fetch(t)}catch{return dr}if(r.status===404)return dr;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${t} (${r.status} ${r.statusText})`);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let o={version:n.version};return typeof n.index=="string"&&(o.index=n.index),typeof n.package=="string"&&(o.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(o.auth=n.auth),o}resolveIndexUrl(e,t){let r=t.index??un;return gr(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??mn;return gr(o,{publisher:e,package:t,version:r})}};function gr(i,e){let t=i;for(let[n,o]of Object.entries(e))t=t.replaceAll(`{${n}}`,o);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${i}`);return t}var pe=class i{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Be,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(o=>this.isVersionCompatible(o,t.version,t.versionOperator));return n.length===0?null:(n.sort((o,s)=>this.compareVersionStrings(s,o)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((o,s)=>this.compareVersionStrings(s,o))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let r=[];for(let[n,o]of t){if(o.length===0)continue;let s=[...o].sort((a,c)=>this.compareVersionStrings(c,a));r.push({packageName:n,version:s[0]})}return r.sort((n,o)=>n.packageName.localeCompare(o.packageName)),r}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let o=await n.text();return i.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
2
2
  `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("/");if(o===-1)continue;let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)continue;let c=t.get(s);c?c.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=i.parseVersion(e);if(!n)return!1;switch(r){case dt.Any:return!0;case dt.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case dt.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case dt.Major:return n.major!==t.major?!1:n.minor>t.minor?!0:n.minor===t.minor?n.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let r=parseInt(t[0],10),n=parseInt(t[1],10),o=t.length>=3?parseInt(t[2],10):0;return isNaN(r)||isNaN(n)||isNaN(o)?null:{major:r,minor:n,patch:o}}compareVersionStrings(e,t){let r=i.parseVersion(e),n=i.parseVersion(t);return!r&&!n?0:r?n?r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch:1:-1}};var gt=class{parser=new $;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new pe({fetchFn:e.fetchFn}):new pe}async getHighestCompatibleVersionAsync(e,t){let r=await this.publisherIndex.resolveVersion(e,t);if(!r)return null;let n=`${e}/${t.packageName}@${r}`,o=this.documents.get(n);if(o)return o;if(this.getFromCache){let l=this.getFromCache(e,t.packageName,r);if(l){let u=this.parser.parse(l);return this.documents.set(n,u),this.contentCache.set(n,l),u}}let s=await this.publisherIndex.getPackageUrl(e,t.packageName,r),a=this.fetchFn?await this.fetchFn(s,e):await fetch(s);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${s} (${a.status} ${a.statusText})`);let c=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,c);let p=this.parser.parse(c);return this.documents.set(n,p),this.contentCache.set(n,c),p}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,o]=t;return this.publisherIndex.getPackageUrl(r,n,o)}};var z=class{};var re=class extends z{statement=[]};var N=class extends re{namespace;name;icon};var _=class extends re{name};le();var w=class i extends z{subject;static parse(e){let t=new i;return t.subject=T.parse(e),t}};var Z=class extends z{value};var B=class{predicate;object};var X=class extends B{};var W=class i extends X{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=t,r}};var Q=class i extends X{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=t,r}};var ee=class extends X{};var U=class i extends B{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=w.parse(t),r}};var H=class extends B{};var L=class extends B{};le();function E(i){if(Array.isArray(i))return i.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=i?.toString();return e?[e]:[]}var j=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new T(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${c}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(c,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${l.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${c}/${l.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[c,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)&&!n.has(c)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(c,{entityName:c,uri:new T(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,l),entity:p,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((p,l)=>p+l.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${o}`);for(let[p,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${p}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(p,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,t,s),f=0;for(let[d,g]of y.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${u.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${p}/${u.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${p}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=E(s);for(let c of a)if(c===t||await this.isSubclassOfRecursiveAsync(c,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=E(s);for(let c of a)if(c===t||await this.isSubpropertyOfRecursiveAsync(c,t,r,n))return!0}return!1}};var ne=class i{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&i.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return i.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var oe=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new j(e),o=new ne(n);for(let c of r){let p=c.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(c.body)){let m=new N,y=this.resolveCanonicalEntity(l,c,p);m.namespace=y.namespace,m.name=y.name,m.statement=[];let f=await this.parseStatements(u,c,n,o,e);m.statement.push(...f),t.push(m)}}let s=new Map,a=[];for(let c of t)if(c instanceof N){let p=`${c.namespace}/${c.name}`,l=s.get(p);l?l.statement.push(...c.statement):(s.set(p,c),a.push(c))}else a.push(c);return a}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let n=e.indexOf("."),o=e.substring(0,n),s=e.substring(n+1);for(let[a,c]of Object.entries(t.metadata.imports))for(let p of c)if((p.alias??p.packageName)===o){let u=p.version;return{namespace:`${a}/${p.packageName}@${u.major}.${u.minor}.${u.patch}`,name:s}}return{namespace:r,name:e}}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,c]of Object.entries(e))try{let p=await this.getPropertyMetadata(a,t,r,o,n);if(!p)continue;let l=await this.parsePropertyValue(a,c,p,t,r,n);l&&s.push(l)}catch(p){console.error(`Error parsing property ${a}:`,p)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,c=a.type?.toString()??"",p=c.includes(".")?c.substring(c.lastIndexOf(".")+1):c;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let u=o.getPropertyTypeClassification(c),m=a.range?.toString(),y;if(u==="ObjectProperty")y="ObjectProperty";else if(u==="DatatypeProperty")y="DatatypeProperty";else{let d=m&&m.includes(".")?m.substring(m.lastIndexOf(".")+1):m??"";(m?o.isKnownXsdDatatypeName(m):!1)||d==="Literal"?y="DatatypeProperty":y="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:y,range:m,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return W.parse(e,t.toISOString());if(typeof t=="string")return W.parse(e,t);if(typeof t=="number")return Q.parse(e,t);if(typeof t=="boolean"){let n=new ee;return n.predicate=w.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let c=new U;return c.predicate=w.parse(e),c.object=a,c}if(typeof t=="object"&&!Array.isArray(t)){let a=new _;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let l=new H;return l.predicate=w.parse(e),l.object=a,l}let c=[];for(let[l,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new _;m.name=l,m.statement=await this.parseStatements(u,n,o,s,{}),c.push(m)}else if(typeof u=="string"){let m=await this.resolveReference(u,n,o);m&&c.push(m)}if(c.length>0){let l=new L;return l.predicate=w.parse(e),l.object=c,l}let p=new H;return p.predicate=w.parse(e),p.object=a,p}}async parseListValue(e,t,r,n,o,s){let a=[],c=r.propertyType==="DatatypeProperty";for(let l of t){if(c&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new Z;u.value=l,a.push(u);continue}if(c&&l instanceof Date){let u=new Z;u.value=l.toISOString(),a.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,n,o);u&&a.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new _;u.statement=await this.parseStatements(l,n,o,s,{}),a.push(u)}}let p=new L;return p.predicate=w.parse(e),p.object=a,p}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new w;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(le(),hr)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),l=e.substring(0,p),u=e.substring(p+1);if(t.metadata?.imports){for(let[m,y]of Object.entries(t.metadata.imports))for(let f of y)if((f.alias??f.packageName)===l){let g=new w;return g.subject=new s(m,f.packageName,u,f.version),g}}}let c=new w;return c.subject=new s(o.publisher,o.package_,e,a),c}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof N&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),a=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,a)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof N&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new $().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let c of s.statement){let[p,l]=this.convertStatementToProperty(c);p&&l!==null&&l!==void 0&&(a[p]=l),this.collectImportsFromStatement(c,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof W)return[e.predicate.subject.name,e.object];if(e instanceof Q)return[e.predicate.subject.name,e.object];if(e instanceof ee)return[e.predicate.subject.name,e.object];if(e instanceof U)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof L){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof H){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof w?t.push(r.subject.name):r instanceof _&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var fn=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),kr={Class:{publisher:"kanonak.org",package_:"core-owl"},ObjectProperty:{publisher:"kanonak.org",package_:"core-owl"},DatatypeProperty:{publisher:"kanonak.org",package_:"core-owl"},AnnotationProperty:{publisher:"kanonak.org",package_:"core-owl"},Property:{publisher:"kanonak.org",package_:"core-rdf"},Datatype:{publisher:"kanonak.org",package_:"core-rdfs"},Resource:{publisher:"kanonak.org",package_:"core-rdfs"},Literal:{publisher:"kanonak.org",package_:"core-rdfs"},Thing:{publisher:"kanonak.org",package_:"core-owl"},Nothing:{publisher:"kanonak.org",package_:"core-owl"}};function Y(i){let e=i;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=kr[t];return r?{publisher:r.publisher,package_:r.package_,name:t}:{publisher:"",package_:"",name:t}}}if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t.object?.subject){let r=t.object.subject;if(!r.publisher&&!r.package_||r.publisher===""&&r.package_===""){let n=kr[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function te(i,e){return fn.has(`${i}/${e}`)}var I=class i{static getTypeUri(e){return Y(e)}static isCoreOntologyType(e){return te(e.publisher,e.package_)}static isClassType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=Y(e);return!t||!te(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=Y(e);return!t||!te(t.publisher,t.package_)?!1:t.name==="Class"||t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"||t.name==="Datatype"}static isInstanceOfKnownClass(e,t){if(i.isSchemaDefinitionType(e))return!1;let r=Y(e);return r?t.has(r.name):!1}};var Jt=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(Jt||{}),Zt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(Zt||{}),ht=class{static async buildFromRepository(e){let r=await new oe().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,c=new Set,p=new Map;for(let u of r){let m=u;m.name&&(I.isClassType(m)&&a.add(m.name),(I.isObjectPropertyType(m)||I.isGenericPropertyType(m))&&c.add(m.name))}for(let u of n)for(let[m,y]of Object.entries(u.body))c.has(m)&&y?.range&&typeof y.range=="string"&&p.set(m,y.range);let l=new Map;for(let u of r){let m=u;m.name&&l.set(m.name,m)}for(let u of n){let m=u.metadata.namespace_,y=m?`${m.publisher}/${m.package_}`:"",f=m?.version?`${m.version.major}.${m.version.minor}.${m.version.patch}`:"",d=br(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=l.get(g),R="Unknown";if(b){let V=b;I.isClassType(V)?R="Class":I.isObjectPropertyType(V)?R="ObjectProperty":I.isDatatypePropertyType(V)?R="DatatypeProperty":I.isAnnotationPropertyType(V)?R="AnnotationProperty":I.isDatatypeType(V)?R="Datatype":I.isGenericPropertyType(V)?R="ObjectProperty":I.isInstanceOfKnownClass(V,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,x={};for(let[V,qt]of Object.entries(h))V!=="type"&&(typeof qt!="object"||qt===null)&&(x[V]=qt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:x}),Rr(v,h,R,a,c,s,y,f,d),Yt(v,h,c,p,o,s,y,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,c=new Set,p=new Map,l=br(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(gn(d,l)&&a.add(y),hn(d,l)&&(c.add(y),f.range&&typeof f.range=="string"&&p.set(y,f.range)))}for(let[y,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=kn(d,y,a,l),h=s&&o?`${s}/${y}@${o}`:y,b={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(b[R]=v);t.push({id:h,label:f.label??y,type:g,namespace:s,properties:b}),Rr(h,f,g,a,c,r,s,o,l),Yt(h,f,c,p,t,r,s,o,l)}let u=new Set(t.map(y=>y.id)),m=r.filter(y=>u.has(y.source)&&u.has(y.target));return{nodes:t,edges:m}}};function br(i,e){let t=new Map;if(i.metadata?.imports)for(let[r,n]of Object.entries(i.metadata.imports))for(let o of n){let s=o.alias??o.packageName,a=o.version,c=`${a.major}.${a.minor}.${a.patch}`;t.set(s,{publisher:r,package_:o.packageName,version:c})}return t}var vr={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},dn=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Qt(i,e){if(i.includes(".")){let t=i.indexOf("."),r=i.substring(0,t),n=i.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function gn(i,e){let t=Qt(i,e);return t?vr[t]==="Class":!1}function hn(i,e){let t=Qt(i,e);return t?dn.has(t):!1}function kn(i,e,t,r){if(!i||i==="Package")return"Unknown";let n=Qt(i,r);if(n){let s=vr[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=i.split(".").pop()??i;return t.has(o)?"Instance":"Unknown"}var Pr=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Rr(i,e,t,r,n,o,s,a,c){let p=e.type,l=e.subClassOf;if(l){let f=Array.isArray(l)?l:[l];for(let d of f)typeof d=="string"&&o.push({source:i,target:se(d,s,a,c),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let f=Array.isArray(u)?u:[u];for(let d of f)typeof d=="string"&&o.push({source:i,target:se(d,s,a,c),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&p){let f=p.split(".").pop()??p;o.push({source:i,target:se(f,s,a,c),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Pr.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&bn(h)&&o.push({source:i,target:se(h,s,a,c),type:"propertyValue",label:f,propertyId:se(f,s,a,c)})}let m=t==="ObjectProperty"||t==="DatatypeProperty",y=e.domain&&e.range;if((m||y)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:se(f,s,a,c),target:se(d,s,a,c),type:"objectRelationship",label:e.label??i.split("/").pop()??"",propertyId:i})}}function Yt(i,e,t,r,n,o,s,a,c){for(let[p,l]of Object.entries(e)){if(Pr.has(p)||typeof l!="object"||l===null||Array.isArray(l))continue;let u=l,m=`${i}/${p}`,y=r.get(p),f=y?y.split(".").pop()??y:"Unknown",d={};for(let[h,b]of Object.entries(u))(typeof b!="object"||b===null)&&(d[h]=b);n.push({id:m,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${p}@${a}`:p;o.push({source:i,target:m,type:"propertyValue",label:p,propertyId:t.has(p)?g:void 0}),y&&o.push({source:m,target:se(f,s,a,c),type:"instanceOf",label:"type (inferred)"}),Yt(m,u,t,r,n,o,s,a,c)}}function bn(i){return!(!i||i.includes(" ")||i.includes(`
3
- `)||i.startsWith("http://")||i.startsWith("https://")||/^\d{4}-\d{2}/.test(i)||/^\d+(\.\d+)?$/.test(i))}function se(i,e,t,r){if(i.includes("@")&&i.includes("/"))return i;if(i.includes(".")){let n=i.indexOf("."),o=i.substring(0,n),s=i.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${i}@${t}`:i}function We(i){return`${i.publisher}/${i.package_}/${i.name}`}function C(i,e,t){return`${i}/${e}/${t}`}function et(i){return`${i.s}|${i.p}|${er(i.o)}`}function er(i){switch(i.kind){case"uri":return`u:${i.key}`;case"literal":return`l:${i.datatype}:${i.lexical}`;case"blank":return`b:${i.id}`}}function A(i,e,t){return{s:i,p:e,o:{kind:"uri",key:t}}}var He=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=et(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),tr(this.byPIdx,e.p,e),tr(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&tr(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(et(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)n.add(o.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)o.o.kind==="uri"&&n.add(o.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${er(r)}`)}};function tr(i,e,t){let r=i.get(e);r?r.push(t):i.set(e,[t])}var qe=class{type=C("kanonak.org","core-rdf","type");subClassOf=C("kanonak.org","core-rdf","subClassOf");subPropertyOf=C("kanonak.org","core-rdf","subPropertyOf");domain=C("kanonak.org","core-rdf","domain");range=C("kanonak.org","core-rdf","range");equivalentClass=C("kanonak.org","core-owl","equivalentClass");equivalentProperty=C("kanonak.org","core-owl","equivalentProperty");inverseOf=C("kanonak.org","core-owl","inverseOf");sameAs=C("kanonak.org","core-owl","sameAs");transitiveProperty=C("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=C("kanonak.org","core-owl","SymmetricProperty")};var Rn={name:"rdfs2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},vn={name:"rdfs3",apply(i,e){let t=!1;for(let r of i.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,e.type,o))&&(t=!0)}return t}},Pn={name:"rdfs5",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subPropertyOf))s.o.kind==="uri"&&i.add(A(n,e.subPropertyOf,s.o.key))&&(t=!0)}return t}},wn={name:"rdfs7",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n)){let a={s:s.s,p:o,o:s.o};i.add(a)&&(t=!0)}}return t}},In={name:"rdfs9",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},Sn={name:"rdfs11",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subClassOf))s.o.kind==="uri"&&i.add(A(n,e.subClassOf,s.o.key))&&(t=!0)}return t}},tt=[Rn,vn,Pn,wn,In,Sn];var An={name:"prp-trp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let o=i.byPredicate(n);for(let s of o){if(s.o.kind!=="uri")continue;let a=s.o.key;for(let c of i.bySubjectPredicate(a,n))c.o.kind==="uri"&&s.s!==c.o.key&&i.add(A(s.s,n,c.o.key))&&(t=!0)}}return t}},Dn={name:"prp-symp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let o of i.byPredicate(n))o.o.kind==="uri"&&i.add(A(o.o.key,n,o.s))&&(t=!0);return t}},Kn={name:"prp-inv1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,o,s.s))&&(t=!0)}return t}},Cn={name:"prp-inv2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(o))s.o.kind==="uri"&&i.add(A(s.o.key,n,s.s))&&(t=!0)}return t}},$n={name:"prp-eqp1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n))i.add({s:s.s,p:o,o:s.o})&&(t=!0)}return t}},jn={name:"prp-eqp2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(o))i.add({s:s.s,p:n,o:s.o})&&(t=!0)}return t}},xn={name:"cax-eqc1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},En={name:"cax-eqc2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,o))i.add(A(s.s,e.type,n))&&(t=!0)}return t}},On={name:"eq-rep-s",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o){for(let s of i.snapshot())s.s===n&&i.add({s:o,p:s.p,o:s.o})&&(t=!0);for(let s of i.snapshot())s.s===o&&i.add({s:n,p:s.p,o:s.o})&&(t=!0)}}return t}},Vn={name:"eq-rep-o",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.snapshot())s.o.kind==="uri"&&(s.o.key===n?i.add(A(s.s,s.p,o))&&(t=!0):s.o.key===o&&i.add(A(s.s,s.p,n))&&(t=!0))}return t}},rt=[An,Dn,Kn,Cn,$n,jn,xn,En,On,Vn];var ze=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=Ge(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(Ge(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(Ge(e),this.vocabulary.type,Ge(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function Ge(i){return typeof i=="string"?i:C(i.publisher,i.package_,i.name)}var kt=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new qe,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new He,n=await new oe().parseKanonaks(e),o=new rr;for(let c of n)if(c instanceof N){let p=Tn(c);if(!p)continue;for(let l of c.statement)this.emitStatement(p,l,t,o)}let s=[...tt];this.profile==="owl-rl-classification"&&s.push(...rt);let a=0;for(;a<this.maxIterations;){let c=!1;for(let p of s)p.apply(t,this.vocabulary)&&(c=!0);if(!c)break;a++}return new ze(t,this.vocabulary)}emitStatement(e,t,r,n){let o=Nn(t);if(o){if(t instanceof W){r.add({s:e,p:o,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof Q){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof ee){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof U){let s=We(t.object.subject);r.add(A(e,o,s));return}if(t instanceof H){let s=n.next();r.add({s:e,p:o,o:{kind:"blank",id:s}}),this.emitEmbedded(s,t.object,r,n);return}if(t instanceof L){for(let s of t.object??[])this.emitListItem(e,o,s,r,n);return}}}emitListItem(e,t,r,n,o){if(r instanceof w)n.add(A(e,t,We(r.subject)));else if(r instanceof _){let s=o.next();n.add({s:e,p:t,o:{kind:"blank",id:s}}),this.emitEmbedded(s,r,n,o)}else if(r instanceof Z){let s=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:s}})}}emitEmbedded(e,t,r,n){let o=`_:${e}`;for(let s of t.statement)this.emitStatement(o,s,r,n)}},rr=class{counter=0;next(){return`b${this.counter++}`}};function Tn(i){let e=i.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let o=r.substring(0,n),s=r.substring(n+1);return!o||!s||!i.name?null:C(o,s,i.name)}function Nn(i){let e=i.predicate;return e?.subject?We(e.subject):null}import _n from"ignore";import*as Rt from"fs";import*as Xe from"path";var bt=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=Xe.join(e,".gitignore");if(Rt.existsSync(t))try{let r=Rt.readFileSync(t,"utf8");this.ignoreInstance=_n(),this.ignoreInstance.add(r)}catch{this.ignoreInstance=null}else this.ignoreInstance=null}shouldIgnore(e){if(!this.ignoreInstance)return!1;let r=Xe.relative(this.basePath,e).split(Xe.sep).join("/");return this.ignoreInstance.ignores(r)}};var vt=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as Un,LineCounter as Ln,isMap as Ye,isPair as O,isScalar as M,isSeq as Pt}from"yaml";var Je=class i{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new i,r=new Ln,n=Un(e,{lineCounter:r});if(n.errors.length>0||!Ye(n.contents))return t;or(n.contents,[],r,t);for(let o of n.contents.items){if(!O(o)||!M(o.key))continue;let s=String(o.key.value),a=o.key.range;if(!a)continue;t.entities.set(s,G(a,r));let c=o.value,p=c&&typeof c=="object"&&"range"in c?c.range:void 0;if(p?t.entityBlocks.set(s,G([a[0],a[1],p[2]],r)):t.entityBlocks.set(s,G(a,r)),Ye(o.value)){let l=new Map,u=new Map,m=new Map;for(let f of o.value.items){if(!O(f)||!M(f.key))continue;let d=String(f.key.value),g=f.key.range;g&&l.set(d,G(g,r));let h=f.value;if(h&&typeof h=="object"&&"range"in h&&Array.isArray(h.range)){let b=h.range;u.set(d,G(b,r))}if(Pt(h)){let b=[];for(let R of h.items)R&&typeof R=="object"&&"range"in R&&Array.isArray(R.range)&&b.push(G(R.range,r));b.length>0&&m.set(d,b)}}l.size>0&&t.properties.set(s,l),u.size>0&&t.propertyValues.set(s,u),m.size>0&&t.valueListItems.set(s,m);let y=Mn(o.value,r);y.length>0&&t.importPackages.set(s,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(nr(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,a;if(o)for(let[c,p]of o)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);if(n)for(let[c,p]of n)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function Mn(i,e){let t=[];if(!Ye(i))return t;let r=i.items.find(n=>O(n)&&M(n.key)&&String(n.key.value)==="imports");if(!r||!O(r)||!Pt(r.value))return t;for(let n of r.value.items){if(!Ye(n))continue;let o=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="publisher");if(!o||!O(o)||!M(o.value))continue;let s=String(o.value.value),a=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="packages");if(!(!a||!O(a)||!Pt(a.value)))for(let c of a.value.items){if(!Ye(c))continue;let p=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="package");if(!p||!O(p)||!M(p.value)||!p.value.range)continue;let l=String(p.value.value),u=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="version"),m=u&&O(u)&&M(u.value)?String(u.value.value):"",y=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="alias"),f=y&&O(y)&&M(y.value)?String(y.value.value):void 0,d=f!==void 0?{publisher:s,package_:l,version:m,alias:f,position:G(p.value.range,e)}:{publisher:s,package_:l,version:m,position:G(p.value.range,e)};t.push(d)}}return t}function nr(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function wr(i,e){let t=i.endLine-i.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function or(i,e,t,r){if(Ye(i)){for(let n of i.items){if(!O(n)||!M(n.key))continue;let o=String(n.key.value),s=[...e,o],a=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(a,G(n.key.range,t));let c=n.value,p=Ir(c);p&&r.setNestedValuePosition(a,G(p,t)),or(c,s,t,r)}return}if(Pt(i)){for(let n=0;n<i.items.length;n++){let o=i.items[n],s=[...e,n],a=JSON.stringify(s),c=Ir(o);c&&r.setNestedValuePosition(a,G(c,t)),or(o,s,t,r)}return}}function Ir(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function G(i,e){let t=e.linePos(i[0]),r=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function Sr(i,e){let r=(e??new $).parse(i),n=Je.fromContent(i);return{document:r,positions:n}}le();le();var wt=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,r){if(e.includes(".")){let o=e.split("."),s=o[0],a=o[1],c=this.findPackageNameForAlias(r,s);if(c){for(let p of t.values())if(p.entityName===a&&p.uri.package_===c)return p.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new T(e,t,r,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===t||!o.alias&&o.packageName===t)return o.packageName;return null}};le();function Ar(i){if(!i||i.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=i.trim(),t=e.split("/");if(t.length===1){let r=t[0];if(!r)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(r.includes("@"))throw new Error(`Invalid Kanonak address: "${i}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:r}}if(t.length===2){let[r,n]=t;if(!r||!n)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let o=n.indexOf("@");if(o===-1)return{kind:"package",publisher:r,package_:n};let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let c=Fn(a);return{kind:"package",publisher:r,package_:s,version:c}}return{kind:"resource",uri:T.parse(e)}}function Dr(i){switch(i.kind){case"publisher":return i.publisher;case"package":return i.version?`${i.publisher}/${i.package_}@${i.version.major}.${i.version.minor}.${i.version.patch}`:`${i.publisher}/${i.package_}`;case"resource":return i.uri.toString()}}function Fn(i){let e=i.split(".").map(Number);return Bn(e[0]||0,e[1]||0,e[2]||0)}function Bn(i,e,t){return{major:i,minor:e,patch:t,toString:()=>`${i}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===i&&r.minor===e&&r.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:r=>i!==r.major?i-r.major:e!==r.minor?e-r.minor:t-r.patch}}async function Cr(i,e){let t=[],r=await i.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,c=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[p,l]of Object.entries(n.body)){if(!l||typeof l!="object")continue;let u=l.type;!u||typeof u!="string"||u!=="Package"&&Wn(u,e)&&t.push({entityName:p,entity:l,documentNamespace:`${s}/${a}@${c}`,publisher:s,package_:a,version:c})}}return t}function Wn(i,e){let t=Kr(i),r=Kr(e);return t===r}function Kr(i){let e=i.lastIndexOf(".");if(e!==-1)return i.substring(e+1);let t=i.lastIndexOf("/");return t!==-1?i.substring(t+1):i}var ue=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var It=class i{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new i;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var me=class i{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&i.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),c=e.split(".")[0],p=new k;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue=n,p.expectedValue=a,p.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(p)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var ye=class i{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){if(!r&&i.RESERVED_WORDS.has(n.toLowerCase())){let s=new k;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Entity name '${n}' is a reserved word and cannot be used.`,s.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(s);continue}if(!i.VALID_NAME_PATTERN.test(n)){let s;/^\d/.test(n)?s="Entity names must start with a letter, not a number.":n.includes(" ")?s="Entity names cannot contain spaces. Use camelCase or underscores instead.":s="Entity names must start with a letter and contain only letters, numbers, and underscores.";let a=new k;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Invalid entity name '${n}'. ${s}`,a.suggestion=s,t.push(a)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!i.VALID_PROPERTIES.has(n)&&!i.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var fe=class i{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let c=[];if(Array.isArray(a))for(let p of a){let l=p?.toString();l&&l==="Property"&&!r&&c.push(l)}else{let p=a?.toString();p&&p==="Property"&&!r&&c.push(p)}for(let p of c){let l=this.getPropertyValue(s,"range"),u=this.determinePropertyType(l),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=p,m.expectedValue=u,m.message=`Invalid property type '${p}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":i.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var de=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=r,c.propertyName="type",c.message=`Subject Kanonak '${r}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
3
+ `)||i.startsWith("http://")||i.startsWith("https://")||/^\d{4}-\d{2}/.test(i)||/^\d+(\.\d+)?$/.test(i))}function se(i,e,t,r){if(i.includes("@")&&i.includes("/"))return i;if(i.includes(".")){let n=i.indexOf("."),o=i.substring(0,n),s=i.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${i}@${t}`:i}function We(i){return`${i.publisher}/${i.package_}/${i.name}`}function C(i,e,t){return`${i}/${e}/${t}`}function et(i){return`${i.s}|${i.p}|${er(i.o)}`}function er(i){switch(i.kind){case"uri":return`u:${i.key}`;case"literal":return`l:${i.datatype}:${i.lexical}`;case"blank":return`b:${i.id}`}}function A(i,e,t){return{s:i,p:e,o:{kind:"uri",key:t}}}var He=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=et(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),tr(this.byPIdx,e.p,e),tr(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&tr(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(et(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)n.add(o.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)o.o.kind==="uri"&&n.add(o.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${er(r)}`)}};function tr(i,e,t){let r=i.get(e);r?r.push(t):i.set(e,[t])}var qe=class{type=C("kanonak.org","core-rdf","type");subClassOf=C("kanonak.org","core-rdf","subClassOf");subPropertyOf=C("kanonak.org","core-rdf","subPropertyOf");domain=C("kanonak.org","core-rdf","domain");range=C("kanonak.org","core-rdf","range");equivalentClass=C("kanonak.org","core-owl","equivalentClass");equivalentProperty=C("kanonak.org","core-owl","equivalentProperty");inverseOf=C("kanonak.org","core-owl","inverseOf");sameAs=C("kanonak.org","core-owl","sameAs");transitiveProperty=C("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=C("kanonak.org","core-owl","SymmetricProperty")};var Rn={name:"rdfs2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},vn={name:"rdfs3",apply(i,e){let t=!1;for(let r of i.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,e.type,o))&&(t=!0)}return t}},Pn={name:"rdfs5",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subPropertyOf))s.o.kind==="uri"&&i.add(A(n,e.subPropertyOf,s.o.key))&&(t=!0)}return t}},wn={name:"rdfs7",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n)){let a={s:s.s,p:o,o:s.o};i.add(a)&&(t=!0)}}return t}},In={name:"rdfs9",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},Sn={name:"rdfs11",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subClassOf))s.o.kind==="uri"&&i.add(A(n,e.subClassOf,s.o.key))&&(t=!0)}return t}},tt=[Rn,vn,Pn,wn,In,Sn];var An={name:"prp-trp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let o=i.byPredicate(n);for(let s of o){if(s.o.kind!=="uri")continue;let a=s.o.key;for(let c of i.bySubjectPredicate(a,n))c.o.kind==="uri"&&s.s!==c.o.key&&i.add(A(s.s,n,c.o.key))&&(t=!0)}}return t}},Dn={name:"prp-symp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let o of i.byPredicate(n))o.o.kind==="uri"&&i.add(A(o.o.key,n,o.s))&&(t=!0);return t}},Kn={name:"prp-inv1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,o,s.s))&&(t=!0)}return t}},Cn={name:"prp-inv2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(o))s.o.kind==="uri"&&i.add(A(s.o.key,n,s.s))&&(t=!0)}return t}},$n={name:"prp-eqp1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n))i.add({s:s.s,p:o,o:s.o})&&(t=!0)}return t}},jn={name:"prp-eqp2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(o))i.add({s:s.s,p:n,o:s.o})&&(t=!0)}return t}},xn={name:"cax-eqc1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},En={name:"cax-eqc2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,o))i.add(A(s.s,e.type,n))&&(t=!0)}return t}},On={name:"eq-rep-s",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o){for(let s of i.snapshot())s.s===n&&i.add({s:o,p:s.p,o:s.o})&&(t=!0);for(let s of i.snapshot())s.s===o&&i.add({s:n,p:s.p,o:s.o})&&(t=!0)}}return t}},Vn={name:"eq-rep-o",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.snapshot())s.o.kind==="uri"&&(s.o.key===n?i.add(A(s.s,s.p,o))&&(t=!0):s.o.key===o&&i.add(A(s.s,s.p,n))&&(t=!0))}return t}},rt=[An,Dn,Kn,Cn,$n,jn,xn,En,On,Vn];var ze=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=Ge(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(Ge(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(Ge(e),this.vocabulary.type,Ge(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function Ge(i){return typeof i=="string"?i:C(i.publisher,i.package_,i.name)}var kt=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new qe,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new He,n=await new oe().parseKanonaks(e),o=new rr;for(let c of n)if(c instanceof N){let p=Tn(c);if(!p)continue;for(let l of c.statement)this.emitStatement(p,l,t,o)}let s=[...tt];this.profile==="owl-rl-classification"&&s.push(...rt);let a=0;for(;a<this.maxIterations;){let c=!1;for(let p of s)p.apply(t,this.vocabulary)&&(c=!0);if(!c)break;a++}return new ze(t,this.vocabulary)}emitStatement(e,t,r,n){let o=Nn(t);if(o){if(t instanceof W){r.add({s:e,p:o,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof Q){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof ee){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof U){let s=We(t.object.subject);r.add(A(e,o,s));return}if(t instanceof H){let s=n.next();r.add({s:e,p:o,o:{kind:"blank",id:s}}),this.emitEmbedded(s,t.object,r,n);return}if(t instanceof L){for(let s of t.object??[])this.emitListItem(e,o,s,r,n);return}}}emitListItem(e,t,r,n,o){if(r instanceof w)n.add(A(e,t,We(r.subject)));else if(r instanceof _){let s=o.next();n.add({s:e,p:t,o:{kind:"blank",id:s}}),this.emitEmbedded(s,r,n,o)}else if(r instanceof Z){let s=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:s}})}}emitEmbedded(e,t,r,n){let o=`_:${e}`;for(let s of t.statement)this.emitStatement(o,s,r,n)}},rr=class{counter=0;next(){return`b${this.counter++}`}};function Tn(i){let e=i.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let o=r.substring(0,n),s=r.substring(n+1);return!o||!s||!i.name?null:C(o,s,i.name)}function Nn(i){let e=i.predicate;return e?.subject?We(e.subject):null}import _n from"ignore";import*as Rt from"fs";import*as Xe from"path";var bt=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=Xe.join(e,".gitignore");if(Rt.existsSync(t))try{let r=Rt.readFileSync(t,"utf8");this.ignoreInstance=_n(),this.ignoreInstance.add(r)}catch{this.ignoreInstance=null}else this.ignoreInstance=null}shouldIgnore(e){if(!this.ignoreInstance)return!1;let r=Xe.relative(this.basePath,e).split(Xe.sep).join("/");return this.ignoreInstance.ignores(r)}};var vt=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as Un,LineCounter as Ln,isMap as Ye,isPair as O,isScalar as M,isSeq as Pt}from"yaml";var Je=class i{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new i,r=new Ln,n=Un(e,{lineCounter:r});if(n.errors.length>0||!Ye(n.contents))return t;or(n.contents,[],r,t);for(let o of n.contents.items){if(!O(o)||!M(o.key))continue;let s=String(o.key.value),a=o.key.range;if(!a)continue;t.entities.set(s,G(a,r));let c=o.value,p=c&&typeof c=="object"&&"range"in c?c.range:void 0;if(p?t.entityBlocks.set(s,G([a[0],a[1],p[2]],r)):t.entityBlocks.set(s,G(a,r)),Ye(o.value)){let l=new Map,u=new Map,m=new Map;for(let f of o.value.items){if(!O(f)||!M(f.key))continue;let d=String(f.key.value),g=f.key.range;g&&l.set(d,G(g,r));let h=f.value;if(h&&typeof h=="object"&&"range"in h&&Array.isArray(h.range)){let b=h.range;u.set(d,G(b,r))}if(Pt(h)){let b=[];for(let R of h.items)R&&typeof R=="object"&&"range"in R&&Array.isArray(R.range)&&b.push(G(R.range,r));b.length>0&&m.set(d,b)}}l.size>0&&t.properties.set(s,l),u.size>0&&t.propertyValues.set(s,u),m.size>0&&t.valueListItems.set(s,m);let y=Mn(o.value,r);y.length>0&&t.importPackages.set(s,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(nr(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,a;if(o)for(let[c,p]of o)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);if(n)for(let[c,p]of n)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function Mn(i,e){let t=[];if(!Ye(i))return t;let r=i.items.find(n=>O(n)&&M(n.key)&&String(n.key.value)==="imports");if(!r||!O(r)||!Pt(r.value))return t;for(let n of r.value.items){if(!Ye(n))continue;let o=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="publisher");if(!o||!O(o)||!M(o.value))continue;let s=String(o.value.value),a=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="packages");if(!(!a||!O(a)||!Pt(a.value)))for(let c of a.value.items){if(!Ye(c))continue;let p=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="package");if(!p||!O(p)||!M(p.value)||!p.value.range)continue;let l=String(p.value.value),u=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="version"),m=u&&O(u)&&M(u.value)?String(u.value.value):"",y=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="alias"),f=y&&O(y)&&M(y.value)?String(y.value.value):void 0,d=f!==void 0?{publisher:s,package_:l,version:m,alias:f,position:G(p.value.range,e)}:{publisher:s,package_:l,version:m,position:G(p.value.range,e)};t.push(d)}}return t}function nr(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function wr(i,e){let t=i.endLine-i.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function or(i,e,t,r){if(Ye(i)){for(let n of i.items){if(!O(n)||!M(n.key))continue;let o=String(n.key.value),s=[...e,o],a=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(a,G(n.key.range,t));let c=n.value,p=Ir(c);p&&r.setNestedValuePosition(a,G(p,t)),or(c,s,t,r)}return}if(Pt(i)){for(let n=0;n<i.items.length;n++){let o=i.items[n],s=[...e,n],a=JSON.stringify(s),c=Ir(o);c&&r.setNestedValuePosition(a,G(c,t)),or(o,s,t,r)}return}}function Ir(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function G(i,e){let t=e.linePos(i[0]),r=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function Sr(i,e){let r=(e??new $).parse(i),n=Je.fromContent(i);return{document:r,positions:n}}le();le();var wt=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,r){if(e.includes(".")){let o=e.split("."),s=o[0],a=o[1],c=this.findPackageNameForAlias(r,s);if(c){for(let p of t.values())if(p.entityName===a&&p.uri.package_===c)return p.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new T(e,t,r,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===t||!o.alias&&o.packageName===t)return o.packageName;return null}};le();function Ar(i){if(!i||i.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=i.trim(),t=e.split("/");if(t.length===1){let r=t[0];if(!r)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(r.includes("@"))throw new Error(`Invalid Kanonak address: "${i}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:r}}if(t.length===2){let[r,n]=t;if(!r||!n)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let o=n.indexOf("@");if(o===-1)return{kind:"package",publisher:r,package_:n};let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let c=Fn(a);return{kind:"package",publisher:r,package_:s,version:c}}return{kind:"resource",uri:T.parse(e)}}function Dr(i){switch(i.kind){case"publisher":return i.publisher;case"package":return i.version?`${i.publisher}/${i.package_}@${i.version.major}.${i.version.minor}.${i.version.patch}`:`${i.publisher}/${i.package_}`;case"resource":return i.uri.toString()}}function Fn(i){let e=i.split(".").map(Number);return Bn(e[0]||0,e[1]||0,e[2]||0)}function Bn(i,e,t){return{major:i,minor:e,patch:t,toString:()=>`${i}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===i&&r.minor===e&&r.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:r=>i!==r.major?i-r.major:e!==r.minor?e-r.minor:t-r.patch}}async function Cr(i,e){let t=[],r=await i.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,c=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[p,l]of Object.entries(n.body)){if(!l||typeof l!="object")continue;let u=l.type;!u||typeof u!="string"||u!=="Package"&&Wn(u,e)&&t.push({entityName:p,entity:l,documentNamespace:`${s}/${a}@${c}`,publisher:s,package_:a,version:c})}}return t}function Wn(i,e){let t=Kr(i),r=Kr(e);return t===r}function Kr(i){let e=i.lastIndexOf(".");if(e!==-1)return i.substring(e+1);let t=i.lastIndexOf("/");return t!==-1?i.substring(t+1):i}var ue=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var It=class i{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new i;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var me=class i{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&i.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),c=e.split(".")[0],p=new k;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue=n,p.expectedValue=a,p.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(p)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var ye=class i{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){let s=i.VALID_AUGMENTATION_PATTERN.test(n);if(!s&&!r&&i.RESERVED_WORDS.has(n.toLowerCase())){let a=new k;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Entity name '${n}' is a reserved word and cannot be used.`,a.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(a);continue}if(!s&&!i.VALID_NAME_PATTERN.test(n)){let a;/^\d/.test(n)?a="Entity names must start with a letter, not a number.":n.includes(" ")?a="Entity names cannot contain spaces. Use camelCase or underscores instead.":a="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.message=`Invalid entity name '${n}'. ${a}`,c.suggestion=a,t.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!i.VALID_PROPERTIES.has(n)&&!i.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var fe=class i{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let c=[];if(Array.isArray(a))for(let p of a){let l=p?.toString();l&&l==="Property"&&!r&&c.push(l)}else{let p=a?.toString();p&&p==="Property"&&!r&&c.push(p)}for(let p of c){let l=this.getPropertyValue(s,"range"),u=this.determinePropertyType(l),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=p,m.expectedValue=u,m.message=`Invalid property type '${p}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":i.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var de=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||r.includes("."))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=r,c.propertyName="type",c.message=`Subject Kanonak '${r}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
4
4
  type: Scene
5
5
 
6
6
  Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,c.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(c)}}return t}};var ge=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,t){let r=[],n=new j(t),o=await this.buildPropertyRangeMap(e,n);for(let[s,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.checkEmbeddedTypes(s,a,void 0,o,n,e,r,0);return r}async checkEmbeddedTypes(e,t,r,n,o,s,a,c){if(c>0){let p=t.type;if(p!=null){let l=await this.validateEmbeddedType(e,String(p),r,o,s);l&&a.push(l)}}for(let[p,l]of Object.entries(t)){let u=this.localName(p),m=n.has(u)?n.get(u):r;if(typeof l=="object"&&l!==null)if(Array.isArray(l))for(let y=0;y<l.length;y++){let f=l[y];typeof f=="object"&&f!==null&&!Array.isArray(f)&&await this.checkEmbeddedTypes(`${e}.${p}[${y}]`,f,m,n,o,s,a,c+1)}else await this.checkEmbeddedTypes(`${e}.${p}`,l,m,n,o,s,a,c+1)}}async validateEmbeddedType(e,t,r,n,o){if(t.length===0||!r)return null;let s=this.localName(t),a=this.localName(r);if(a==="Resource"||a==="Class")return null;let c=e.split(".")[0];if(s===a){let l=new k;return l.ruleType=this.ruleName,l.severity="Warning",l.entityName=c,l.propertyName=e,l.actualValue=t,l.expectedValue=r,l.message=`Embedded object at '${e}' declares 'type: ${t}', which equals the parent property's range '${r}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,l.suggestion=`Remove the 'type: ${t}' line, or keep it if explicitness is preferred over concision.`,l}if(await n.isSubclassOfAsync(t,r,o)||(s!==t||a!==r)&&await n.isSubclassOfAsync(s,a,o))return null;let p=new k;return p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue=t,p.expectedValue=r,p.message=`Embedded object at '${e}' has 'type: ${t}', which is not a subclass of the parent property's range '${r}'.`,p.suggestion=`Either remove the 'type: ${t}' line (so the type is inferred from the property's range '${r}'), or add 'subClassOf: ${r}' to the '${t}' class definition so the relationship holds.`,p}localName(e){let t=e.lastIndexOf(".");return t<0||t===e.length-1?e:e.substring(t+1)}async buildPropertyRangeMap(e,t){let r=new Map,n=await t.buildEntityIndexAsync(e);for(let[o,s]of n){let a=s.entity.type;if(a==null)continue;let c=String(a),p=this.localName(c);if(!(p==="Property"||p==="DatatypeProperty"||p==="ObjectProperty"||p==="AnnotationProperty"))continue;let u=s.entity.range;if(u==null)continue;let m=String(u);m.length!==0&&r.set(this.localName(o),m)}return r}};var he=class{ruleName="ImportExistence";async validateAsync(e,t){let r=[];if(!e.metadata?.imports)return r;let n=await t.getAllDocumentsAsync();for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!await t.getHighestCompatibleVersionAsync(o,a)){let p=await this.determineImportErrorAsync(t,o,a,n),l=new k;l.ruleType=this.ruleName,l.severity="Error",l.message=p.message,l.suggestion=p.suggestion,l.entityName=`Import: ${o}/${a.packageName}`,l.actualValue=a.toString(),l.expectedValue=p.expectedValue,r.push(l)}return r}async determineImportErrorAsync(e,t,r,n){let o=await e.getDocumentsByNamespaceAsync(t,r.packageName);if(o.length===0){let p=n.filter(y=>y.metadata.namespace_?.publisher===t).map(y=>y.metadata.namespace_.package_).filter((y,f,d)=>d.indexOf(y)===f),l=this.findSimilarPackages(r.packageName,p),u=`Import '${t}/${r.package_}' not found - package does not exist`,m=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:p.length>0?`Available packages in ${t}: ${p.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:u,suggestion:m,expectedValue:"Existing package"}}let a=o.filter(p=>p.metadata.namespace_?.version).map(p=>p.metadata.namespace_.version.toString()).sort().join(", "),c=this.getAcceptableVersionRange(r);return{message:`Import '${t}/${r.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${c}`,expectedValue:c}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let r=t.filter(s=>s.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(s.toLowerCase()));if(r.length>0)return r.sort((s,a)=>s.length-a.length);let n=t.map(s=>({package:s,distance:this.levenshteinDistance(e.toLowerCase(),s.toLowerCase())})).sort((s,a)=>s.distance-a.distance),o=Math.max(3,Math.floor(e.length*.4));return n.filter(s=>s.distance<=o).map(s=>s.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let r=e.length,n=t.length,o=Array(r+1).fill(null).map(()=>Array(n+1).fill(0));for(let s=0;s<=r;s++)o[s][0]=s;for(let s=0;s<=n;s++)o[0][s]=s;for(let s=1;s<=r;s++)for(let a=1;a<=n;a++){let c=e[s-1]===t[a-1]?0:1;o[s][a]=Math.min(Math.min(o[s-1][a]+1,o[s][a-1]+1),o[s-1][a-1]+c)}return o[r][n]}};var ke=class{ruleName="UnresolvedReference";async validateAsync(e,t){let r=[],n=new j(t),o=await n.buildEntityIndexAsync(e),s=new Set;for(let[a,c]of o.entries()){let p=c.entity.type;if(p){let l=p.toString();(l==="ObjectProperty"||l.endsWith(".ObjectProperty"))&&s.add(a)}}for(let[a,c]of Object.entries(e.body)){if(!c||typeof c!="object"||Array.isArray(c))continue;let p=c,l=this.getPropertyValue(p,"type");if(!(!l||l==="Class"||l.endsWith("Property")||l==="AnnotationProperty"))for(let[u,m]of Object.entries(p))u==="type"||u==="label"||u==="comment"||!(s.has(u)||Array.from(s).some(f=>f.endsWith(`.${u}`)))||await this.validateReferenceValue(a,u,m,e,n,r)}return r}async validateReferenceValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string")await o.resolveEntityAsync(r,n)||s.push(this.createUnresolvedReferenceError(e,t,r));else if(Array.isArray(r))for(let a=0;a<r.length;a++){let c=r[a];typeof c=="string"&&(await o.resolveEntityAsync(c,n)||s.push(this.createUnresolvedReferenceError(e,`${t}[${a}]`,c)))}}}createUnresolvedReferenceError(e,t,r){let n=`The entity '${r}' cannot be found in the current document or any imported namespaces.
@@ -1,42 +1,42 @@
1
- var P=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(o=>(o.Warning="Warning",o.Error="Error",o))(b||{});var h=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var ee=class d{resolvedDocuments=[];currentEntityPath;withPath(e){let o=new d;return o.resolvedDocuments=this.resolvedDocuments,o.currentEntityPath=e,o}};import*as Z from"js-yaml";var G=class{parse(e){let o=this.parseWithErrors(e);if(!o.isValid){let t=o.errors[0];throw new Error(`YAML parse error at line ${t.line}, column ${t.column}: ${t.message}`)}return o.document}parseWithErrors(e){let o=[],t;try{e=e.replace(/^\uFEFF/,"");let i=Z.load(e);if(!i||typeof i!="object")return t={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:t,errors:o,isValid:!0};let r=this.extractMetadata(i),n=this.extractBody(i,r);return t={metadata:r,body:n,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:t,errors:o,isValid:!0}}catch(i){let r=i,n={message:r.message||"Unknown parse error",line:r.mark?.line??0,column:r.mark?.column??0,errorType:r.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${r.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${r.mark?.line??0}: ${r.message||"Unknown parse error"}`};return o.push(n),{document:void 0,errors:o,isValid:!1}}}save(e){let o={};if(e.metadata.namespace_){let t=e.metadata.namespace_,i={type:"Package",publisher:t.publisher};t.version&&(i.version=`${t.version.major}.${t.version.minor}.${t.version.patch}`),e.metadata.imports&&(i.imports=this.serializeImports(e.metadata.imports)),o[t.package_]=i}return Object.assign(o,e.body),Z.dump(o,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let o=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!o)return[];let t=[];for(let i of Object.values(o))t.push(...i);return t},enumerable:!0,configurable:!0}),e}createVersion(e,o,t){return{major:e,minor:o,patch:t,toString:()=>`${e}.${o}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===o&&r.patch===t,getHashCode:()=>e<<20|o<<10|t,compareTo:r=>e!==r.major?e-r.major:o!==r.minor?o-r.minor:t-r.patch}}extractMetadata(e){let o=this.createEmptyMetadata();for(let[t,i]of Object.entries(e))if(i&&typeof i=="object"&&i.type==="Package"){o.type_="Package";let r=t,n=i.publisher,a=i.version?this.parseVersion(i.version):void 0;return n&&r&&(o.namespace_={publisher:n,package_:r,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:p=>!p||typeof p!="object"?!1:p.publisher===n&&p.package_===r&&(!a||!p.version||a.equals(p.version)),getHashCode:()=>{let p=0;for(let s=0;s<n.length;s++)p=(p<<5)-p+n.charCodeAt(s);for(let s=0;s<r.length;s++)p=(p<<5)-p+r.charCodeAt(s);return p|0}}),i.imports&&Array.isArray(i.imports)&&(o.imports=this.parseImportsV3(i.imports)),this.addAllImportsGetter(o)}if(e.kanonak&&typeof e.kanonak=="object"){let t=e.kanonak;return(t.publisher||t.package||t.version)&&(o.namespace_=this.parseNamespace(t)),t.imports&&typeof t.imports=="object"&&(o.imports=this.parseImportsLegacy(t.imports)),this.addAllImportsGetter(o)}return o}extractBody(e,o){let t={},i;for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){i=r;break}for(let[r,n]of Object.entries(e))r!==i&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(t[r]=n);return t}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let n=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:n,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===r[1]&&a.package_===r[2]&&(!n||!a.version||n.equals(a.version)),getHashCode:()=>{let a=0;for(let p=0;p<r[1].length;p++)a=(a<<5)-a+r[1].charCodeAt(p);for(let p=0;p<r[2].length;p++)a=(a<<5)-a+r[2].charCodeAt(p);return a|0}}}}let o=e.publisher||"",t=e.package||"",i=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:o,package_:t,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:r=>!r||typeof r!="object"?!1:r.publisher===o&&r.package_===t&&(!i||!r.version||i.equals(r.version)),getHashCode:()=>{let r=0;for(let n=0;n<o.length;n++)r=(r<<5)-r+o.charCodeAt(n);for(let n=0;n<t.length;n++)r=(r<<5)-r+t.charCodeAt(n);return r|0}}}parseVersion(e){if(typeof e=="string"){let o=e.split(".").map(Number);return this.createVersion(o[0]||0,o[1]||0,o[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let o={};for(let t of e)if(!(!t||typeof t!="object"))if(t.packages&&Array.isArray(t.packages)){let i=t.publisher;if(!i)throw new Error("PublisherImport requires 'publisher' property");o[i]||(o[i]=[]);for(let r of t.packages){if(!r||typeof r!="object")continue;let n=this.parseImportFromEmbeddedObject(r,i);o[i].push(n)}}else{let i=this.parseImportFromEmbeddedObject(t,t.publisher),r=i.publisher||"";o[r]||(o[r]=[]),o[r].push(i)}return o}parseImportsLegacy(e){let o={};for(let[t,i]of Object.entries(e))Array.isArray(i)&&(o[t]=i.map(r=>this.parseImport(r,t)));return o}parseImportFromEmbeddedObject(e,o){let t=e.package;if(!t)throw new Error("Import requires 'package' property");let i=e.match;if(!i)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let n=this.parseVersion(r),a=this.parseVersionOperator(i),p=this.calculateMaxVersion(i,n),s=e.alias;return{package_:`${t} ${i} ${n.toString()}`,publisher:o,packageName:t,versionOperator:a,version:n,alias:s,minVersion:n,maxVersion:p,toEmbeddedObject:()=>{let c={package:t,match:i,version:n.toString()};return s&&(c.alias=s),c},toString:()=>s?`${t} ${i} ${n.toString()} as ${s}`:`${t} ${i} ${n.toString()}`}}parseImport(e,o){if(typeof e=="string"){let p=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(p){let c=p[1].trim(),l=p[2],y=this.parseVersion(p[3].trim()),u=p[4].trim(),m=this.parseVersionOperator(l),f=this.calculateMaxVersion(l,y);return{package_:e,publisher:o,packageName:c,versionOperator:m,version:y,alias:u,minVersion:y,maxVersion:f,toEmbeddedObject:()=>{let g={package:c,match:l,version:y.toString()};return u&&(g.alias=u),g},toString:()=>`${c} ${l} ${y.toString()} as ${u}`}}let s=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(s){let c=s[1].trim(),l=s[2],y=this.parseVersion(s[3].trim()),u=this.parseVersionOperator(l),m=this.calculateMaxVersion(l,y);return{package_:e,publisher:o,packageName:c,versionOperator:u,version:y,alias:void 0,minVersion:y,maxVersion:m,toEmbeddedObject:()=>({package:c,match:l,version:y.toString()}),toString:()=>`${c} ${l} ${y.toString()}`}}}let t=this.parseVersionOperator(e.operator||"~"),i=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",n=["=","~","^","*"][t],a=this.calculateMaxVersion(e.operator||"~",i);return{package_:e.package||"",publisher:o,packageName:r,versionOperator:t,version:i,alias:e.alias,minVersion:i,maxVersion:a,toEmbeddedObject:()=>{let p={package:r,match:n,version:i.toString()};return e.alias&&(p.alias=e.alias),p},toString:()=>`${r} ${n} ${i.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,o){switch(e){case"~":return this.createVersion(o.major,o.minor+1,0);case"^":return o.major===0?this.createVersion(0,o.minor+1,0):this.createVersion(o.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let o=[];for(let[t,i]of Object.entries(e)){let r={publisher:t,packages:i.map(n=>{let a=["=","~","^","*"][n.versionOperator],p={package:n.packageName,match:a,version:`${n.version.major}.${n.version.minor}.${n.version.patch}`};return n.alias&&(p.alias=n.alias),p})};o.push(r)}return o}};var I=class d{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let o=[];for(let[t,i]of Object.entries(e.body))i&&typeof i=="object"&&!Array.isArray(i)&&this.validateEntity(t,i,o);return o}validateEntity(e,o,t){for(let[i,r]of Object.entries(o)){let n=r?.toString()??"";if(n&&d.NAMESPACE_PREFIX_PATTERN.test(n)){let a=this.getSuggestionForPrefixedValue(n),p=e.split(".")[0],s=new h;s.ruleType=this.ruleName,s.severity="Error",s.entityName=p,s.propertyName=e,s.actualValue=i,s.expectedValue=a,s.message=`Invalid namespace prefix '${n}'. Use '${a}' without prefix.`,s.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${i}`,r,t)}}getSuggestionForPrefixedValue(e){let o=e.toLowerCase();if(o==="rdfs:class"||o==="owl:class")return"Class";if(o==="rdfs:property"||o==="rdf:property")return"DatatypeProperty or ObjectProperty";if(o.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var D=class d{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let o=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[i,r]of Object.entries(e.body)){if(!t&&d.RESERVED_WORDS.has(i.toLowerCase())){let n=new h;n.ruleType=this.ruleName,n.severity="Error",n.entityName=i,n.message=`Entity name '${i}' is a reserved word and cannot be used.`,n.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",o.push(n);continue}if(!d.VALID_NAME_PATTERN.test(i)){let n;/^\d/.test(i)?n="Entity names must start with a letter, not a number.":i.includes(" ")?n="Entity names cannot contain spaces. Use camelCase or underscores instead.":n="Entity names must start with a letter and contain only letters, numbers, and underscores.";let a=new h;a.ruleType=this.ruleName,a.severity="Error",a.entityName=i,a.message=`Invalid entity name '${i}'. ${n}`,a.suggestion=n,o.push(a)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(i,r,o)}return o}validatePropertyNames(e,o,t){for(let i of Object.keys(o))if(!d.VALID_PROPERTIES.has(i)&&!d.VALID_PROPERTY_NAME_PATTERN.test(i)){let r=new h;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=i,r.message=`Property name '${i}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(r)}}};var O=class d{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let o=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return o;let t=this.isPropertyDefinedAsClass(e);for(let[i,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let n=r,a=n.type;if(a){let p=[];if(Array.isArray(a))for(let s of a){let c=s?.toString();c&&c==="Property"&&!t&&p.push(c)}else{let s=a?.toString();s&&s==="Property"&&!t&&p.push(s)}for(let s of p){let c=this.getPropertyValue(n,"range"),l=this.determinePropertyType(c),y=new h;y.ruleType=this.ruleName,y.severity="Error",y.entityName=i,y.propertyName="type",y.actualValue=s,y.expectedValue=l,y.message=`Invalid property type '${s}'. Use '${l}' instead.`,y.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",o.push(y)}}}return o}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":d.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,o){let t=e[o];return t?t.toString():null}isPropertyDefinedAsClass(e){let o=e.body.Property;if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o.type;if(i){let r=i.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var $=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let o=[];for(let[t,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i,n="type"in r,a=r.type?.toString().trim();if(!n||!a){let p=new h;p.ruleType=this.ruleName,p.severity="Error",p.entityName=t,p.propertyName="type",p.message=`Subject Kanonak '${t}' must have a 'type' property.`,p.suggestion=`Add a type statement like:
1
+ var P=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(o=>(o.Warning="Warning",o.Error="Error",o))(b||{});var h=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var ee=class d{resolvedDocuments=[];currentEntityPath;withPath(e){let o=new d;return o.resolvedDocuments=this.resolvedDocuments,o.currentEntityPath=e,o}};import*as G from"js-yaml";var Z=class{parse(e){let o=this.parseWithErrors(e);if(!o.isValid){let t=o.errors[0];throw new Error(`YAML parse error at line ${t.line}, column ${t.column}: ${t.message}`)}return o.document}parseWithErrors(e){let o=[],t;try{e=e.replace(/^\uFEFF/,"");let n=G.load(e);if(!n||typeof n!="object")return t={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:t,errors:o,isValid:!0};let r=this.extractMetadata(n),i=this.extractBody(n,r);return t={metadata:r,body:i,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:t,errors:o,isValid:!0}}catch(n){let r=n,i={message:r.message||"Unknown parse error",line:r.mark?.line??0,column:r.mark?.column??0,errorType:r.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${r.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${r.mark?.line??0}: ${r.message||"Unknown parse error"}`};return o.push(i),{document:void 0,errors:o,isValid:!1}}}save(e){let o={};if(e.metadata.namespace_){let t=e.metadata.namespace_,n={type:"Package",publisher:t.publisher};t.version&&(n.version=`${t.version.major}.${t.version.minor}.${t.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),o[t.package_]=n}return Object.assign(o,e.body),G.dump(o,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let o=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!o)return[];let t=[];for(let n of Object.values(o))t.push(...n);return t},enumerable:!0,configurable:!0}),e}createVersion(e,o,t){return{major:e,minor:o,patch:t,toString:()=>`${e}.${o}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===o&&r.patch===t,getHashCode:()=>e<<20|o<<10|t,compareTo:r=>e!==r.major?e-r.major:o!==r.minor?o-r.minor:t-r.patch}}extractMetadata(e){let o=this.createEmptyMetadata();for(let[t,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){o.type_="Package";let r=t,i=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return i&&r&&(o.namespace_={publisher:i,package_:r,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:p=>!p||typeof p!="object"?!1:p.publisher===i&&p.package_===r&&(!a||!p.version||a.equals(p.version)),getHashCode:()=>{let p=0;for(let s=0;s<i.length;s++)p=(p<<5)-p+i.charCodeAt(s);for(let s=0;s<r.length;s++)p=(p<<5)-p+r.charCodeAt(s);return p|0}}),n.imports&&Array.isArray(n.imports)&&(o.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(o)}if(e.kanonak&&typeof e.kanonak=="object"){let t=e.kanonak;return(t.publisher||t.package||t.version)&&(o.namespace_=this.parseNamespace(t)),t.imports&&typeof t.imports=="object"&&(o.imports=this.parseImportsLegacy(t.imports)),this.addAllImportsGetter(o)}return o}extractBody(e,o){let t={},n;for(let[r,i]of Object.entries(e))if(i&&typeof i=="object"&&i.type==="Package"){n=r;break}for(let[r,i]of Object.entries(e))r!==n&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(t[r]=i);return t}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let i=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:i,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===r[1]&&a.package_===r[2]&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let p=0;p<r[1].length;p++)a=(a<<5)-a+r[1].charCodeAt(p);for(let p=0;p<r[2].length;p++)a=(a<<5)-a+r[2].charCodeAt(p);return a|0}}}}let o=e.publisher||"",t=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:o,package_:t,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:r=>!r||typeof r!="object"?!1:r.publisher===o&&r.package_===t&&(!n||!r.version||n.equals(r.version)),getHashCode:()=>{let r=0;for(let i=0;i<o.length;i++)r=(r<<5)-r+o.charCodeAt(i);for(let i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i);return r|0}}}parseVersion(e){if(typeof e=="string"){let o=e.split(".").map(Number);return this.createVersion(o[0]||0,o[1]||0,o[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let o={};for(let t of e)if(!(!t||typeof t!="object"))if(t.packages&&Array.isArray(t.packages)){let n=t.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");o[n]||(o[n]=[]);for(let r of t.packages){if(!r||typeof r!="object")continue;let i=this.parseImportFromEmbeddedObject(r,n);o[n].push(i)}}else{let n=this.parseImportFromEmbeddedObject(t,t.publisher),r=n.publisher||"";o[r]||(o[r]=[]),o[r].push(n)}return o}parseImportsLegacy(e){let o={};for(let[t,n]of Object.entries(e))Array.isArray(n)&&(o[t]=n.map(r=>this.parseImport(r,t)));return o}parseImportFromEmbeddedObject(e,o){let t=e.package;if(!t)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let i=this.parseVersion(r),a=this.parseVersionOperator(n),p=this.calculateMaxVersion(n,i),s=e.alias;return{package_:`${t} ${n} ${i.toString()}`,publisher:o,packageName:t,versionOperator:a,version:i,alias:s,minVersion:i,maxVersion:p,toEmbeddedObject:()=>{let c={package:t,match:n,version:i.toString()};return s&&(c.alias=s),c},toString:()=>s?`${t} ${n} ${i.toString()} as ${s}`:`${t} ${n} ${i.toString()}`}}parseImport(e,o){if(typeof e=="string"){let p=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(p){let c=p[1].trim(),l=p[2],y=this.parseVersion(p[3].trim()),u=p[4].trim(),m=this.parseVersionOperator(l),f=this.calculateMaxVersion(l,y);return{package_:e,publisher:o,packageName:c,versionOperator:m,version:y,alias:u,minVersion:y,maxVersion:f,toEmbeddedObject:()=>{let g={package:c,match:l,version:y.toString()};return u&&(g.alias=u),g},toString:()=>`${c} ${l} ${y.toString()} as ${u}`}}let s=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(s){let c=s[1].trim(),l=s[2],y=this.parseVersion(s[3].trim()),u=this.parseVersionOperator(l),m=this.calculateMaxVersion(l,y);return{package_:e,publisher:o,packageName:c,versionOperator:u,version:y,alias:void 0,minVersion:y,maxVersion:m,toEmbeddedObject:()=>({package:c,match:l,version:y.toString()}),toString:()=>`${c} ${l} ${y.toString()}`}}}let t=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",i=["=","~","^","*"][t],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:o,packageName:r,versionOperator:t,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let p={package:r,match:i,version:n.toString()};return e.alias&&(p.alias=e.alias),p},toString:()=>`${r} ${i} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,o){switch(e){case"~":return this.createVersion(o.major,o.minor+1,0);case"^":return o.major===0?this.createVersion(0,o.minor+1,0):this.createVersion(o.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let o=[];for(let[t,n]of Object.entries(e)){let r={publisher:t,packages:n.map(i=>{let a=["=","~","^","*"][i.versionOperator],p={package:i.packageName,match:a,version:`${i.version.major}.${i.version.minor}.${i.version.patch}`};return i.alias&&(p.alias=i.alias),p})};o.push(r)}return o}};var I=class d{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let o=[];for(let[t,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(t,n,o);return o}validateEntity(e,o,t){for(let[n,r]of Object.entries(o)){let i=r?.toString()??"";if(i&&d.NAMESPACE_PREFIX_PATTERN.test(i)){let a=this.getSuggestionForPrefixedValue(i),p=e.split(".")[0],s=new h;s.ruleType=this.ruleName,s.severity="Error",s.entityName=p,s.propertyName=e,s.actualValue=n,s.expectedValue=a,s.message=`Invalid namespace prefix '${i}'. Use '${a}' without prefix.`,s.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,t)}}getSuggestionForPrefixedValue(e){let o=e.toLowerCase();if(o==="rdfs:class"||o==="owl:class")return"Class";if(o==="rdfs:property"||o==="rdf:property")return"DatatypeProperty or ObjectProperty";if(o.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var D=class d{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let o=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let i=d.VALID_AUGMENTATION_PATTERN.test(n);if(!i&&!t&&d.RESERVED_WORDS.has(n.toLowerCase())){let a=new h;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Entity name '${n}' is a reserved word and cannot be used.`,a.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",o.push(a);continue}if(!i&&!d.VALID_NAME_PATTERN.test(n)){let a;/^\d/.test(n)?a="Entity names must start with a letter, not a number.":n.includes(" ")?a="Entity names cannot contain spaces. Use camelCase or underscores instead.":a="Entity names must start with a letter and contain only letters, numbers, and underscores.";let p=new h;p.ruleType=this.ruleName,p.severity="Error",p.entityName=n,p.message=`Invalid entity name '${n}'. ${a}`,p.suggestion=a,o.push(p)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,o)}return o}validatePropertyNames(e,o,t){for(let n of Object.keys(o))if(!d.VALID_PROPERTIES.has(n)&&!d.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new h;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(r)}}};var O=class d{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let o=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return o;let t=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r,a=i.type;if(a){let p=[];if(Array.isArray(a))for(let s of a){let c=s?.toString();c&&c==="Property"&&!t&&p.push(c)}else{let s=a?.toString();s&&s==="Property"&&!t&&p.push(s)}for(let s of p){let c=this.getPropertyValue(i,"range"),l=this.determinePropertyType(c),y=new h;y.ruleType=this.ruleName,y.severity="Error",y.entityName=n,y.propertyName="type",y.actualValue=s,y.expectedValue=l,y.message=`Invalid property type '${s}'. Use '${l}' instead.`,y.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",o.push(y)}}}return o}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":d.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,o){let t=e[o];return t?t.toString():null}isPropertyDefinedAsClass(e){let o=e.body.Property;if(o&&typeof o=="object"&&!Array.isArray(o)){let n=o.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var $=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let o=[];for(let[t,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||t.includes("."))continue;let r=n,i="type"in r,a=r.type?.toString().trim();if(!i||!a){let p=new h;p.ruleType=this.ruleName,p.severity="Error",p.entityName=t,p.propertyName="type",p.message=`Subject Kanonak '${t}' must have a 'type' property.`,p.suggestion=`Add a type statement like:
2
2
  type: Scene
3
3
 
4
- Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,p.expectedValue="A valid class name (Scene, Character, Story, etc.)",o.push(p)}}return o}};var Y=class d{constructor(e,o,t,i){this.publisher=e;this.package_=o;this.name=t;this.version=i}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let o=e.split("/");if(o.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[t,i,r]=o;if(!t||!i||!r)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let n=i.indexOf("@");if(n===-1)return new d(t,i,r,void 0);let a=i.substring(0,n),p=i.substring(n+1);if(!a||!p)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=p.split(".").map(Number),c=oe(s[0]||0,s[1]||0,s[2]||0);return new d(t,a,r,c)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}};function oe(d,e,o){return{major:d,minor:e,patch:o,toString:()=>`${d}.${e}.${o}`,equals:t=>!t||typeof t!="object"?!1:t.major===d&&t.minor===e&&t.patch===o,getHashCode:()=>d<<20|e<<10|o,compareTo:t=>d!==t.major?d-t.major:e!==t.minor?e-t.minor:o-t.patch}}function k(d){if(Array.isArray(d))return d.map(o=>o?.toString()??"").filter(o=>o.length>0);let e=d?.toString();return e?[e]:[]}var V=class{cache=new Map;repository;logger;constructor(e,o){this.repository=e,this.logger=o}async resolveEntityAsync(e,o){let t=o.metadata?.namespace_?.toString()??"unknown",i=this.cache.get(t);if(i){let n=i.get(e);if(n)return n}let r=await this.buildEntityIndexAsyncInternal(o,new Set,"");return this.cache.set(t,r),r.get(e)??null}async resolveAllEntitiesAsync(e,o){let t=await this.buildAllEntitiesIndexAsync(o,new Set,"");if(e.includes(".")){let i=e.split("."),r=i[0],n=i[1],a=await this.findDocumentForAlias(o,r);return a?await this.resolveAllEntitiesAsync(n,a):[]}return t.filter(i=>i.entityName===e)}async buildAllEntitiesIndexAsync(e,o,t){let i=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),o.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),i;o.add(r);let n=t.length===0?r:`${t} \u2192 ${r}`;for(let[a,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let s=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};i.push({entityName:a,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,s),entity:p,definedInNamespace:r,isImported:t.length>0,importPath:n})}if(this.logger?.debug?.(`Collected ${i.length} entities from ${r}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((p,s)=>p+s.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${r}`);for(let[p,s]of Object.entries(e.metadata.imports))for(let c of s)try{this.logger?.debug?.(`Resolving import: ${p}/${c.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(p,c);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let y=await this.buildAllEntitiesIndexAsync(l,o,n);i.push(...y),this.logger?.debug?.(`Added ${y.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${c.packageName}`)}catch(l){let y=l;throw this.logger?.error?.(`Failed to process import ${p}/${c.packageName} for namespace ${r}. Error: ${y.message}`,y),new Error(`Failed to process import ${p}/${c.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return i}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,o,t){let i=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),o.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),i;o.add(r);let n=t.length===0?r:`${t} \u2192 ${r}`,a=0;for(let[p,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)&&!i.has(p)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};i.set(p,{entityName:p,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,p,c),entity:s,definedInNamespace:r,isImported:t.length>0,importPath:n}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${r}`),e.metadata?.imports){let p=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${p} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let l of c)try{this.logger?.debug?.(`Resolving import: ${s}/${l.packageName}`);let y=await this.repository.getHighestCompatibleVersionAsync(s,l);if(y){this.logger?.debug?.(`Successfully loaded import: ${y.metadata?.namespace_?.toString()}`);let u=await this.buildEntityIndexAsyncInternal(y,o,n),m=0;for(let[f,g]of u.entries())if(i.has(f)||(i.set(f,g),m++),l.alias&&!f.includes(".")){let R=`${l.alias}.${f}`;i.has(R)||(i.set(R,g),m++)}this.logger?.debug?.(`Merged ${m} entities from import ${y.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${l.packageName}`)}catch(y){let u=y;throw this.logger?.error?.(`Failed to process import ${s}/${l.packageName} for namespace ${r}. Error: ${u.message}`,u),new Error(`Failed to process import ${s}/${l.packageName} for namespace ${r}. See inner exception for details.`,{cause:y})}}return i}async findDocumentForAlias(e,o){if(!e.metadata?.imports)return null;for(let[t,i]of Object.entries(e.metadata.imports))for(let r of i){if(r.alias===o)return await this.repository.getHighestCompatibleVersionAsync(t,r);if(!r.alias&&r.packageName===o)return await this.repository.getHighestCompatibleVersionAsync(t,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,o,t){if(e===o)return!0;let i=new Set;return await this.isSubclassOfRecursiveAsync(e,o,t,i)}async isSubclassOfRecursiveAsync(e,o,t,i){if(i.has(e))return!1;i.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let n=r.entity.subClassOf;if(n){let a=k(n);for(let p of a)if(p===o||await this.isSubclassOfRecursiveAsync(p,o,t,i))return!0}return!1}async isSubpropertyOfAsync(e,o,t){if(e===o)return!0;let i=new Set;return await this.isSubpropertyOfRecursiveAsync(e,o,t,i)}async isSubpropertyOfRecursiveAsync(e,o,t,i){if(i.has(e))return!1;i.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let n=r.entity.subPropertyOf;if(n){let a=k(n);for(let p of a)if(p===o||await this.isSubpropertyOfRecursiveAsync(p,o,t,i))return!0}return!1}};var w=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,o){let t=[],i=new V(o),r=await this.buildPropertyRangeMap(e,i);for(let[n,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.checkEmbeddedTypes(n,a,void 0,r,i,e,t,0);return t}async checkEmbeddedTypes(e,o,t,i,r,n,a,p){if(p>0){let s=o.type;if(s!=null){let c=await this.validateEmbeddedType(e,String(s),t,r,n);c&&a.push(c)}}for(let[s,c]of Object.entries(o)){let l=this.localName(s),y=i.has(l)?i.get(l):t;if(typeof c=="object"&&c!==null)if(Array.isArray(c))for(let u=0;u<c.length;u++){let m=c[u];typeof m=="object"&&m!==null&&!Array.isArray(m)&&await this.checkEmbeddedTypes(`${e}.${s}[${u}]`,m,y,i,r,n,a,p+1)}else await this.checkEmbeddedTypes(`${e}.${s}`,c,y,i,r,n,a,p+1)}}async validateEmbeddedType(e,o,t,i,r){if(o.length===0||!t)return null;let n=this.localName(o),a=this.localName(t);if(a==="Resource"||a==="Class")return null;let p=e.split(".")[0];if(n===a){let c=new h;return c.ruleType=this.ruleName,c.severity="Warning",c.entityName=p,c.propertyName=e,c.actualValue=o,c.expectedValue=t,c.message=`Embedded object at '${e}' declares 'type: ${o}', which equals the parent property's range '${t}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,c.suggestion=`Remove the 'type: ${o}' line, or keep it if explicitness is preferred over concision.`,c}if(await i.isSubclassOfAsync(o,t,r)||(n!==o||a!==t)&&await i.isSubclassOfAsync(n,a,r))return null;let s=new h;return s.ruleType=this.ruleName,s.severity="Error",s.entityName=p,s.propertyName=e,s.actualValue=o,s.expectedValue=t,s.message=`Embedded object at '${e}' has 'type: ${o}', which is not a subclass of the parent property's range '${t}'.`,s.suggestion=`Either remove the 'type: ${o}' line (so the type is inferred from the property's range '${t}'), or add 'subClassOf: ${t}' to the '${o}' class definition so the relationship holds.`,s}localName(e){let o=e.lastIndexOf(".");return o<0||o===e.length-1?e:e.substring(o+1)}async buildPropertyRangeMap(e,o){let t=new Map,i=await o.buildEntityIndexAsync(e);for(let[r,n]of i){let a=n.entity.type;if(a==null)continue;let p=String(a),s=this.localName(p);if(!(s==="Property"||s==="DatatypeProperty"||s==="ObjectProperty"||s==="AnnotationProperty"))continue;let l=n.entity.range;if(l==null)continue;let y=String(l);y.length!==0&&t.set(this.localName(r),y)}return t}};var E=class{ruleName="ImportExistence";async validateAsync(e,o){let t=[];if(!e.metadata?.imports)return t;let i=await o.getAllDocumentsAsync();for(let[r,n]of Object.entries(e.metadata.imports))for(let a of n)if(!await o.getHighestCompatibleVersionAsync(r,a)){let s=await this.determineImportErrorAsync(o,r,a,i),c=new h;c.ruleType=this.ruleName,c.severity="Error",c.message=s.message,c.suggestion=s.suggestion,c.entityName=`Import: ${r}/${a.packageName}`,c.actualValue=a.toString(),c.expectedValue=s.expectedValue,t.push(c)}return t}async determineImportErrorAsync(e,o,t,i){let r=await e.getDocumentsByNamespaceAsync(o,t.packageName);if(r.length===0){let s=i.filter(u=>u.metadata.namespace_?.publisher===o).map(u=>u.metadata.namespace_.package_).filter((u,m,f)=>f.indexOf(u)===m),c=this.findSimilarPackages(t.packageName,s),l=`Import '${o}/${t.package_}' not found - package does not exist`,y=c.length>0?`Did you mean: ${c.slice(0,3).join(", ")}?`:s.length>0?`Available packages in ${o}: ${s.slice(0,5).join(", ")}`:`No packages found for publisher '${o}'. Verify the publisher name is correct.`;return{message:l,suggestion:y,expectedValue:"Existing package"}}let a=r.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),p=this.getAcceptableVersionRange(t);return{message:`Import '${o}/${t.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${p}`,expectedValue:p}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,o){if(o.length===0)return[];let t=o.filter(n=>n.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(n.toLowerCase()));if(t.length>0)return t.sort((n,a)=>n.length-a.length);let i=o.map(n=>({package:n,distance:this.levenshteinDistance(e.toLowerCase(),n.toLowerCase())})).sort((n,a)=>n.distance-a.distance),r=Math.max(3,Math.floor(e.length*.4));return i.filter(n=>n.distance<=r).map(n=>n.package)}levenshteinDistance(e,o){if(!e||e.length===0)return o?.length??0;if(!o||o.length===0)return e.length;let t=e.length,i=o.length,r=Array(t+1).fill(null).map(()=>Array(i+1).fill(0));for(let n=0;n<=t;n++)r[n][0]=n;for(let n=0;n<=i;n++)r[0][n]=n;for(let n=1;n<=t;n++)for(let a=1;a<=i;a++){let p=e[n-1]===o[a-1]?0:1;r[n][a]=Math.min(Math.min(r[n-1][a]+1,r[n][a-1]+1),r[n-1][a-1]+p)}return r[t][i]}};var S=class{ruleName="UnresolvedReference";async validateAsync(e,o){let t=[],i=new V(o),r=await i.buildEntityIndexAsync(e),n=new Set;for(let[a,p]of r.entries()){let s=p.entity.type;if(s){let c=s.toString();(c==="ObjectProperty"||c.endsWith(".ObjectProperty"))&&n.add(a)}}for(let[a,p]of Object.entries(e.body)){if(!p||typeof p!="object"||Array.isArray(p))continue;let s=p,c=this.getPropertyValue(s,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[l,y]of Object.entries(s))l==="type"||l==="label"||l==="comment"||!(n.has(l)||Array.from(n).some(m=>m.endsWith(`.${l}`)))||await this.validateReferenceValue(a,l,y,e,i,t)}return t}async validateReferenceValue(e,o,t,i,r,n){if(t!=null){if(typeof t=="string")await r.resolveEntityAsync(t,i)||n.push(this.createUnresolvedReferenceError(e,o,t));else if(Array.isArray(t))for(let a=0;a<t.length;a++){let p=t[a];typeof p=="string"&&(await r.resolveEntityAsync(p,i)||n.push(this.createUnresolvedReferenceError(e,`${o}[${a}]`,p)))}}}createUnresolvedReferenceError(e,o,t){let i=`The entity '${t}' cannot be found in the current document or any imported namespaces.
4
+ Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,p.expectedValue="A valid class name (Scene, Character, Story, etc.)",o.push(p)}}return o}};var Y=class d{constructor(e,o,t,n){this.publisher=e;this.package_=o;this.name=t;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let o=e.split("/");if(o.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[t,n,r]=o;if(!t||!n||!r)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let i=n.indexOf("@");if(i===-1)return new d(t,n,r,void 0);let a=n.substring(0,i),p=n.substring(i+1);if(!a||!p)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=p.split(".").map(Number),c=oe(s[0]||0,s[1]||0,s[2]||0);return new d(t,a,r,c)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}};function oe(d,e,o){return{major:d,minor:e,patch:o,toString:()=>`${d}.${e}.${o}`,equals:t=>!t||typeof t!="object"?!1:t.major===d&&t.minor===e&&t.patch===o,getHashCode:()=>d<<20|e<<10|o,compareTo:t=>d!==t.major?d-t.major:e!==t.minor?e-t.minor:o-t.patch}}function k(d){if(Array.isArray(d))return d.map(o=>o?.toString()??"").filter(o=>o.length>0);let e=d?.toString();return e?[e]:[]}var A=class{cache=new Map;repository;logger;constructor(e,o){this.repository=e,this.logger=o}async resolveEntityAsync(e,o){let t=o.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(t);if(n){let i=n.get(e);if(i)return i}let r=await this.buildEntityIndexAsyncInternal(o,new Set,"");return this.cache.set(t,r),r.get(e)??null}async resolveAllEntitiesAsync(e,o){let t=await this.buildAllEntitiesIndexAsync(o,new Set,"");if(e.includes(".")){let n=e.split("."),r=n[0],i=n[1],a=await this.findDocumentForAlias(o,r);return a?await this.resolveAllEntitiesAsync(i,a):[]}return t.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,o,t){let n=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),o.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),n;o.add(r);let i=t.length===0?r:`${t} \u2192 ${r}`;for(let[a,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let s=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,s),entity:p,definedInNamespace:r,isImported:t.length>0,importPath:i})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${r}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((p,s)=>p+s.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${r}`);for(let[p,s]of Object.entries(e.metadata.imports))for(let c of s)try{this.logger?.debug?.(`Resolving import: ${p}/${c.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(p,c);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let y=await this.buildAllEntitiesIndexAsync(l,o,i);n.push(...y),this.logger?.debug?.(`Added ${y.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${c.packageName}`)}catch(l){let y=l;throw this.logger?.error?.(`Failed to process import ${p}/${c.packageName} for namespace ${r}. Error: ${y.message}`,y),new Error(`Failed to process import ${p}/${c.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,o,t){let n=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),o.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),n;o.add(r);let i=t.length===0?r:`${t} \u2192 ${r}`,a=0;for(let[p,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)&&!n.has(p)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(p,{entityName:p,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,p,c),entity:s,definedInNamespace:r,isImported:t.length>0,importPath:i}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${r}`),e.metadata?.imports){let p=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${p} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let l of c)try{this.logger?.debug?.(`Resolving import: ${s}/${l.packageName}`);let y=await this.repository.getHighestCompatibleVersionAsync(s,l);if(y){this.logger?.debug?.(`Successfully loaded import: ${y.metadata?.namespace_?.toString()}`);let u=await this.buildEntityIndexAsyncInternal(y,o,i),m=0;for(let[f,g]of u.entries())if(n.has(f)||(n.set(f,g),m++),l.alias&&!f.includes(".")){let R=`${l.alias}.${f}`;n.has(R)||(n.set(R,g),m++)}this.logger?.debug?.(`Merged ${m} entities from import ${y.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${l.packageName}`)}catch(y){let u=y;throw this.logger?.error?.(`Failed to process import ${s}/${l.packageName} for namespace ${r}. Error: ${u.message}`,u),new Error(`Failed to process import ${s}/${l.packageName} for namespace ${r}. See inner exception for details.`,{cause:y})}}return n}async findDocumentForAlias(e,o){if(!e.metadata?.imports)return null;for(let[t,n]of Object.entries(e.metadata.imports))for(let r of n){if(r.alias===o)return await this.repository.getHighestCompatibleVersionAsync(t,r);if(!r.alias&&r.packageName===o)return await this.repository.getHighestCompatibleVersionAsync(t,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,o,t){if(e===o)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,o,t,n)}async isSubclassOfRecursiveAsync(e,o,t,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let i=r.entity.subClassOf;if(i){let a=k(i);for(let p of a)if(p===o||await this.isSubclassOfRecursiveAsync(p,o,t,n))return!0}return!1}async isSubpropertyOfAsync(e,o,t){if(e===o)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,o,t,n)}async isSubpropertyOfRecursiveAsync(e,o,t,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let i=r.entity.subPropertyOf;if(i){let a=k(i);for(let p of a)if(p===o||await this.isSubpropertyOfRecursiveAsync(p,o,t,n))return!0}return!1}};var w=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,o){let t=[],n=new A(o),r=await this.buildPropertyRangeMap(e,n);for(let[i,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.checkEmbeddedTypes(i,a,void 0,r,n,e,t,0);return t}async checkEmbeddedTypes(e,o,t,n,r,i,a,p){if(p>0){let s=o.type;if(s!=null){let c=await this.validateEmbeddedType(e,String(s),t,r,i);c&&a.push(c)}}for(let[s,c]of Object.entries(o)){let l=this.localName(s),y=n.has(l)?n.get(l):t;if(typeof c=="object"&&c!==null)if(Array.isArray(c))for(let u=0;u<c.length;u++){let m=c[u];typeof m=="object"&&m!==null&&!Array.isArray(m)&&await this.checkEmbeddedTypes(`${e}.${s}[${u}]`,m,y,n,r,i,a,p+1)}else await this.checkEmbeddedTypes(`${e}.${s}`,c,y,n,r,i,a,p+1)}}async validateEmbeddedType(e,o,t,n,r){if(o.length===0||!t)return null;let i=this.localName(o),a=this.localName(t);if(a==="Resource"||a==="Class")return null;let p=e.split(".")[0];if(i===a){let c=new h;return c.ruleType=this.ruleName,c.severity="Warning",c.entityName=p,c.propertyName=e,c.actualValue=o,c.expectedValue=t,c.message=`Embedded object at '${e}' declares 'type: ${o}', which equals the parent property's range '${t}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,c.suggestion=`Remove the 'type: ${o}' line, or keep it if explicitness is preferred over concision.`,c}if(await n.isSubclassOfAsync(o,t,r)||(i!==o||a!==t)&&await n.isSubclassOfAsync(i,a,r))return null;let s=new h;return s.ruleType=this.ruleName,s.severity="Error",s.entityName=p,s.propertyName=e,s.actualValue=o,s.expectedValue=t,s.message=`Embedded object at '${e}' has 'type: ${o}', which is not a subclass of the parent property's range '${t}'.`,s.suggestion=`Either remove the 'type: ${o}' line (so the type is inferred from the property's range '${t}'), or add 'subClassOf: ${t}' to the '${o}' class definition so the relationship holds.`,s}localName(e){let o=e.lastIndexOf(".");return o<0||o===e.length-1?e:e.substring(o+1)}async buildPropertyRangeMap(e,o){let t=new Map,n=await o.buildEntityIndexAsync(e);for(let[r,i]of n){let a=i.entity.type;if(a==null)continue;let p=String(a),s=this.localName(p);if(!(s==="Property"||s==="DatatypeProperty"||s==="ObjectProperty"||s==="AnnotationProperty"))continue;let l=i.entity.range;if(l==null)continue;let y=String(l);y.length!==0&&t.set(this.localName(r),y)}return t}};var E=class{ruleName="ImportExistence";async validateAsync(e,o){let t=[];if(!e.metadata?.imports)return t;let n=await o.getAllDocumentsAsync();for(let[r,i]of Object.entries(e.metadata.imports))for(let a of i)if(!await o.getHighestCompatibleVersionAsync(r,a)){let s=await this.determineImportErrorAsync(o,r,a,n),c=new h;c.ruleType=this.ruleName,c.severity="Error",c.message=s.message,c.suggestion=s.suggestion,c.entityName=`Import: ${r}/${a.packageName}`,c.actualValue=a.toString(),c.expectedValue=s.expectedValue,t.push(c)}return t}async determineImportErrorAsync(e,o,t,n){let r=await e.getDocumentsByNamespaceAsync(o,t.packageName);if(r.length===0){let s=n.filter(u=>u.metadata.namespace_?.publisher===o).map(u=>u.metadata.namespace_.package_).filter((u,m,f)=>f.indexOf(u)===m),c=this.findSimilarPackages(t.packageName,s),l=`Import '${o}/${t.package_}' not found - package does not exist`,y=c.length>0?`Did you mean: ${c.slice(0,3).join(", ")}?`:s.length>0?`Available packages in ${o}: ${s.slice(0,5).join(", ")}`:`No packages found for publisher '${o}'. Verify the publisher name is correct.`;return{message:l,suggestion:y,expectedValue:"Existing package"}}let a=r.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),p=this.getAcceptableVersionRange(t);return{message:`Import '${o}/${t.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${p}`,expectedValue:p}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,o){if(o.length===0)return[];let t=o.filter(i=>i.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(i.toLowerCase()));if(t.length>0)return t.sort((i,a)=>i.length-a.length);let n=o.map(i=>({package:i,distance:this.levenshteinDistance(e.toLowerCase(),i.toLowerCase())})).sort((i,a)=>i.distance-a.distance),r=Math.max(3,Math.floor(e.length*.4));return n.filter(i=>i.distance<=r).map(i=>i.package)}levenshteinDistance(e,o){if(!e||e.length===0)return o?.length??0;if(!o||o.length===0)return e.length;let t=e.length,n=o.length,r=Array(t+1).fill(null).map(()=>Array(n+1).fill(0));for(let i=0;i<=t;i++)r[i][0]=i;for(let i=0;i<=n;i++)r[0][i]=i;for(let i=1;i<=t;i++)for(let a=1;a<=n;a++){let p=e[i-1]===o[a-1]?0:1;r[i][a]=Math.min(Math.min(r[i-1][a]+1,r[i][a-1]+1),r[i-1][a-1]+p)}return r[t][n]}};var S=class{ruleName="UnresolvedReference";async validateAsync(e,o){let t=[],n=new A(o),r=await n.buildEntityIndexAsync(e),i=new Set;for(let[a,p]of r.entries()){let s=p.entity.type;if(s){let c=s.toString();(c==="ObjectProperty"||c.endsWith(".ObjectProperty"))&&i.add(a)}}for(let[a,p]of Object.entries(e.body)){if(!p||typeof p!="object"||Array.isArray(p))continue;let s=p,c=this.getPropertyValue(s,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[l,y]of Object.entries(s))l==="type"||l==="label"||l==="comment"||!(i.has(l)||Array.from(i).some(m=>m.endsWith(`.${l}`)))||await this.validateReferenceValue(a,l,y,e,n,t)}return t}async validateReferenceValue(e,o,t,n,r,i){if(t!=null){if(typeof t=="string")await r.resolveEntityAsync(t,n)||i.push(this.createUnresolvedReferenceError(e,o,t));else if(Array.isArray(t))for(let a=0;a<t.length;a++){let p=t[a];typeof p=="string"&&(await r.resolveEntityAsync(p,n)||i.push(this.createUnresolvedReferenceError(e,`${o}[${a}]`,p)))}}}createUnresolvedReferenceError(e,o,t){let n=`The entity '${t}' cannot be found in the current document or any imported namespaces.
5
5
 
6
6
  Possible solutions:
7
7
  \u2022 Add import if the entity is defined in another namespace:
8
8
  kanonak namespace add-import <publisher>/<package>@<version>
9
9
  \u2022 Check for typos in the reference name '${t}'
10
10
  \u2022 Define '${t}' in the current namespace or an appropriate namespace
11
- \u2022 Use 'kanonak search type ${t} --include-imports' to locate the entity`,r=new h;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=o,r.actualValue=t,r.message=`Reference to '${t}' could not be resolved`,r.suggestion=i,r.expectedValue="A valid entity reference that exists in the current document or imported namespaces",r}getPropertyValue(e,o){let t=e[o];return t?t.toString():null}};var j=class{ruleName="TypeAmbiguity";async validateAsync(e,o){let t=[],i=new Map,r=[];if(e.metadata?.imports)for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){r.push({doc:s,import:p,publisher:n});let c=await this.getTransitiveImportsAsync(o,s,new Set);r.push(...c.map(l=>({doc:l,import:null,publisher:n})))}}for(let{doc:n,import:a}of r){let p=n.metadata?.namespace_?.toString()??"unknown";for(let s of Object.keys(n.body))i.has(s)||i.set(s,[]),i.get(s).push({namespace:p,import:a})}for(let[n,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a;this.checkAmbiguousReference(p,"type",i,n,t),this.checkAmbiguousReference(p,"subClassOf",i,n,t),this.checkAmbiguousReference(p,"subPropertyOf",i,n,t),this.checkAmbiguousReference(p,"domain",i,n,t),this.checkAmbiguousReference(p,"range",i,n,t)}return t}checkAmbiguousReference(e,o,t,i,r){let n=e[o];if(!n)return;let a=k(n);for(let p of a){if(p.includes("."))continue;let s=t.get(p);if(s&&s.length>1){let c=s.map(m=>m.namespace).join(", "),l=[];for(let{namespace:m,import:f}of s)if(f?.alias)l.push(`${f.alias}.${p}`);else{let g=m.split("/"),v=g[g.length-1]?.split("@")[0]??"alias";l.push(`${v}.${p}`)}let y=l.length>0?`Use one of: ${l.join(", ")}`:"Consider adding namespace aliases to your imports",u=new h;u.ruleType=this.ruleName,u.severity="Warning",u.entityName=i,u.propertyName=o,u.actualValue=p,u.message=`Type '${p}' is ambiguous. It's defined in: ${c}`,u.suggestion=y,r.push(u)}}}async getTransitiveImportsAsync(e,o,t){let i=[],r=o.metadata?.namespace_?.toString()??"";if(t.has(r))return i;if(t.add(r),o.metadata?.imports)for(let[n,a]of Object.entries(o.metadata.imports))for(let p of a){let s=await e.getHighestCompatibleVersionAsync(n,p);if(s){i.push(s);let c=await this.getTransitiveImportsAsync(e,s,t);i.push(...c)}}return i}};var N=class{ruleName="ClassHierarchyCycle";async validateAsync(e,o){let t=[],i=new Map,r=new Set;await this.buildClassHierarchy(e,o,i,r);for(let[n,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a,s=p.type,c=p.subClassOf;if(s?.toString()==="Class"&&c){let l=n,y=this.detectCycle(l,i);if(y){let u=y.join(" \u2192 "),m=new h;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${u}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=l,m.propertyName="subClassOf",m.actualValue=u,t.push(m);break}}}return t}async buildClassHierarchy(e,o,t,i){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&i.has(r))){r&&i.add(r);for(let[n,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a,s=p.type,c=p.subClassOf;if(s?.toString()==="Class"&&c){let l=k(c);l.length>0&&t.set(n,l)}}if(e.metadata?.imports)for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);s&&await this.buildClassHierarchy(s,o,t,i)}}}detectCycle(e,o){let t=[],i=new Set;return this.detectCycleRecursive(e,o,t,i)}detectCycleRecursive(e,o,t,i){if(t.includes(e)){let n=t.indexOf(e),a=t.slice(n);return a.push(e),a}if(i.has(e))return null;t.push(e),i.add(e);let r=o.get(e);if(r)for(let n of r){let a=this.detectCycleRecursive(n,o,t,i);if(a)return a}return t.pop(),null}};var K=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,o){let t=[],i=new Map,r=new Set;await this.buildPropertyHierarchy(e,o,i,r);for(let[n,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&a.subPropertyOf){let c=n,l=this.detectCycle(c,i);if(l){let y=l.join(" \u2192 "),u=new h;u.ruleType=this.ruleName,u.severity="Error",u.message=`Circular property hierarchy detected: ${y}`,u.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",u.entityName=c,u.propertyName="subPropertyOf",u.actualValue=y,t.push(u);break}}return t}async buildPropertyHierarchy(e,o,t,i){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&i.has(r))){r&&i.add(r);for(let[n,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a,s=p.type;if(s){let c=s.toString();if(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty"){let l=p.subPropertyOf;if(l){let y=k(l);y.length>0&&t.set(n,y)}}}}if(e.metadata?.imports)for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);s&&await this.buildPropertyHierarchy(s,o,t,i)}}}detectCycle(e,o){let t=[],i=new Set;return this.detectCycleRecursive(e,o,t,i)}detectCycleRecursive(e,o,t,i){if(t.includes(e)){let n=t.indexOf(e),a=t.slice(n);return a.push(e),a}if(i.has(e))return null;t.push(e),i.add(e);let r=o.get(e);if(r)for(let n of r){let a=this.detectCycleRecursive(n,o,t,i);if(a)return a}return t.pop(),null}};var C=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,o){let t=[];for(let[i,r]of Object.entries(e.body)){if(typeof r!="object"||r===null||Array.isArray(r))continue;let n=r,a=n.type?.toString();if(a==="DatatypeProperty"||a==="ObjectProperty"||a?.endsWith(".DatatypeProperty")||a?.endsWith(".ObjectProperty")){let p="range"in n,s=n.range?.toString().trim();if(!p||!s){let c=new h;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName="range",c.message=`Property '${i}' must have a 'range' defined.`,c.suggestion=a==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",c.expectedValue=a==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",t.push(c)}}}return t}};var x=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}async validateAsync(e,o){let t=[],i=new Set;for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=n.type?.toString();(p==="Class"||p&&p.endsWith(".Class"))&&i.add(r)}for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=k(n.subClassOf);for(let s=0;s<p.length;s++){let c=p[s];if(this.builtInClasses.has(c)||i.has(c))continue;if(!await this.isClassAvailableInImports(e,o,c)){let y=p.length>1?`[${s}]`:"",u=new h;u.ruleType=this.ruleName,u.severity="Error",u.message=`Class '${c}' referenced in subClassOf${y} is not defined or imported`,u.suggestion=`Define '${c}' as a Class, or import a namespace that contains it`,u.entityName=r,u.propertyName="subClassOf",u.actualValue=c,u.expectedValue="Defined or imported class",t.push(u)}}}return t}async isClassAvailableInImports(e,o,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let n=t.split(".",2);i=n[0],r=n[1]}for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){if(i!==null&&p.alias!==i)continue;let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="Class"||m&&m.endsWith(".Class"))return!0}let y=new Set;if(await this.isClassAvailableInImportsRecursive(s,o,c,y))return!0}}return!1}async isClassAvailableInImportsRecursive(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(y==="Class"||y&&y.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(s,o,t,i))return!0}}return!1}};var T=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,o){let t=[],i=new Set;for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=n.type?.toString();(p==="DatatypeProperty"||p==="ObjectProperty"||p==="AnnotationProperty")&&i.add(r)}for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=k(n.subPropertyOf);for(let s=0;s<p.length;s++){let c=p[s];if(this.builtInProperties.has(c)||i.has(c))continue;if(!await this.isPropertyAvailableInImports(e,o,c)){let y=p.length>1?`[${s}]`:"",u=new h;u.ruleType=this.ruleName,u.severity="Error",u.message=`Property '${c}' referenced in subPropertyOf${y} is not defined or imported`,u.suggestion=`Define '${c}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,u.entityName=r,u.propertyName="subPropertyOf",u.actualValue=c,u.expectedValue="Defined or imported property",t.push(u)}}}return t}async isPropertyAvailableInImports(e,o,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let n=t.split(".",2);i=n[0],r=n[1]}for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){if(i!==null&&p.alias!==i)continue;let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty")return!0}let y=new Set;if(await this.isPropertyAvailableInImportsRecursive(s,o,c,y))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(s,o,t,i))return!0}}return!1}};var _=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,o){let t=[],i=e.metadata.namespace_?.toString();if(!i)return t;let r=new Map,n=new Set;await this.buildImportGraph(e,o,r,n);let a=this.detectCycle(i,r);if(a){let p=a.join(" \u2192 "),s=new h;s.ruleType=this.ruleName,s.severity="Error",s.message=`Circular namespace import detected: ${p}`,s.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",s.entityName="imports",s.propertyName="imports",s.actualValue=p,t.push(s)}return t}async buildImportGraph(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(!(!r||i.has(r))&&(i.add(r),e.metadata.imports)){let n=[];for(let[a,p]of Object.entries(e.metadata.imports))for(let s of p){let c=`${a}/${s.packageName}@${s.version}`;n.push(c);let l=await o.getHighestCompatibleVersionAsync(a,s);l&&await this.buildImportGraph(l,o,t,i)}n.length>0&&t.set(r,n)}}detectCycle(e,o){let t=[],i=new Set;return this.detectCycleRecursive(e,o,t,i)}detectCycleRecursive(e,o,t,i){let r=t.indexOf(e);if(r>=0){let a=t.slice(r);return a.push(e),a}if(i.has(e))return null;t.push(e),i.add(e);let n=o.get(e);if(n)for(let a of n){let p=this.detectCycleRecursive(a,o,t,i);if(p)return p}return t.pop(),null}};var M=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,o){let t=[],i=new Set;for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=n.type?.toString();this.isPropertyType(p)&&i.add(r)}for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,p=a.type?.toString();if(this.isPropertyType(p)||this.isClassType(p))continue;for(let[s,c]of Object.entries(a)){if(!s||this.metadataKeys.has(s))continue;let l=s,y=null;if(s.includes(".")){let m=s.lastIndexOf(".");y=s.substring(0,m),l=s.substring(m+1)}if(i.has(l))continue;if(!await this.isPropertyAvailableInImports(e,o,l,y)){let m=new h;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${s}' is not defined or imported`,m.suggestion=y?`The property '${l}' is not found in the imported namespace with alias '${y}'.
11
+ \u2022 Use 'kanonak search type ${t} --include-imports' to locate the entity`,r=new h;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=o,r.actualValue=t,r.message=`Reference to '${t}' could not be resolved`,r.suggestion=n,r.expectedValue="A valid entity reference that exists in the current document or imported namespaces",r}getPropertyValue(e,o){let t=e[o];return t?t.toString():null}};var j=class{ruleName="TypeAmbiguity";async validateAsync(e,o){let t=[],n=new Map,r=[];if(e.metadata?.imports)for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){r.push({doc:s,import:p,publisher:i});let c=await this.getTransitiveImportsAsync(o,s,new Set);r.push(...c.map(l=>({doc:l,import:null,publisher:i})))}}for(let{doc:i,import:a}of r){let p=i.metadata?.namespace_?.toString()??"unknown";for(let s of Object.keys(i.body))n.has(s)||n.set(s,[]),n.get(s).push({namespace:p,import:a})}for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a;this.checkAmbiguousReference(p,"type",n,i,t),this.checkAmbiguousReference(p,"subClassOf",n,i,t),this.checkAmbiguousReference(p,"subPropertyOf",n,i,t),this.checkAmbiguousReference(p,"domain",n,i,t),this.checkAmbiguousReference(p,"range",n,i,t)}return t}checkAmbiguousReference(e,o,t,n,r){let i=e[o];if(!i)return;let a=k(i);for(let p of a){if(p.includes("."))continue;let s=t.get(p);if(s&&s.length>1){let c=s.map(m=>m.namespace).join(", "),l=[];for(let{namespace:m,import:f}of s)if(f?.alias)l.push(`${f.alias}.${p}`);else{let g=m.split("/"),v=g[g.length-1]?.split("@")[0]??"alias";l.push(`${v}.${p}`)}let y=l.length>0?`Use one of: ${l.join(", ")}`:"Consider adding namespace aliases to your imports",u=new h;u.ruleType=this.ruleName,u.severity="Warning",u.entityName=n,u.propertyName=o,u.actualValue=p,u.message=`Type '${p}' is ambiguous. It's defined in: ${c}`,u.suggestion=y,r.push(u)}}}async getTransitiveImportsAsync(e,o,t){let n=[],r=o.metadata?.namespace_?.toString()??"";if(t.has(r))return n;if(t.add(r),o.metadata?.imports)for(let[i,a]of Object.entries(o.metadata.imports))for(let p of a){let s=await e.getHighestCompatibleVersionAsync(i,p);if(s){n.push(s);let c=await this.getTransitiveImportsAsync(e,s,t);n.push(...c)}}return n}};var N=class{ruleName="ClassHierarchyCycle";async validateAsync(e,o){let t=[],n=new Map,r=new Set;await this.buildClassHierarchy(e,o,n,r);for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a,s=p.type,c=p.subClassOf;if(s?.toString()==="Class"&&c){let l=i,y=this.detectCycle(l,n);if(y){let u=y.join(" \u2192 "),m=new h;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${u}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=l,m.propertyName="subClassOf",m.actualValue=u,t.push(m);break}}}return t}async buildClassHierarchy(e,o,t,n){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&n.has(r))){r&&n.add(r);for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a,s=p.type,c=p.subClassOf;if(s?.toString()==="Class"&&c){let l=k(c);l.length>0&&t.set(i,l)}}if(e.metadata?.imports)for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);s&&await this.buildClassHierarchy(s,o,t,n)}}}detectCycle(e,o){let t=[],n=new Set;return this.detectCycleRecursive(e,o,t,n)}detectCycleRecursive(e,o,t,n){if(t.includes(e)){let i=t.indexOf(e),a=t.slice(i);return a.push(e),a}if(n.has(e))return null;t.push(e),n.add(e);let r=o.get(e);if(r)for(let i of r){let a=this.detectCycleRecursive(i,o,t,n);if(a)return a}return t.pop(),null}};var K=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,o){let t=[],n=new Map,r=new Set;await this.buildPropertyHierarchy(e,o,n,r);for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&a.subPropertyOf){let c=i,l=this.detectCycle(c,n);if(l){let y=l.join(" \u2192 "),u=new h;u.ruleType=this.ruleName,u.severity="Error",u.message=`Circular property hierarchy detected: ${y}`,u.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",u.entityName=c,u.propertyName="subPropertyOf",u.actualValue=y,t.push(u);break}}return t}async buildPropertyHierarchy(e,o,t,n){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&n.has(r))){r&&n.add(r);for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let p=a,s=p.type;if(s){let c=s.toString();if(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty"){let l=p.subPropertyOf;if(l){let y=k(l);y.length>0&&t.set(i,y)}}}}if(e.metadata?.imports)for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);s&&await this.buildPropertyHierarchy(s,o,t,n)}}}detectCycle(e,o){let t=[],n=new Set;return this.detectCycleRecursive(e,o,t,n)}detectCycleRecursive(e,o,t,n){if(t.includes(e)){let i=t.indexOf(e),a=t.slice(i);return a.push(e),a}if(n.has(e))return null;t.push(e),n.add(e);let r=o.get(e);if(r)for(let i of r){let a=this.detectCycleRecursive(i,o,t,n);if(a)return a}return t.pop(),null}};var C=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,o){let t=[];for(let[n,r]of Object.entries(e.body)){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r,a=i.type?.toString();if(a==="DatatypeProperty"||a==="ObjectProperty"||a?.endsWith(".DatatypeProperty")||a?.endsWith(".ObjectProperty")){let p="range"in i,s=i.range?.toString().trim();if(!p||!s){let c=new h;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.propertyName="range",c.message=`Property '${n}' must have a 'range' defined.`,c.suggestion=a==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",c.expectedValue=a==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",t.push(c)}}}return t}};var x=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}async validateAsync(e,o){let t=[],n=new Set;for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type?.toString();(p==="Class"||p&&p.endsWith(".Class"))&&n.add(r)}for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=k(i.subClassOf);for(let s=0;s<p.length;s++){let c=p[s];if(this.builtInClasses.has(c)||n.has(c))continue;if(!await this.isClassAvailableInImports(e,o,c)){let y=p.length>1?`[${s}]`:"",u=new h;u.ruleType=this.ruleName,u.severity="Error",u.message=`Class '${c}' referenced in subClassOf${y} is not defined or imported`,u.suggestion=`Define '${c}' as a Class, or import a namespace that contains it`,u.entityName=r,u.propertyName="subClassOf",u.actualValue=c,u.expectedValue="Defined or imported class",t.push(u)}}}return t}async isClassAvailableInImports(e,o,t){if(!e.metadata.imports)return!1;let n=null,r=t;if(t.includes(".")){let i=t.split(".",2);n=i[0],r=i[1]}for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){if(n!==null&&p.alias!==n)continue;let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=n!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="Class"||m&&m.endsWith(".Class"))return!0}let y=new Set;if(await this.isClassAvailableInImportsRecursive(s,o,c,y))return!0}}return!1}async isClassAvailableInImportsRecursive(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(r&&n.has(r)||(r&&n.add(r),!e.metadata.imports))return!1;for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(y==="Class"||y&&y.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(s,o,t,n))return!0}}return!1}};var T=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,o){let t=[],n=new Set;for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type?.toString();(p==="DatatypeProperty"||p==="ObjectProperty"||p==="AnnotationProperty")&&n.add(r)}for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=k(i.subPropertyOf);for(let s=0;s<p.length;s++){let c=p[s];if(this.builtInProperties.has(c)||n.has(c))continue;if(!await this.isPropertyAvailableInImports(e,o,c)){let y=p.length>1?`[${s}]`:"",u=new h;u.ruleType=this.ruleName,u.severity="Error",u.message=`Property '${c}' referenced in subPropertyOf${y} is not defined or imported`,u.suggestion=`Define '${c}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,u.entityName=r,u.propertyName="subPropertyOf",u.actualValue=c,u.expectedValue="Defined or imported property",t.push(u)}}}return t}async isPropertyAvailableInImports(e,o,t){if(!e.metadata.imports)return!1;let n=null,r=t;if(t.includes(".")){let i=t.split(".",2);n=i[0],r=i[1]}for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){if(n!==null&&p.alias!==n)continue;let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=n!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty")return!0}let y=new Set;if(await this.isPropertyAvailableInImportsRecursive(s,o,c,y))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(r&&n.has(r)||(r&&n.add(r),!e.metadata.imports))return!1;for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(s,o,t,n))return!0}}return!1}};var _=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,o){let t=[],n=e.metadata.namespace_?.toString();if(!n)return t;let r=new Map,i=new Set;await this.buildImportGraph(e,o,r,i);let a=this.detectCycle(n,r);if(a){let p=a.join(" \u2192 "),s=new h;s.ruleType=this.ruleName,s.severity="Error",s.message=`Circular namespace import detected: ${p}`,s.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",s.entityName="imports",s.propertyName="imports",s.actualValue=p,t.push(s)}return t}async buildImportGraph(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(!(!r||n.has(r))&&(n.add(r),e.metadata.imports)){let i=[];for(let[a,p]of Object.entries(e.metadata.imports))for(let s of p){let c=`${a}/${s.packageName}@${s.version}`;i.push(c);let l=await o.getHighestCompatibleVersionAsync(a,s);l&&await this.buildImportGraph(l,o,t,n)}i.length>0&&t.set(r,i)}}detectCycle(e,o){let t=[],n=new Set;return this.detectCycleRecursive(e,o,t,n)}detectCycleRecursive(e,o,t,n){let r=t.indexOf(e);if(r>=0){let a=t.slice(r);return a.push(e),a}if(n.has(e))return null;t.push(e),n.add(e);let i=o.get(e);if(i)for(let a of i){let p=this.detectCycleRecursive(a,o,t,n);if(p)return p}return t.pop(),null}};var M=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,o){let t=[],n=new Set;for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type?.toString();this.isPropertyType(p)&&n.add(r)}for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i,p=a.type?.toString();if(this.isPropertyType(p)||this.isClassType(p))continue;for(let[s,c]of Object.entries(a)){if(!s||this.metadataKeys.has(s))continue;let l=s,y=null;if(s.includes(".")){let m=s.lastIndexOf(".");y=s.substring(0,m),l=s.substring(m+1)}if(n.has(l))continue;if(!await this.isPropertyAvailableInImports(e,o,l,y)){let m=new h;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${s}' is not defined or imported`,m.suggestion=y?`The property '${l}' is not found in the imported namespace with alias '${y}'.
12
12
  1. Verify the namespace is imported with the correct alias
13
13
  2. Check if the property name is spelled correctly
14
14
  3. Ensure the imported namespace version contains this property`:`The property '${s}' is not defined in this namespace or any imported namespace.
15
15
  1. Define '${s}' as an ObjectProperty or DatatypeProperty in this namespace, OR
16
16
  2. Import the namespace that contains '${s}', OR
17
- 3. Use a qualified reference like 'alias.${s}' if already imported with an alias`,m.entityName=r,m.propertyName=s,m.actualValue=c?.toString(),m.expectedValue="A defined or imported property",t.push(m)}}}return t}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,o,t,i){if(!e.metadata.imports)return!1;for(let[r,n]of Object.entries(e.metadata.imports))for(let a of n){if(i!==null&&a.alias!==i)continue;let p=await o.getHighestCompatibleVersionAsync(r,a);if(p){let s=p.body[t];if(s&&typeof s=="object"&&!Array.isArray(s)){let y=s.type?.toString();if(this.isPropertyType(y))return!0}let c=new Set;if(await this.isPropertyAvailableInImportsRecursive(p,o,t,c))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(s,o,t,i))return!0}}return!1}};var W=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,o){let t=[],i=new Set;for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=n.type?.toString();this.isPropertyType(p)&&i.add(r)}for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,p=a.type?.toString();if(!this.isPropertyType(p)&&!this.isClassType(p))continue;for(let[s,c]of Object.entries(a)){if(!s||this.metadataKeys.has(s))continue;let l=s,y=null;if(s.includes(".")){let m=s.lastIndexOf(".");y=s.substring(0,m),l=s.substring(m+1)}if(i.has(l))continue;if(!await this.isPropertyAvailableInImports(e,o,l,y)){let m=this.isClassType(p)?"class":"property",f=new h;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${s}' used on ${m} '${r}' is not defined or imported`,f.suggestion=y?`The property '${l}' is not found in the imported namespace with alias '${y}'.
17
+ 3. Use a qualified reference like 'alias.${s}' if already imported with an alias`,m.entityName=r,m.propertyName=s,m.actualValue=c?.toString(),m.expectedValue="A defined or imported property",t.push(m)}}}return t}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,o,t,n){if(!e.metadata.imports)return!1;for(let[r,i]of Object.entries(e.metadata.imports))for(let a of i){if(n!==null&&a.alias!==n)continue;let p=await o.getHighestCompatibleVersionAsync(r,a);if(p){let s=p.body[t];if(s&&typeof s=="object"&&!Array.isArray(s)){let y=s.type?.toString();if(this.isPropertyType(y))return!0}let c=new Set;if(await this.isPropertyAvailableInImportsRecursive(p,o,t,c))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(r&&n.has(r)||(r&&n.add(r),!e.metadata.imports))return!1;for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(s,o,t,n))return!0}}return!1}};var L=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,o){let t=[],n=new Set;for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type?.toString();this.isPropertyType(p)&&n.add(r)}for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i,p=a.type?.toString();if(!this.isPropertyType(p)&&!this.isClassType(p))continue;for(let[s,c]of Object.entries(a)){if(!s||this.metadataKeys.has(s))continue;let l=s,y=null;if(s.includes(".")){let m=s.lastIndexOf(".");y=s.substring(0,m),l=s.substring(m+1)}if(n.has(l))continue;if(!await this.isPropertyAvailableInImports(e,o,l,y)){let m=this.isClassType(p)?"class":"property",f=new h;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${s}' used on ${m} '${r}' is not defined or imported`,f.suggestion=y?`The property '${l}' is not found in the imported namespace with alias '${y}'.
18
18
  1. Verify the namespace is imported with the correct alias
19
19
  2. Check if the property name is spelled correctly
20
20
  3. Ensure the imported namespace version contains this property`:`The property '${s}' is not defined in this namespace or any imported namespace.
21
21
  1. Define '${s}' as an ObjectProperty or DatatypeProperty in this namespace, OR
22
22
  2. Import the namespace that contains '${s}', OR
23
- 3. Use a qualified reference like 'alias.${s}' if already imported with an alias`,f.entityName=r,f.propertyName=s,f.actualValue=c?.toString(),f.expectedValue="A defined or imported property",t.push(f)}}}return t}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,o,t,i){if(!e.metadata.imports)return!1;for(let[r,n]of Object.entries(e.metadata.imports))for(let a of n){if(i!==null&&a.alias!==i)continue;let p=await o.getHighestCompatibleVersionAsync(r,a);if(p){let s=p.body[t];if(s&&typeof s=="object"&&!Array.isArray(s)){let y=s.type?.toString();if(this.isPropertyType(y))return!0}let c=new Set;if(await this.isPropertyAvailableInImportsRecursive(p,o,t,c))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(s,o,t,i))return!0}}return!1}};var L=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,o){let t=[],i=new Set,r=[];for(let[n,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=!1,c=p.type;if(Array.isArray(c)){for(let l of c)if(l?.toString()==="DatatypeProperty"){s=!0;break}}else c?.toString()==="DatatypeProperty"&&(s=!0);if(s){r.push(n);let l=this.getPropertyValue(p,"range");l&&this.xsdTypes.has(l)&&i.add(l)}}if(i.size>0&&!await this.checkXsdImportAsync(e.metadata,o)){let a=Array.from(i).sort().join(", "),p=r.sort().join(", "),s=new h;s.ruleType=this.ruleName,s.severity="Error",s.message=`XSD namespace not imported but XSD types are used: ${a}`,s.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${p}`,s.entityName="imports",t.push(s)}return t}async checkXsdImportAsync(e,o,t=new Set){if(!e?.imports)return!1;let i=e.namespace_?.toString()??"";if(i&&t.has(i))return!1;i&&t.add(i);for(let[,r]of Object.entries(e.imports))for(let n of r)if(n.packageName==="xsd"||n.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[r,n]of Object.entries(e.imports))for(let a of n){let p=await o.getHighestCompatibleVersionAsync(r,a);if(p?.metadata&&await this.checkXsdImportAsync(p.metadata,o,t))return!0}return!1}getPropertyValue(e,o){return e[o]?.toString()}};var H=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,o){let t=[],i=await this.buildEntitySourceMapAsync(e,o),r=await this.buildDatatypePropertyNamesAsync(e,o);for(let[n,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&this.validateEntityReferences(n,a,i,r,e,t);return t}async buildEntitySourceMapAsync(e,o){let t=new Map,i=new Set;for(let r of Object.keys(e.body)){let n=e.metadata.namespace_?.toString()??"";t.has(r)||t.set(r,[]),t.get(r).push(`(local:${n})`)}if(e.metadata.imports)for(let[r,n]of Object.entries(e.metadata.imports))for(let a of n){let p=await o.getHighestCompatibleVersionAsync(r,a);p&&await this.collectEntitiesRecursivelyAsync(p,t,i,o)}return t}async collectEntitiesRecursivelyAsync(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(!t.has(r)){t.add(r);for(let n of Object.keys(e.body)){o.has(n)||o.set(n,[]);let a=o.get(n);a.includes(r)||a.push(r)}if(e.metadata.imports)for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await i.getHighestCompatibleVersionAsync(n,p);s&&await this.collectEntitiesRecursivelyAsync(s,o,t,i)}}}async buildDatatypePropertyNamesAsync(e,o){let t=new Set,i=new Set;if(await this.collectDatatypePropertiesAsync(e,t,i,o),e.metadata.imports)for(let[r,n]of Object.entries(e.metadata.imports))for(let a of n){let p=await o.getHighestCompatibleVersionAsync(r,a);p&&await this.collectDatatypePropertiesAsync(p,t,i,o)}return t}async collectDatatypePropertiesAsync(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(!t.has(r)){t.add(r);for(let[n,a]of Object.entries(e.body)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let p=a.type;if(typeof p!="string")continue;(p.includes(".")?p.substring(p.lastIndexOf(".")+1):p)==="DatatypeProperty"&&o.add(n)}if(e.metadata.imports)for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await i.getHighestCompatibleVersionAsync(n,p);s&&await this.collectDatatypePropertiesAsync(s,o,t,i)}}}validateEntityReferences(e,o,t,i,r,n){for(let[a,p]of Object.entries(o)){let s=a;if(s&&!s.includes(".")){let c=t.get(s);if(c&&c.length>1&&!c.some(y=>y.startsWith("(local:"))){let y=c.filter(u=>!u.startsWith("(local:"));y.length>1&&n.push(this.createAmbiguityError(e,s,`Property '${s}'`,y,r,!0,s))}}this.validatePropertyValue(e,s,p,t,i,r,n)}}validatePropertyValue(e,o,t,i,r,n,a){if(t==null)return;let p=o&&o.includes(".")?o.substring(o.lastIndexOf(".")+1):o,s=!!p&&r.has(p);if(typeof t=="string"&&!t.includes(".")&&!s){let c=i.get(t);if(c&&c.length>1&&!c.some(y=>y.startsWith("(local:"))){let y=c.filter(u=>!u.startsWith("(local:"));y.length>1&&a.push(this.createAmbiguityError(e,o,`Reference '${t}'`,y,n,!1,t))}}else if(Array.isArray(t))for(let c=0;c<t.length;c++){let l=`${e}.${o}[${c}]`;this.validatePropertyValue(l,o,t[c],i,r,n,a)}else if(typeof t=="object"&&!Array.isArray(t)){let c=o?`${e}.${o}`:e;this.validateEntityReferences(c,t,i,r,n,a)}}createAmbiguityError(e,o,t,i,r,n,a){let p=[];for(let f of i){let g=this.findAliasForNamespace(r,f);if(g){let R=o?.split(".").pop()??o;p.push(`${g}.${R}`)}}let s=p.length>0?`Use one of: ${p.map(f=>`'${f}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${o}')`,c=i.map(f=>` \u2022 ${f}`).join(`
23
+ 3. Use a qualified reference like 'alias.${s}' if already imported with an alias`,f.entityName=r,f.propertyName=s,f.actualValue=c?.toString(),f.expectedValue="A defined or imported property",t.push(f)}}}return t}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,o,t,n){if(!e.metadata.imports)return!1;for(let[r,i]of Object.entries(e.metadata.imports))for(let a of i){if(n!==null&&a.alias!==n)continue;let p=await o.getHighestCompatibleVersionAsync(r,a);if(p){let s=p.body[t];if(s&&typeof s=="object"&&!Array.isArray(s)){let y=s.type?.toString();if(this.isPropertyType(y))return!0}let c=new Set;if(await this.isPropertyAvailableInImportsRecursive(p,o,t,c))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(r&&n.has(r)||(r&&n.add(r),!e.metadata.imports))return!1;for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(s,o,t,n))return!0}}return!1}};var W=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,o){let t=[],n=new Set,r=[];for(let[i,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=!1,c=p.type;if(Array.isArray(c)){for(let l of c)if(l?.toString()==="DatatypeProperty"){s=!0;break}}else c?.toString()==="DatatypeProperty"&&(s=!0);if(s){r.push(i);let l=this.getPropertyValue(p,"range");l&&this.xsdTypes.has(l)&&n.add(l)}}if(n.size>0&&!await this.checkXsdImportAsync(e.metadata,o)){let a=Array.from(n).sort().join(", "),p=r.sort().join(", "),s=new h;s.ruleType=this.ruleName,s.severity="Error",s.message=`XSD namespace not imported but XSD types are used: ${a}`,s.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${p}`,s.entityName="imports",t.push(s)}return t}async checkXsdImportAsync(e,o,t=new Set){if(!e?.imports)return!1;let n=e.namespace_?.toString()??"";if(n&&t.has(n))return!1;n&&t.add(n);for(let[,r]of Object.entries(e.imports))for(let i of r)if(i.packageName==="xsd"||i.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[r,i]of Object.entries(e.imports))for(let a of i){let p=await o.getHighestCompatibleVersionAsync(r,a);if(p?.metadata&&await this.checkXsdImportAsync(p.metadata,o,t))return!0}return!1}getPropertyValue(e,o){return e[o]?.toString()}};var H=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,o){let t=[],n=await this.buildEntitySourceMapAsync(e,o),r=await this.buildDatatypePropertyNamesAsync(e,o);for(let[i,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&this.validateEntityReferences(i,a,n,r,e,t);return t}async buildEntitySourceMapAsync(e,o){let t=new Map,n=new Set;for(let r of Object.keys(e.body)){let i=e.metadata.namespace_?.toString()??"";t.has(r)||t.set(r,[]),t.get(r).push(`(local:${i})`)}if(e.metadata.imports)for(let[r,i]of Object.entries(e.metadata.imports))for(let a of i){let p=await o.getHighestCompatibleVersionAsync(r,a);p&&await this.collectEntitiesRecursivelyAsync(p,t,n,o)}return t}async collectEntitiesRecursivelyAsync(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(!t.has(r)){t.add(r);for(let i of Object.keys(e.body)){o.has(i)||o.set(i,[]);let a=o.get(i);a.includes(r)||a.push(r)}if(e.metadata.imports)for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await n.getHighestCompatibleVersionAsync(i,p);s&&await this.collectEntitiesRecursivelyAsync(s,o,t,n)}}}async buildDatatypePropertyNamesAsync(e,o){let t=new Set,n=new Set;if(await this.collectDatatypePropertiesAsync(e,t,n,o),e.metadata.imports)for(let[r,i]of Object.entries(e.metadata.imports))for(let a of i){let p=await o.getHighestCompatibleVersionAsync(r,a);p&&await this.collectDatatypePropertiesAsync(p,t,n,o)}return t}async collectDatatypePropertiesAsync(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(!t.has(r)){t.add(r);for(let[i,a]of Object.entries(e.body)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let p=a.type;if(typeof p!="string")continue;(p.includes(".")?p.substring(p.lastIndexOf(".")+1):p)==="DatatypeProperty"&&o.add(i)}if(e.metadata.imports)for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await n.getHighestCompatibleVersionAsync(i,p);s&&await this.collectDatatypePropertiesAsync(s,o,t,n)}}}validateEntityReferences(e,o,t,n,r,i){for(let[a,p]of Object.entries(o)){let s=a;if(s&&!s.includes(".")){let c=t.get(s);if(c&&c.length>1&&!c.some(y=>y.startsWith("(local:"))){let y=c.filter(u=>!u.startsWith("(local:"));y.length>1&&i.push(this.createAmbiguityError(e,s,`Property '${s}'`,y,r,!0,s))}}this.validatePropertyValue(e,s,p,t,n,r,i)}}validatePropertyValue(e,o,t,n,r,i,a){if(t==null)return;let p=o&&o.includes(".")?o.substring(o.lastIndexOf(".")+1):o,s=!!p&&r.has(p);if(typeof t=="string"&&!t.includes(".")&&!s){let c=n.get(t);if(c&&c.length>1&&!c.some(y=>y.startsWith("(local:"))){let y=c.filter(u=>!u.startsWith("(local:"));y.length>1&&a.push(this.createAmbiguityError(e,o,`Reference '${t}'`,y,i,!1,t))}}else if(Array.isArray(t))for(let c=0;c<t.length;c++){let l=`${e}.${o}[${c}]`;this.validatePropertyValue(l,o,t[c],n,r,i,a)}else if(typeof t=="object"&&!Array.isArray(t)){let c=o?`${e}.${o}`:e;this.validateEntityReferences(c,t,n,r,i,a)}}createAmbiguityError(e,o,t,n,r,i,a){let p=[];for(let f of n){let g=this.findAliasForNamespace(r,f);if(g){let R=o?.split(".").pop()??o;p.push(`${g}.${R}`)}}let s=p.length>0?`Use one of: ${p.map(f=>`'${f}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${o}')`,c=n.map(f=>` \u2022 ${f}`).join(`
24
24
  `),l=e.split(".")[0],y=e.includes(".")?e:o,u=new h;u.ruleType=this.ruleName,u.severity="Error",u.entityName=l,y&&(u.propertyName=y);let m=a??o;return m&&(u.actualValue=m),u.message=`${t} is ambiguous - defined in multiple imported namespaces`,u.suggestion=`${s}
25
25
 
26
26
  Defined in:
27
- ${c}`,u.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",u}findAliasForNamespace(e,o){if(!e.metadata.imports)return null;for(let[t,i]of Object.entries(e.metadata.imports))for(let r of i)if(`${t}/${r.packageName}@${r.version}`===o&&r.alias)return r.alias;return null}};var F=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,o){let t=[],i=new Set;for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let p=n.type?.toString();this.isValidRangeTargetType(p)&&i.add(r)}for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,p=a.type?.toString();if(p!=="DatatypeProperty"&&p!=="ObjectProperty"&&!p?.endsWith(".DatatypeProperty")&&!p?.endsWith(".ObjectProperty"))continue;let s=a.range;if(!s)continue;let c=[];if(Array.isArray(s))for(let l of s){let y=l?.toString();y&&c.push(y)}else{let l=s?.toString();l&&c.push(l)}if(c.length===0)continue;for(let l of c){if(this.primitiveTypes.has(l)||this.builtInClasses.has(l)||i.has(l))continue;if(!await this.isTypeAvailableInImports(e,o,l)){let u=p?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",m=new h;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${r}' has range '${l}' which is not defined or imported`,m.suggestion=u==="ObjectProperty"?`For ObjectProperty:
27
+ ${c}`,u.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",u}findAliasForNamespace(e,o){if(!e.metadata.imports)return null;for(let[t,n]of Object.entries(e.metadata.imports))for(let r of n)if(`${t}/${r.packageName}@${r.version}`===o&&r.alias)return r.alias;return null}};var U=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,o){let t=[],n=new Set;for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type?.toString();this.isValidRangeTargetType(p)&&n.add(r)}for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i,p=a.type?.toString();if(p!=="DatatypeProperty"&&p!=="ObjectProperty"&&!p?.endsWith(".DatatypeProperty")&&!p?.endsWith(".ObjectProperty"))continue;let s=a.range;if(!s)continue;let c=[];if(Array.isArray(s))for(let l of s){let y=l?.toString();y&&c.push(y)}else{let l=s?.toString();l&&c.push(l)}if(c.length===0)continue;for(let l of c){if(this.primitiveTypes.has(l)||this.builtInClasses.has(l)||n.has(l))continue;if(!await this.isTypeAvailableInImports(e,o,l)){let u=p?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",m=new h;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${r}' has range '${l}' which is not defined or imported`,m.suggestion=u==="ObjectProperty"?`For ObjectProperty:
28
28
  1. Define '${l}' as a Class in this namespace, OR
29
29
  2. Import the namespace that contains '${l}', OR
30
30
  3. Use a qualified reference like 'alias.${l}' if already imported with an alias`:`For DatatypeProperty:
31
31
  1. Use a primitive type (string, integer, boolean, dateTime, etc.), OR
32
- 2. If '${l}' should be a class, change property type to ObjectProperty`,m.entityName=r,m.propertyName="range",m.actualValue=l,m.expectedValue=u==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",t.push(m)}}}return t}async isTypeAvailableInImports(e,o,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let n=t.split(".",2);i=n[0],r=n[1]}for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){if(i!==null&&p.alias!==i)continue;let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isValidRangeTargetType(m))return!0}let y=new Set;if(await this.isTypeAvailableInImportsRecursive(s,o,c,y))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,o,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[n,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(n,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isValidRangeTargetType(y))return!0}if(await this.isTypeAvailableInImportsRecursive(s,o,t,i))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var U=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"ObjectPropertyImport"}async validateAsync(e,o){let t=[],i=new Map,r=new V(o);await r.buildEntityIndexAsync(e);for(let[n,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=!1,c=p.type;if(Array.isArray(c)){for(let l of c)if(l?.toString()==="ObjectProperty"){s=!0;break}}else c?.toString()==="ObjectProperty"&&(s=!0);if(s){let l=p.range,y=[];if(Array.isArray(l))for(let u of l){let m=u?.toString();m&&y.push(m)}else{let u=l?.toString();u&&y.push(u)}for(let u of y)this.xsdTypes.has(u)||(i.has(u)||i.set(u,[]),i.get(u).push(n))}}for(let[n,a]of i)if(!await r.resolveEntityAsync(n,e))for(let s of a){let c=new h;c.ruleType=this.ruleName,c.severity="Warning",c.message=`ObjectProperty references class '${n}' which may not be imported`,c.suggestion=`Ensure the namespace containing '${n}' is imported, or define '${n}' in this document`,c.entityName=s,c.propertyName="range",c.actualValue=n,t.push(c)}return t}};var J=class d{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&d.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let o=e.includes(".")?e.split(".")[1]:e;return d.KNOWN_XSD_DATATYPES.has(o.toLowerCase())}async isClassTypeAsync(e,o){if(this.isKnownXsdDatatypeName(e))return!1;let t=await this.resourceResolver.resolveEntityAsync(e,o);if(t){let i=t.entity.type;if(i){let r=String(i);return r==="Class"||r==="rdfs.Class"||r.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,o){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(o)||e==="Property"&&this.isLiteralType(o))}isEffectiveObjectProperty(e,o){return!!(e==="ObjectProperty"||e==="Property"&&o&&!this.isXsdDatatype(o)&&!this.isLiteralType(o))}};var q=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"ObjectPropertyValue"}async validateAsync(e,o){let t=[],i=new V(o),r=new J(i),n=await i.buildEntityIndexAsync(e),a=await this.buildPropertyMetadataAsync(e,o,i,n);for(let[p,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&await this.scanEntityForObjectProperties(s,p,"",a,i,r,e,t);return t}async scanEntityForObjectProperties(e,o,t,i,r,n,a,p){for(let[s,c]of Object.entries(e)){if(this.standardProperties.has(s))continue;let l=s,y=s.lastIndexOf(".");y>0&&y<s.length-1&&(l=s.substring(y+1));let u=i.get(l);if(u&&n.isEffectiveObjectProperty(u.propertyType,u.rangeUri)){let f=t?`${t}.${s}`:s;if(typeof c=="string"&&c.trim().length>0){let g=c.trim();if(g.includes(",")){let v=g.split(",").map(A=>A.trim()).filter(A=>A.length>0);p.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
32
+ 2. If '${l}' should be a class, change property type to ObjectProperty`,m.entityName=r,m.propertyName="range",m.actualValue=l,m.expectedValue=u==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",t.push(m)}}}return t}async isTypeAvailableInImports(e,o,t){if(!e.metadata.imports)return!1;let n=null,r=t;if(t.includes(".")){let i=t.split(".",2);n=i[0],r=i[1]}for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){if(n!==null&&p.alias!==n)continue;let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=n!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isValidRangeTargetType(m))return!0}let y=new Set;if(await this.isTypeAvailableInImportsRecursive(s,o,c,y))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,o,t,n){let r=e.metadata.namespace_?.toString()??"";if(r&&n.has(r)||(r&&n.add(r),!e.metadata.imports))return!1;for(let[i,a]of Object.entries(e.metadata.imports))for(let p of a){let s=await o.getHighestCompatibleVersionAsync(i,p);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isValidRangeTargetType(y))return!0}if(await this.isTypeAvailableInImportsRecursive(s,o,t,n))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var F=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"ObjectPropertyImport"}async validateAsync(e,o){let t=[],n=new Map,r=new A(o);await r.buildEntityIndexAsync(e);for(let[i,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=!1,c=p.type;if(Array.isArray(c)){for(let l of c)if(l?.toString()==="ObjectProperty"){s=!0;break}}else c?.toString()==="ObjectProperty"&&(s=!0);if(s){let l=p.range,y=[];if(Array.isArray(l))for(let u of l){let m=u?.toString();m&&y.push(m)}else{let u=l?.toString();u&&y.push(u)}for(let u of y)this.xsdTypes.has(u)||(n.has(u)||n.set(u,[]),n.get(u).push(i))}}for(let[i,a]of n)if(!await r.resolveEntityAsync(i,e))for(let s of a){let c=new h;c.ruleType=this.ruleName,c.severity="Warning",c.message=`ObjectProperty references class '${i}' which may not be imported`,c.suggestion=`Ensure the namespace containing '${i}' is imported, or define '${i}' in this document`,c.entityName=s,c.propertyName="range",c.actualValue=i,t.push(c)}return t}};var J=class d{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&d.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let o=e.includes(".")?e.split(".")[1]:e;return d.KNOWN_XSD_DATATYPES.has(o.toLowerCase())}async isClassTypeAsync(e,o){if(this.isKnownXsdDatatypeName(e))return!1;let t=await this.resourceResolver.resolveEntityAsync(e,o);if(t){let n=t.entity.type;if(n){let r=String(n);return r==="Class"||r==="rdfs.Class"||r.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,o){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(o)||e==="Property"&&this.isLiteralType(o))}isEffectiveObjectProperty(e,o){return!!(e==="ObjectProperty"||e==="Property"&&o&&!this.isXsdDatatype(o)&&!this.isLiteralType(o))}};var q=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"ObjectPropertyValue"}async validateAsync(e,o){let t=[],n=new A(o),r=new J(n),i=await n.buildEntityIndexAsync(e),a=await this.buildPropertyMetadataAsync(e,o,n,i);for(let[p,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&await this.scanEntityForObjectProperties(s,p,"",a,n,r,e,t);return t}async scanEntityForObjectProperties(e,o,t,n,r,i,a,p){for(let[s,c]of Object.entries(e)){if(this.standardProperties.has(s))continue;let l=s,y=s.lastIndexOf(".");y>0&&y<s.length-1&&(l=s.substring(y+1));let u=n.get(l);if(u&&i.isEffectiveObjectProperty(u.propertyType,u.rangeUri)){let f=t?`${t}.${s}`:s;if(typeof c=="string"&&c.trim().length>0){let g=c.trim();if(g.includes(",")){let v=g.split(",").map(V=>V.trim()).filter(V=>V.length>0);p.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
33
33
  ${s}:
34
34
  - ${v[0]}
35
- ${v.slice(1).map(A=>` - ${A}`).join(`
36
- `)}`,entityName:o,propertyName:s,propertyPath:f,actualValue:g,expectedValue:`A single reference to ${u.range??"an entity"} OR a YAML list`});continue}let R=await r.resolveEntityAsync(g,a);if(R)u.range&&(await this.validateRangeType(R,u.range,r,a)||p.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${u.range}, but '${g}' may not be a ${u.range}`,suggestion:`Ensure '${g}' is defined with appropriate type`,entityName:o,propertyName:s,propertyPath:f,actualValue:g,expectedValue:u.range}));else{let v=u.range??"entity";p.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${g}' which is not defined or imported`,suggestion:`Define '${g}' or import a namespace that contains it. Expected range: ${v}`,entityName:o,propertyName:s,propertyPath:f,actualValue:g,expectedValue:"Defined or imported entity"})}}else if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let g=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(c,o,g,i,r,n,a,p)}else if(Array.isArray(c))for(let g=0;g<c.length;g++){let R=c[g];if(typeof R=="string"&&R.trim().length>0){let v=R.trim(),A=await r.resolveEntityAsync(v,a);if(A){if(u.range&&!await this.validateRangeType(A,u.range,r,a)){let Q=t?`${t}.${s}[${g}]`:`${s}[${g}]`;p.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${u.range}, but '${v}' may not be a ${u.range}`,suggestion:`Ensure '${v}' is defined with appropriate type`,entityName:o,propertyName:`${s}[${g}]`,propertyPath:Q,actualValue:v,expectedValue:u.range})}}else{let re=u.range??"entity",Q=t?`${t}.${s}[${g}]`:`${s}[${g}]`;p.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${v}' which is not defined or imported`,suggestion:`Define '${v}' or import a namespace that contains it. Expected range: ${re}`,entityName:o,propertyName:`${s}[${g}]`,propertyPath:Q,actualValue:v,expectedValue:"Defined or imported entity"})}}else if(typeof R=="object"&&R!==null&&!Array.isArray(R)){let v=t?`${t}.${s}[${g}]`:`${s}[${g}]`;await this.scanEntityForObjectProperties(R,o,v,i,r,n,a,p)}}}if(typeof c=="object"&&c!==null&&!Array.isArray(c)&&!i.has(s)){let m=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(c,o,m,i,r,n,a,p)}else if(Array.isArray(c))for(let m=0;m<c.length;m++){let f=c[m];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let g=t?`${t}.${s}[${m}]`:`${s}[${m}]`;await this.scanEntityForObjectProperties(f,o,g,i,r,n,a,p)}}}}async validateRangeType(e,o,t,i){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(o))return!0;let n=e.entity.type;if(n){let a=[];if(Array.isArray(n))for(let p of n){let s=p?.toString();s&&s.trim().length>0&&a.push(s)}else{let p=n?.toString();p&&p.trim().length>0&&a.push(p)}for(let p of a){let s=p.includes(".")?p.split(".")[1]:p;if(s===o||o==="Property"&&(s==="DatatypeProperty"||s==="ObjectProperty"||s==="AnnotationProperty")||o==="Class"&&s==="Class"||await t.isSubclassOfAsync(p,o,i))return!0}}return!1}async buildPropertyMetadataAsync(e,o,t,i){let r=new Map;for(let[n,a]of i){let p=a.entity.type;if(p){let s=[];if(Array.isArray(p))for(let y of p){let u=y?.toString();u&&u.trim().length>0&&s.push(u)}else{let y=p?.toString();y&&y.trim().length>0&&s.push(y)}let c=!1,l="Property";for(let y of s){let u=y.includes(".")?y.split(".")[1]:y;if(u==="Property"||u==="DatatypeProperty"||u==="ObjectProperty"||u==="AnnotationProperty"){c=!0,l=y;break}}if(c){let y={propertyType:l},u=a.entity.range;if(u){let m=u?.toString();if(m&&m.trim().length>0){y.range=m;let f=await t.resolveEntityAsync(m,e);f&&(y.rangeUri=f.uri)}}r.set(n,y)}}}return r}};var X=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"PropertyDomain"}async validateAsync(e,o){let t=[],i=new Map;for(let[n,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=this.getPropertyValue(p,"type");(s==="DatatypeProperty"||s?.endsWith(".DatatypeProperty")||s==="ObjectProperty"||s?.endsWith(".ObjectProperty")||s==="AnnotationProperty"||s?.endsWith(".AnnotationProperty"))&&i.set(n,p)}let r=await this.buildCompleteClassHierarchyAsync(e,o);for(let[n,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=this.getPropertyValue(p,"type");if(!s||s==="Class"||s.endsWith(".Class")||s.endsWith("Property")||s==="AnnotationProperty")continue;this.validateEntityProperties(p,n,s,i,r,t)}return t}async buildCompleteClassHierarchyAsync(e,o){let t=new Map,i=new Set,r=async(a,p)=>{if(!i.has(p)){i.add(p);for(let[s,c]of Object.entries(a.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=c,y=this.getPropertyValue(l,"type");if(y==="Class"||y?.endsWith(".Class")){let u=l.subClassOf;if(u===void 0){for(let f of Object.keys(l))if(f.endsWith(".subClassOf")){u=l[f];break}}let m=k(u);m.length>0&&t.set(s,m)}}if(a.metadata.imports)for(let[s,c]of Object.entries(a.metadata.imports))for(let l of c)try{let y=await o.getHighestCompatibleVersionAsync(s,l);if(y){let u=`${s}/${l.packageName}@${l.version}`;await r(y,u)}}catch{}}},n=e.metadata.namespace_?.toString()??"unknown";return await r(e,n),t}validateEntityProperties(e,o,t,i,r,n){for(let[a,p]of Object.entries(e)){if(this.standardProperties.has(a))continue;let s=a,c=a.lastIndexOf(".");c>0&&c<a.length-1&&(s=a.substring(c+1));let l=i.get(s);if(!l)continue;let y=this.getPropertyValue(l,"domain");if(y){if(!this.isTypeCompatibleWithDomain(t,y,r)){let u=o.split(".")[0];n.push({ruleType:this.ruleName,severity:"Error",entityName:u,propertyName:o,actualValue:a,message:`Property '${a}' has domain '${y}' but is used on '${t}' at '${o}'`,suggestion:`Either:
35
+ ${v.slice(1).map(V=>` - ${V}`).join(`
36
+ `)}`,entityName:o,propertyName:s,propertyPath:f,actualValue:g,expectedValue:`A single reference to ${u.range??"an entity"} OR a YAML list`});continue}let R=await r.resolveEntityAsync(g,a);if(R)u.range&&(await this.validateRangeType(R,u.range,r,a)||p.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${u.range}, but '${g}' may not be a ${u.range}`,suggestion:`Ensure '${g}' is defined with appropriate type`,entityName:o,propertyName:s,propertyPath:f,actualValue:g,expectedValue:u.range}));else{let v=u.range??"entity";p.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${g}' which is not defined or imported`,suggestion:`Define '${g}' or import a namespace that contains it. Expected range: ${v}`,entityName:o,propertyName:s,propertyPath:f,actualValue:g,expectedValue:"Defined or imported entity"})}}else if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let g=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(c,o,g,n,r,i,a,p)}else if(Array.isArray(c))for(let g=0;g<c.length;g++){let R=c[g];if(typeof R=="string"&&R.trim().length>0){let v=R.trim(),V=await r.resolveEntityAsync(v,a);if(V){if(u.range&&!await this.validateRangeType(V,u.range,r,a)){let Q=t?`${t}.${s}[${g}]`:`${s}[${g}]`;p.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${u.range}, but '${v}' may not be a ${u.range}`,suggestion:`Ensure '${v}' is defined with appropriate type`,entityName:o,propertyName:`${s}[${g}]`,propertyPath:Q,actualValue:v,expectedValue:u.range})}}else{let re=u.range??"entity",Q=t?`${t}.${s}[${g}]`:`${s}[${g}]`;p.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${v}' which is not defined or imported`,suggestion:`Define '${v}' or import a namespace that contains it. Expected range: ${re}`,entityName:o,propertyName:`${s}[${g}]`,propertyPath:Q,actualValue:v,expectedValue:"Defined or imported entity"})}}else if(typeof R=="object"&&R!==null&&!Array.isArray(R)){let v=t?`${t}.${s}[${g}]`:`${s}[${g}]`;await this.scanEntityForObjectProperties(R,o,v,n,r,i,a,p)}}}if(typeof c=="object"&&c!==null&&!Array.isArray(c)&&!n.has(s)){let m=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(c,o,m,n,r,i,a,p)}else if(Array.isArray(c))for(let m=0;m<c.length;m++){let f=c[m];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let g=t?`${t}.${s}[${m}]`:`${s}[${m}]`;await this.scanEntityForObjectProperties(f,o,g,n,r,i,a,p)}}}}async validateRangeType(e,o,t,n){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(o))return!0;let i=e.entity.type;if(i){let a=[];if(Array.isArray(i))for(let p of i){let s=p?.toString();s&&s.trim().length>0&&a.push(s)}else{let p=i?.toString();p&&p.trim().length>0&&a.push(p)}for(let p of a){let s=p.includes(".")?p.split(".")[1]:p;if(s===o||o==="Property"&&(s==="DatatypeProperty"||s==="ObjectProperty"||s==="AnnotationProperty")||o==="Class"&&s==="Class"||await t.isSubclassOfAsync(p,o,n))return!0}}return!1}async buildPropertyMetadataAsync(e,o,t,n){let r=new Map;for(let[i,a]of n){let p=a.entity.type;if(p){let s=[];if(Array.isArray(p))for(let y of p){let u=y?.toString();u&&u.trim().length>0&&s.push(u)}else{let y=p?.toString();y&&y.trim().length>0&&s.push(y)}let c=!1,l="Property";for(let y of s){let u=y.includes(".")?y.split(".")[1]:y;if(u==="Property"||u==="DatatypeProperty"||u==="ObjectProperty"||u==="AnnotationProperty"){c=!0,l=y;break}}if(c){let y={propertyType:l},u=a.entity.range;if(u){let m=u?.toString();if(m&&m.trim().length>0){y.range=m;let f=await t.resolveEntityAsync(m,e);f&&(y.rangeUri=f.uri)}}r.set(i,y)}}}return r}};var X=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"PropertyDomain"}async validateAsync(e,o){let t=[],n=new Map;for(let[i,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=this.getPropertyValue(p,"type");(s==="DatatypeProperty"||s?.endsWith(".DatatypeProperty")||s==="ObjectProperty"||s?.endsWith(".ObjectProperty")||s==="AnnotationProperty"||s?.endsWith(".AnnotationProperty"))&&n.set(i,p)}let r=await this.buildCompleteClassHierarchyAsync(e,o);for(let[i,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a,s=this.getPropertyValue(p,"type");if(!s||s==="Class"||s.endsWith(".Class")||s.endsWith("Property")||s==="AnnotationProperty")continue;this.validateEntityProperties(p,i,s,n,r,t)}return t}async buildCompleteClassHierarchyAsync(e,o){let t=new Map,n=new Set,r=async(a,p)=>{if(!n.has(p)){n.add(p);for(let[s,c]of Object.entries(a.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=c,y=this.getPropertyValue(l,"type");if(y==="Class"||y?.endsWith(".Class")){let u=l.subClassOf;if(u===void 0){for(let f of Object.keys(l))if(f.endsWith(".subClassOf")){u=l[f];break}}let m=k(u);m.length>0&&t.set(s,m)}}if(a.metadata.imports)for(let[s,c]of Object.entries(a.metadata.imports))for(let l of c)try{let y=await o.getHighestCompatibleVersionAsync(s,l);if(y){let u=`${s}/${l.packageName}@${l.version}`;await r(y,u)}}catch{}}},i=e.metadata.namespace_?.toString()??"unknown";return await r(e,i),t}validateEntityProperties(e,o,t,n,r,i){for(let[a,p]of Object.entries(e)){if(this.standardProperties.has(a))continue;let s=a,c=a.lastIndexOf(".");c>0&&c<a.length-1&&(s=a.substring(c+1));let l=n.get(s);if(!l)continue;let y=this.getPropertyValue(l,"domain");if(y){if(!this.isTypeCompatibleWithDomain(t,y,r)){let u=o.split(".")[0];i.push({ruleType:this.ruleName,severity:"Error",entityName:u,propertyName:o,actualValue:a,message:`Property '${a}' has domain '${y}' but is used on '${t}' at '${o}'`,suggestion:`Either:
37
37
  1. Use this property only on '${y}' instances
38
38
  2. Change the property domain to include '${t}'
39
- 3. Create a different property for '${t}'`,expectedValue:`Property used on ${y} or its subclasses`})}if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=p,m=this.getPropertyValue(u,"type");if(m){let f=`${o}.${a}`;this.validateEntityProperties(u,f,m,i,r,n)}else{let f=this.getPropertyValue(l,"range");if(f){let g=`${o}.${a}`;this.validateEntityProperties(u,g,f,i,r,n)}}}else if(Array.isArray(p))for(let u=0;u<p.length;u++){let m=p[u];if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let f=m,g=this.getPropertyValue(f,"type");if(g){let R=`${o}.${a}[${u}]`;this.validateEntityProperties(f,R,g,i,r,n)}else{let R=this.getPropertyValue(l,"range");if(R){let v=`${o}.${a}[${u}]`;this.validateEntityProperties(f,v,R,i,r,n)}}}}}}}isTypeCompatibleWithDomain(e,o,t){if(e===o)return!0;let i=new Set,r=[e];for(;r.length>0;){let n=r.shift();if(i.has(n))continue;i.add(n);let a=t.get(n);if(a)for(let p of a){if(p===o)return!0;r.push(p)}}return!1}getPropertyValue(e,o){if(o in e){let t=e[o];return this.extractFirstValue(t)}for(let t of Object.keys(e))if(t.endsWith(`.${o}`)){let i=e[t];return this.extractFirstValue(i)}}extractFirstValue(e){if(Array.isArray(e)){let o=[];for(let t of e)o.push(t?.toString()??"");return o.length>0?o[0]:void 0}return e?.toString()}};var B=class{get ruleName(){return"PropertyValueType"}async validateAsync(e,o){let t=[],i=new Map;for(let[r,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,p=this.getPropertyValue(a,"type");(p==="DatatypeProperty"||p==="ObjectProperty")&&i.set(r,a)}for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let a=n,p=this.getPropertyValue(a,"type");if(!(!p||p==="Class"||p.endsWith("Property")||p==="AnnotationProperty"))for(let[s,c]of Object.entries(a)){if(s==="type"||s==="label"||s==="comment")continue;let l=s,y=s.lastIndexOf(".");y>0&&y<s.length-1&&(l=s.substring(y+1));let u=i.get(l);if(!u)continue;let m=this.getPropertyValue(u,"type"),f=this.getPropertyValue(u,"range");if(m==="DatatypeProperty"){if(typeof c=="object"&&c!==null&&!Array.isArray(c)||Array.isArray(c))t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:s,message:`Property '${s}' is a DatatypeProperty with range '${f}' but instance '${r}' has a complex object value`,suggestion:`Either:
39
+ 3. Create a different property for '${t}'`,expectedValue:`Property used on ${y} or its subclasses`})}if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=p,m=this.getPropertyValue(u,"type");if(m){let f=`${o}.${a}`;this.validateEntityProperties(u,f,m,n,r,i)}else{let f=this.getPropertyValue(l,"range");if(f){let g=`${o}.${a}`;this.validateEntityProperties(u,g,f,n,r,i)}}}else if(Array.isArray(p))for(let u=0;u<p.length;u++){let m=p[u];if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let f=m,g=this.getPropertyValue(f,"type");if(g){let R=`${o}.${a}[${u}]`;this.validateEntityProperties(f,R,g,n,r,i)}else{let R=this.getPropertyValue(l,"range");if(R){let v=`${o}.${a}[${u}]`;this.validateEntityProperties(f,v,R,n,r,i)}}}}}}}isTypeCompatibleWithDomain(e,o,t){if(e===o)return!0;let n=new Set,r=[e];for(;r.length>0;){let i=r.shift();if(n.has(i))continue;n.add(i);let a=t.get(i);if(a)for(let p of a){if(p===o)return!0;r.push(p)}}return!1}getPropertyValue(e,o){if(o in e){let t=e[o];return this.extractFirstValue(t)}for(let t of Object.keys(e))if(t.endsWith(`.${o}`)){let n=e[t];return this.extractFirstValue(n)}}extractFirstValue(e){if(Array.isArray(e)){let o=[];for(let t of e)o.push(t?.toString()??"");return o.length>0?o[0]:void 0}return e?.toString()}};var z=class{get ruleName(){return"PropertyValueType"}async validateAsync(e,o){let t=[],n=new Map;for(let[r,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i,p=this.getPropertyValue(a,"type");(p==="DatatypeProperty"||p==="ObjectProperty")&&n.set(r,a)}for(let[r,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i,p=this.getPropertyValue(a,"type");if(!(!p||p==="Class"||p.endsWith("Property")||p==="AnnotationProperty"))for(let[s,c]of Object.entries(a)){if(s==="type"||s==="label"||s==="comment")continue;let l=s,y=s.lastIndexOf(".");y>0&&y<s.length-1&&(l=s.substring(y+1));let u=n.get(l);if(!u)continue;let m=this.getPropertyValue(u,"type"),f=this.getPropertyValue(u,"range");if(m==="DatatypeProperty"){if(typeof c=="object"&&c!==null&&!Array.isArray(c)||Array.isArray(c))t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:s,message:`Property '${s}' is a DatatypeProperty with range '${f}' but instance '${r}' has a complex object value`,suggestion:`Either:
40
40
  1. Create a class for this data and change '${s}' to an ObjectProperty
41
41
  2. Store as a JSON string to keep it as DatatypeProperty
42
- 3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${f}'`});else if(!this.validateDatatypeValue(f,c)){let g={ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:s,message:`Property '${s}' expects type '${f}' but instance '${r}' has value of type '${this.getValueTypeName(c)}'`,suggestion:`Provide a value of type '${f}'`,toString:()=>""};f&&(g.expectedValue=f),t.push(g)}}else if(m==="ObjectProperty")if(Array.isArray(c))for(let g=0;g<c.length;g++){let R=c[g];typeof R!="string"&&(typeof R!="object"||R===null||Array.isArray(R))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:`${s}[${g}]`,message:`ObjectProperty '${s}' array item ${g} in instance '${r}' has invalid type '${this.getValueTypeName(R)}'`,suggestion:"Array items must be references (strings) or embedded objects (dictionaries)",expectedValue:"string or object"})}else typeof c!="string"&&(typeof c!="object"||c===null||Array.isArray(c))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:s,message:`ObjectProperty '${s}' in instance '${r}' has invalid value type '${this.getValueTypeName(c)}'`,suggestion:"Value must be a reference (string), embedded object (dictionary), or array of these",expectedValue:`Reference to ${f} or embedded ${f} object`})}}return t}validateDatatypeValue(e,o){switch(e?.toLowerCase()){case"string":return typeof o=="string";case"integer":case"int":return typeof o=="number"&&Number.isInteger(o);case"decimal":return typeof o=="number";case"boolean":return typeof o=="boolean";case"float":case"double":return typeof o=="number";default:return!0}}getValueTypeName(e){return typeof e=="string"?"string":typeof e=="number"?Number.isInteger(e)?"integer":"decimal":typeof e=="boolean"?"boolean":Array.isArray(e)?"array":typeof e=="object"&&e!==null?"object":e===null?"null":e===void 0?"undefined":typeof e}getPropertyValue(e,o){if(o in e){let t=e[o];if(Array.isArray(t)){let i=[];for(let r of t)i.push(r?.toString()??"");return i.length>0?i[0]:void 0}return t?.toString()}}};var z=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"ClassDefinition"}async validateAsync(e,o){let t=[],i=new Map,r=new Set;for(let[a,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let c=p.type;if(c)if(Array.isArray(c))for(let l of c){let y=l?.toString();if(y==="Class"||y&&y.endsWith(".Class")){r.add(a);break}}else{let l=c?.toString();(l==="Class"||l&&l.endsWith(".Class"))&&r.add(a)}}for(let[a,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let s=p,c=s.type;if(c)if(Array.isArray(c)){let l=!1;for(let y of c){let u=y?.toString();if(u&&this.isDefinitionType(u)){l=!0;break}}if(!l)for(let y of c){let u=y?.toString();u&&u.trim().length>0&&(i.has(u)||i.set(u,[]),i.get(u).push(a))}}else{let l=c?.toString();l&&l.trim().length>0&&(this.isDefinitionType(l)||(i.has(l)||i.set(l,[]),i.get(l).push(a)))}this.checkNestedTypes(s,a,i,a)}let n=new V(o);for(let[a,p]of i){if(this.builtInClasses.has(a)||r.has(a))continue;let s=await n.resolveEntityAsync(a,e);if(!(s&&this.isClassEntity(s.entity))){let l=Array.from(new Set(p)).sort();for(let y of l)t.push({ruleType:this.ruleName,severity:"Error",message:`Class '${a}' is not defined or imported`,suggestion:`Define '${a}' as a Class in this document, or import a namespace that contains it`,entityName:y,propertyName:"type",actualValue:a,expectedValue:"Defined or imported class"})}}return t}checkNestedTypes(e,o,t,i){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=e,n=r.type;if(n){let a=new Set(["Class","DatatypeProperty","ObjectProperty","AnnotationProperty"]);if(Array.isArray(n))for(let p of n){let s=p?.toString();s&&s.trim().length>0&&!a.has(s)&&(t.has(s)||t.set(s,[]),t.get(s).push(i))}else{let p=n?.toString();p&&p.trim().length>0&&!a.has(p)&&(t.has(p)||t.set(p,[]),t.get(p).push(i))}}for(let[a,p]of Object.entries(r))if(a!=="type"){let s=`${i}.${a}`;this.checkNestedTypes(p,o,t,s)}}else if(Array.isArray(e))for(let r=0;r<e.length;r++){let n=`${i}[${r}]`;this.checkNestedTypes(e[r],o,t,n)}}isClassEntity(e){if(!e)return!1;let o=e.type;if(!o)return!1;if(Array.isArray(o))for(let t of o){let i=t?.toString();if(i==="Class"||i&&i.endsWith(".Class"))return!0}else{let t=o?.toString();if(t==="Class"||t&&t.endsWith(".Class"))return!0}return!1}isDefinitionType(e){return!e||e.trim().length===0?!1:new Set(["Class","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(e)?!0:e.endsWith(".Class")||e.endsWith(".Property")||e.endsWith(".DatatypeProperty")||e.endsWith(".ObjectProperty")||e.endsWith(".AnnotationProperty")}};var te=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new G,this.documentRules=[new I,new D,new O,new $],this.repositoryRules=[new w,new E,new S,new j,new N,new K,new C,new x,new T,new _,new M,new W,new L,new H,new F,new U,new q,new X,new B,new z]}async validateAsync(e,o){let t=new P;for(let i of this.documentRules)try{let r=i.validate(e);this.addErrorsToResult(t,r)}catch(r){let n=new h;n.ruleType=i.ruleName,n.severity="Error",n.message=`Validation rule '${i.ruleName}' failed: ${r instanceof Error?r.message:String(r)}`,t.errors.push(n)}if(o){let i=[];for(let r of this.repositoryRules)try{let n=await r.validateAsync(e,o);this.addErrorsToResult(t,n)}catch(n){let a=n instanceof Error?n.message:String(n);i.push({ruleName:r.ruleName,cause:a})}if(i.length>0){let r=new Map;for(let{ruleName:n,cause:a}of i){let p=r.get(a);p?p.push(n):r.set(a,[n])}for(let[n,a]of r){let p=new h;p.ruleType=a[0],p.severity="Error",a.length===1?p.message=`Validation rule '${a[0]}' failed: ${n}`:p.message=`${n} (affects ${a.length} rules: ${a.join(", ")})`,t.errors.push(p)}}}return t.isValid=t.errors.length===0,t}async validateYamlAsync(e,o){let t=this.parser.parseWithErrors(e);if(!t.isValid){let i=new P;i.isValid=!1;for(let r of t.errors){let n=new h;n.ruleType="ParseError",n.severity="Error",n.lineNumber=r.line,n.column=r.column,n.message=r.message,r.keyName&&(n.entityName=r.keyName),r.errorType==="DuplicateKey"&&(n.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),i.errors.push(n)}return i}return await this.validateAsync(t.document,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let o=this.documentRules.findIndex(t=>t instanceof e);o>=0&&this.documentRules.splice(o,1)}removeRepositoryRule(e){let o=this.repositoryRules.findIndex(t=>t instanceof e);o>=0&&this.repositoryRules.splice(o,1)}addErrorsToResult(e,o){for(let t of o)t.severity==="Error"?e.errors.push(t):this.includeWarnings&&e.warnings.push(t)}};export{H as AmbiguousReferenceRule,z as ClassDefinitionRule,N as ClassHierarchyCycleRule,W as DefinitionPropertyReferenceRule,w as EmbeddedKanonakTypeRule,E as ImportExistenceRule,M as InstancePropertyReferenceRule,te as KanonakObjectValidator,_ as NamespaceImportCycleRule,I as NamespacePrefixRule,U as ObjectPropertyImportRule,q as ObjectPropertyValueValidationRule,h as OntologyValidationError,P as OntologyValidationResult,X as PropertyDomainRule,K as PropertyHierarchyCycleRule,F as PropertyRangeReferenceRule,C as PropertyRangeRequiredRule,O as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,D as ResourceNamingRule,x as SubClassOfReferenceRule,T as SubPropertyOfReferenceRule,$ as SubjectKanonakTypeRequiredRule,j as TypeAmbiguityRule,S as UnresolvedReferenceRule,ee as ValidationContext,b as ValidationSeverity,L as XsdImportRule};
42
+ 3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${f}'`});else if(!this.validateDatatypeValue(f,c)){let g={ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:s,message:`Property '${s}' expects type '${f}' but instance '${r}' has value of type '${this.getValueTypeName(c)}'`,suggestion:`Provide a value of type '${f}'`,toString:()=>""};f&&(g.expectedValue=f),t.push(g)}}else if(m==="ObjectProperty")if(Array.isArray(c))for(let g=0;g<c.length;g++){let R=c[g];typeof R!="string"&&(typeof R!="object"||R===null||Array.isArray(R))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:`${s}[${g}]`,message:`ObjectProperty '${s}' array item ${g} in instance '${r}' has invalid type '${this.getValueTypeName(R)}'`,suggestion:"Array items must be references (strings) or embedded objects (dictionaries)",expectedValue:"string or object"})}else typeof c!="string"&&(typeof c!="object"||c===null||Array.isArray(c))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:s,message:`ObjectProperty '${s}' in instance '${r}' has invalid value type '${this.getValueTypeName(c)}'`,suggestion:"Value must be a reference (string), embedded object (dictionary), or array of these",expectedValue:`Reference to ${f} or embedded ${f} object`})}}return t}validateDatatypeValue(e,o){switch(e?.toLowerCase()){case"string":return typeof o=="string";case"integer":case"int":return typeof o=="number"&&Number.isInteger(o);case"decimal":return typeof o=="number";case"boolean":return typeof o=="boolean";case"float":case"double":return typeof o=="number";default:return!0}}getValueTypeName(e){return typeof e=="string"?"string":typeof e=="number"?Number.isInteger(e)?"integer":"decimal":typeof e=="boolean"?"boolean":Array.isArray(e)?"array":typeof e=="object"&&e!==null?"object":e===null?"null":e===void 0?"undefined":typeof e}getPropertyValue(e,o){if(o in e){let t=e[o];if(Array.isArray(t)){let n=[];for(let r of t)n.push(r?.toString()??"");return n.length>0?n[0]:void 0}return t?.toString()}}};var B=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"ClassDefinition"}async validateAsync(e,o){let t=[],n=new Map,r=new Set;for(let[a,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let c=p.type;if(c)if(Array.isArray(c))for(let l of c){let y=l?.toString();if(y==="Class"||y&&y.endsWith(".Class")){r.add(a);break}}else{let l=c?.toString();(l==="Class"||l&&l.endsWith(".Class"))&&r.add(a)}}for(let[a,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let s=p,c=s.type;if(c)if(Array.isArray(c)){let l=!1;for(let y of c){let u=y?.toString();if(u&&this.isDefinitionType(u)){l=!0;break}}if(!l)for(let y of c){let u=y?.toString();u&&u.trim().length>0&&(n.has(u)||n.set(u,[]),n.get(u).push(a))}}else{let l=c?.toString();l&&l.trim().length>0&&(this.isDefinitionType(l)||(n.has(l)||n.set(l,[]),n.get(l).push(a)))}this.checkNestedTypes(s,a,n,a)}let i=new A(o);for(let[a,p]of n){if(this.builtInClasses.has(a)||r.has(a))continue;let s=await i.resolveEntityAsync(a,e);if(!(s&&this.isClassEntity(s.entity))){let l=Array.from(new Set(p)).sort();for(let y of l)t.push({ruleType:this.ruleName,severity:"Error",message:`Class '${a}' is not defined or imported`,suggestion:`Define '${a}' as a Class in this document, or import a namespace that contains it`,entityName:y,propertyName:"type",actualValue:a,expectedValue:"Defined or imported class"})}}return t}checkNestedTypes(e,o,t,n){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=e,i=r.type;if(i){let a=new Set(["Class","DatatypeProperty","ObjectProperty","AnnotationProperty"]);if(Array.isArray(i))for(let p of i){let s=p?.toString();s&&s.trim().length>0&&!a.has(s)&&(t.has(s)||t.set(s,[]),t.get(s).push(n))}else{let p=i?.toString();p&&p.trim().length>0&&!a.has(p)&&(t.has(p)||t.set(p,[]),t.get(p).push(n))}}for(let[a,p]of Object.entries(r))if(a!=="type"){let s=`${n}.${a}`;this.checkNestedTypes(p,o,t,s)}}else if(Array.isArray(e))for(let r=0;r<e.length;r++){let i=`${n}[${r}]`;this.checkNestedTypes(e[r],o,t,i)}}isClassEntity(e){if(!e)return!1;let o=e.type;if(!o)return!1;if(Array.isArray(o))for(let t of o){let n=t?.toString();if(n==="Class"||n&&n.endsWith(".Class"))return!0}else{let t=o?.toString();if(t==="Class"||t&&t.endsWith(".Class"))return!0}return!1}isDefinitionType(e){return!e||e.trim().length===0?!1:new Set(["Class","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(e)?!0:e.endsWith(".Class")||e.endsWith(".Property")||e.endsWith(".DatatypeProperty")||e.endsWith(".ObjectProperty")||e.endsWith(".AnnotationProperty")}};var te=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new Z,this.documentRules=[new I,new D,new O,new $],this.repositoryRules=[new w,new E,new S,new j,new N,new K,new C,new x,new T,new _,new M,new L,new W,new H,new U,new F,new q,new X,new z,new B]}async validateAsync(e,o){let t=new P;for(let n of this.documentRules)try{let r=n.validate(e);this.addErrorsToResult(t,r)}catch(r){let i=new h;i.ruleType=n.ruleName,i.severity="Error",i.message=`Validation rule '${n.ruleName}' failed: ${r instanceof Error?r.message:String(r)}`,t.errors.push(i)}if(o){let n=[];for(let r of this.repositoryRules)try{let i=await r.validateAsync(e,o);this.addErrorsToResult(t,i)}catch(i){let a=i instanceof Error?i.message:String(i);n.push({ruleName:r.ruleName,cause:a})}if(n.length>0){let r=new Map;for(let{ruleName:i,cause:a}of n){let p=r.get(a);p?p.push(i):r.set(a,[i])}for(let[i,a]of r){let p=new h;p.ruleType=a[0],p.severity="Error",a.length===1?p.message=`Validation rule '${a[0]}' failed: ${i}`:p.message=`${i} (affects ${a.length} rules: ${a.join(", ")})`,t.errors.push(p)}}}return t.isValid=t.errors.length===0,t}async validateYamlAsync(e,o){let t=this.parser.parseWithErrors(e);if(!t.isValid){let n=new P;n.isValid=!1;for(let r of t.errors){let i=new h;i.ruleType="ParseError",i.severity="Error",i.lineNumber=r.line,i.column=r.column,i.message=r.message,r.keyName&&(i.entityName=r.keyName),r.errorType==="DuplicateKey"&&(i.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),n.errors.push(i)}return n}return await this.validateAsync(t.document,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let o=this.documentRules.findIndex(t=>t instanceof e);o>=0&&this.documentRules.splice(o,1)}removeRepositoryRule(e){let o=this.repositoryRules.findIndex(t=>t instanceof e);o>=0&&this.repositoryRules.splice(o,1)}addErrorsToResult(e,o){for(let t of o)t.severity==="Error"?e.errors.push(t):this.includeWarnings&&e.warnings.push(t)}};export{H as AmbiguousReferenceRule,B as ClassDefinitionRule,N as ClassHierarchyCycleRule,L as DefinitionPropertyReferenceRule,w as EmbeddedKanonakTypeRule,E as ImportExistenceRule,M as InstancePropertyReferenceRule,te as KanonakObjectValidator,_ as NamespaceImportCycleRule,I as NamespacePrefixRule,F as ObjectPropertyImportRule,q as ObjectPropertyValueValidationRule,h as OntologyValidationError,P as OntologyValidationResult,X as PropertyDomainRule,K as PropertyHierarchyCycleRule,U as PropertyRangeReferenceRule,C as PropertyRangeRequiredRule,O as PropertyTypeSpecificityRule,z as PropertyValueTypeRule,D as ResourceNamingRule,x as SubClassOfReferenceRule,T as SubPropertyOfReferenceRule,$ as SubjectKanonakTypeRequiredRule,j as TypeAmbiguityRule,S as UnresolvedReferenceRule,ee as ValidationContext,b as ValidationSeverity,W as XsdImportRule};
@@ -5,6 +5,15 @@ export declare class ResourceNamingRule implements IDocumentValidationRule {
5
5
  private static readonly RESERVED_WORDS;
6
6
  private static readonly VALID_PROPERTIES;
7
7
  private static readonly VALID_NAME_PATTERN;
8
+ /**
9
+ * Open-world augmentation: an entity name of the form
10
+ * `alias.localName` references an entity defined in another
11
+ * package (resolved through this document's imports). Both
12
+ * segments must be valid local names. The parser's open-world
13
+ * merge collapses these into the canonical subject; the validator
14
+ * accepts the dotted form here.
15
+ */
16
+ private static readonly VALID_AUGMENTATION_PATTERN;
8
17
  private static readonly VALID_PROPERTY_NAME_PATTERN;
9
18
  readonly ruleName = "ResourceNaming";
10
19
  validate(document: KanonakDocument): OntologyValidationError[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.7.0",
3
+ "version": "3.8.0",
4
4
  "description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -105,7 +105,7 @@
105
105
  "yaml-parser"
106
106
  ],
107
107
  "dependencies": {
108
- "@kanonak-protocol/types": "^3.7.0",
108
+ "@kanonak-protocol/types": "^3.8.0",
109
109
  "ignore": "^7.0.5",
110
110
  "js-yaml": "^4.1.0",
111
111
  "yaml": "^2.7.0"