@kanonak-protocol/sdk 1.4.0 → 1.6.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 +2 -2
- package/dist/index.js +2 -2
- package/dist/parsing/index.js +1 -1
- package/dist/validation/index.js +9 -9
- package/package.json +2 -2
package/dist/browser.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Vt=Object.defineProperty;var St=(l,e)=>()=>(l&&(e=l(l=0)),e);var Kt=(l,e)=>{for(var t in e)Vt(l,t,{get:e[t],enumerable:!0})};var pt={};Kt(pt,{KanonakUri:()=>V});var V,De=St(()=>{"use strict";V=class l{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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as Ee from"js-yaml";var O=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=Ee.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),Ee.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 p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},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 p=i[1].trim(),u=i[2],y=this.parseVersion(i[3].trim()),m=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:y,alias:m,minVersion:y,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:y.toString()};return m&&(g.alias=m),g},toString:()=>`${p} ${u} ${y.toString()} as ${m}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),u=c[2],y=this.parseVersion(c[3].trim()),m=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:m,version:y,alias:void 0,minVersion:y,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:y.toString()}),toString:()=>`${p} ${u} ${y.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 L=class extends U{statement=[]};var F=class extends L{namespace;name;icon};var N=class extends L{};De();var I=class l extends U{subject;static parse(e){let t=new l;return t.subject=V.parse(e),t}};var S=class{predicate;object};var E=class extends S{};var X=class l extends E{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var Y=class l extends E{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var J=class extends E{};var Z=class l extends S{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=I.parse(t),r}};var B=class extends S{};var W=class extends S{};De();function D(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var $=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 V(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 p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let y=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...y),this.logger?.debug?.(`Added ${y.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(u){let y=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${i}/${p.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 p=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 V(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),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,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let y=await this.repository.getHighestCompatibleVersionAsync(c,u);if(y){this.logger?.debug?.(`Successfully loaded import: ${y.metadata?.namespace_?.toString()}`);let m=await this.buildEntityIndexAsyncInternal(y,t,s),f=0;for(let[d,g]of m.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 ${y.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(y){let m=y;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:y})}}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=D(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=D(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var H=class l{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"&&l.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 l.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 je=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new $(e),o=new H(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new F;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}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 p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}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=o.getPropertyTypeClassification(i),p=a.range?.toString(),u;if(c==="ObjectProperty")u="ObjectProperty";else if(c==="DatatypeProperty")u="DatatypeProperty";else{let m=p&&p.includes(".")?p.substring(p.lastIndexOf(".")+1):p??"";(p?o.isKnownXsdDatatypeName(p):!1)||m==="Literal"?u="DatatypeProperty":u="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:u,range:p,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(typeof t=="string")return X.parse(e,t);if(typeof t=="number")return Y.parse(e,t);if(typeof t=="boolean"){let n=new J;return n.predicate=I.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 Z;return i.predicate=I.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new N;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new B;return p.predicate=I.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new N;u.statement=await this.parseStatements(p,n,o,s,{}),i.push(u)}else if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&i.push(u)}if(i.length>0){let p=new W;return p.predicate=I.parse(e),p.object=i,p}let c=new B;return c.predicate=I.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,n,o);p&&a.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new N;p.statement=await this.parseStatements(c,n,o,s,{}),a.push(p)}let i=new W;return i.predicate=I.parse(e),i.object=a,i}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new I;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(De(),pt)),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("."),p=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[y,m]of Object.entries(t.metadata.imports))for(let f of m)if((f.alias??f.packageName)===p){let g=new I;return g.subject=new s(y,f.packageName,u,f.version),g}}}let i=new I;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 F&&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 F&&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 O().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,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof X)return[e.predicate.subject.name,e.object];if(e instanceof Y)return[e.predicate.subject.name,e.object];if(e instanceof J)return[e.predicate.subject.name,e.object];if(e instanceof Z)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof W){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 I?t.push(r.subject.name):r instanceof N&&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 Ce=class{propertyUri;propertyType;range;isImported;definedInNamespace};var Ot=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),lt={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 C(l){let e=l;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=lt[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=lt[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function _(l,e){return Ot.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return C(e)}static isCoreOntologyType(e){return _(e.publisher,e.package_)}static isClassType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=C(e);return!t||!_(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=C(e);return!t||!_(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(l.isSchemaDefinitionType(e))return!1;let r=C(e);return r?t.has(r.name):!1}};var Qe=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(Qe||{}),et=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(et||{}),xe=class{static async buildFromRepository(e){let r=await new je().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,i=new Set,c=new Map;for(let u of r){let y=u;y.name&&(w.isClassType(y)&&a.add(y.name),(w.isObjectPropertyType(y)||w.isGenericPropertyType(y))&&i.add(y.name))}for(let u of n)for(let[y,m]of Object.entries(u.body))i.has(y)&&m?.range&&typeof m.range=="string"&&c.set(y,m.range);let p=new Map;for(let u of r){let y=u;y.name&&p.set(y.name,y)}for(let u of n){let y=u.metadata.namespace_,m=y?`${y.publisher}/${y.package_}`:"",f=y?.version?`${y.version.major}.${y.version.minor}.${y.version.patch}`:"",d=ut(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let k=p.get(g),R="Unknown";if(k){let j=k;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=m&&f?`${m}/${g}@${f}`:g,A={};for(let[j,Je]of Object.entries(h))j!=="type"&&(typeof Je!="object"||Je===null)&&(A[j]=Je);o.push({id:v,label:h.label??g,type:R,namespace:m,properties:A}),yt(v,h,R,a,i,s,m,f,d),Ze(v,h,i,c,o,s,m,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,p=ut(e);for(let[m,f]of Object.entries(e.body)){let d=f?.type;d&&(Ct(d,p)&&a.add(m),xt(d,p)&&(i.add(m),f.range&&typeof f.range=="string"&&c.set(m,f.range)))}for(let[m,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=Tt(d,m,a,p),h=s&&o?`${s}/${m}@${o}`:m,k={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(k[R]=v);t.push({id:h,label:f.label??m,type:g,namespace:s,properties:k}),yt(h,f,g,a,i,r,s,o,p),Ze(h,f,i,c,t,r,s,o,p)}let u=new Set(t.map(m=>m.id)),y=r.filter(m=>u.has(m.source)&&u.has(m.target));return{nodes:t,edges:y}}};function ut(l,e){let t=new Map;if(l.metadata?.imports)for(let[r,n]of Object.entries(l.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 mt={"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"},Et=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function tt(l,e){if(l.includes(".")){let t=l.indexOf("."),r=l.substring(0,t),n=l.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function Ct(l,e){let t=tt(l,e);return t?mt[t]==="Class":!1}function xt(l,e){let t=tt(l,e);return t?Et.has(t):!1}function Tt(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=tt(l,r);if(n){let s=mt[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=l.split(".").pop()??l;return t.has(o)?"Instance":"Unknown"}var ft=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function yt(l,e,t,r,n,o,s,a,i){let c=e.type,p=e.subClassOf;if(p){let f=Array.isArray(p)?p:[p];for(let d of f)typeof d=="string"&&o.push({source:l,target:G(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:l,target:G(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:G(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(ft.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&Nt(h)&&o.push({source:l,target:G(h,s,a,i),type:"propertyValue",label:f,propertyId:G(f,s,a,i)})}let y=t==="ObjectProperty"||t==="DatatypeProperty",m=e.domain&&e.range;if((y||m)&&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:G(f,s,a,i),target:G(d,s,a,i),type:"objectRelationship",label:e.label??l.split("/").pop()??"",propertyId:l})}}function Ze(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(ft.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,y=`${l}/${c}`,m=r.get(c),f=m?m.split(".").pop()??m:"Unknown",d={};for(let[h,k]of Object.entries(u))(typeof k!="object"||k===null)&&(d[h]=k);n.push({id:y,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:l,target:y,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),m&&o.push({source:y,target:G(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),Ze(y,u,t,r,n,o,s,a,i)}}function Nt(l){return!(!l||l.includes(" ")||l.includes(`
|
|
2
|
-
`)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function G(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.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}/${l}@${t}`:l}var Q=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 b=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 Te=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ee=class l{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&&l.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new b;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 te=class l{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=[];for(let[
|
|
1
|
+
var Vt=Object.defineProperty;var St=(l,e)=>()=>(l&&(e=l(l=0)),e);var Kt=(l,e)=>{for(var t in e)Vt(l,t,{get:e[t],enumerable:!0})};var pt={};Kt(pt,{KanonakUri:()=>V});var V,De=St(()=>{"use strict";V=class l{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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as Ee from"js-yaml";var O=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=Ee.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),Ee.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 p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},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 p=i[1].trim(),u=i[2],y=this.parseVersion(i[3].trim()),m=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:y,alias:m,minVersion:y,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:y.toString()};return m&&(g.alias=m),g},toString:()=>`${p} ${u} ${y.toString()} as ${m}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),u=c[2],y=this.parseVersion(c[3].trim()),m=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:m,version:y,alias:void 0,minVersion:y,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:y.toString()}),toString:()=>`${p} ${u} ${y.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 L=class extends U{statement=[]};var F=class extends L{namespace;name;icon};var N=class extends L{};De();var I=class l extends U{subject;static parse(e){let t=new l;return t.subject=V.parse(e),t}};var S=class{predicate;object};var E=class extends S{};var X=class l extends E{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var Y=class l extends E{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var J=class extends E{};var Z=class l extends S{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=I.parse(t),r}};var B=class extends S{};var W=class extends S{};De();function D(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var $=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 V(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 p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let y=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...y),this.logger?.debug?.(`Added ${y.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(u){let y=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${i}/${p.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 p=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 V(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),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,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let y=await this.repository.getHighestCompatibleVersionAsync(c,u);if(y){this.logger?.debug?.(`Successfully loaded import: ${y.metadata?.namespace_?.toString()}`);let m=await this.buildEntityIndexAsyncInternal(y,t,s),f=0;for(let[d,g]of m.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 ${y.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(y){let m=y;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:y})}}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=D(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=D(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var H=class l{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"&&l.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 l.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 je=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new $(e),o=new H(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new F;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}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 p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}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),y=a.range?.toString(),m;if(u==="ObjectProperty")m="ObjectProperty";else if(u==="DatatypeProperty")m="DatatypeProperty";else{let d=y&&y.includes(".")?y.substring(y.lastIndexOf(".")+1):y??"";(y?o.isKnownXsdDatatypeName(y):!1)||d==="Literal"?m="DatatypeProperty":m="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:m,range:y,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(typeof t=="string")return X.parse(e,t);if(typeof t=="number")return Y.parse(e,t);if(typeof t=="boolean"){let n=new J;return n.predicate=I.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 Z;return i.predicate=I.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new N;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new B;return p.predicate=I.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new N;u.statement=await this.parseStatements(p,n,o,s,{}),i.push(u)}else if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&i.push(u)}if(i.length>0){let p=new W;return p.predicate=I.parse(e),p.object=i,p}let c=new B;return c.predicate=I.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,n,o);p&&a.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new N;p.statement=await this.parseStatements(c,n,o,s,{}),a.push(p)}let i=new W;return i.predicate=I.parse(e),i.object=a,i}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new I;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(De(),pt)),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("."),p=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[y,m]of Object.entries(t.metadata.imports))for(let f of m)if((f.alias??f.packageName)===p){let g=new I;return g.subject=new s(y,f.packageName,u,f.version),g}}}let i=new I;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 F&&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 F&&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 O().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,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof X)return[e.predicate.subject.name,e.object];if(e instanceof Y)return[e.predicate.subject.name,e.object];if(e instanceof J)return[e.predicate.subject.name,e.object];if(e instanceof Z)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof W){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 I?t.push(r.subject.name):r instanceof N&&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 Ce=class{propertyUri;propertyType;range;isImported;definedInNamespace};var Ot=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),lt={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 C(l){let e=l;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=lt[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=lt[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function _(l,e){return Ot.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return C(e)}static isCoreOntologyType(e){return _(e.publisher,e.package_)}static isClassType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=C(e);return t?_(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=C(e);return!t||!_(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=C(e);return!t||!_(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(l.isSchemaDefinitionType(e))return!1;let r=C(e);return r?t.has(r.name):!1}};var Qe=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(Qe||{}),et=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(et||{}),xe=class{static async buildFromRepository(e){let r=await new je().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,i=new Set,c=new Map;for(let u of r){let y=u;y.name&&(w.isClassType(y)&&a.add(y.name),(w.isObjectPropertyType(y)||w.isGenericPropertyType(y))&&i.add(y.name))}for(let u of n)for(let[y,m]of Object.entries(u.body))i.has(y)&&m?.range&&typeof m.range=="string"&&c.set(y,m.range);let p=new Map;for(let u of r){let y=u;y.name&&p.set(y.name,y)}for(let u of n){let y=u.metadata.namespace_,m=y?`${y.publisher}/${y.package_}`:"",f=y?.version?`${y.version.major}.${y.version.minor}.${y.version.patch}`:"",d=ut(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let k=p.get(g),R="Unknown";if(k){let j=k;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=m&&f?`${m}/${g}@${f}`:g,A={};for(let[j,Je]of Object.entries(h))j!=="type"&&(typeof Je!="object"||Je===null)&&(A[j]=Je);o.push({id:v,label:h.label??g,type:R,namespace:m,properties:A}),yt(v,h,R,a,i,s,m,f,d),Ze(v,h,i,c,o,s,m,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,p=ut(e);for(let[m,f]of Object.entries(e.body)){let d=f?.type;d&&(Ct(d,p)&&a.add(m),xt(d,p)&&(i.add(m),f.range&&typeof f.range=="string"&&c.set(m,f.range)))}for(let[m,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=Tt(d,m,a,p),h=s&&o?`${s}/${m}@${o}`:m,k={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(k[R]=v);t.push({id:h,label:f.label??m,type:g,namespace:s,properties:k}),yt(h,f,g,a,i,r,s,o,p),Ze(h,f,i,c,t,r,s,o,p)}let u=new Set(t.map(m=>m.id)),y=r.filter(m=>u.has(m.source)&&u.has(m.target));return{nodes:t,edges:y}}};function ut(l,e){let t=new Map;if(l.metadata?.imports)for(let[r,n]of Object.entries(l.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 mt={"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"},Et=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function tt(l,e){if(l.includes(".")){let t=l.indexOf("."),r=l.substring(0,t),n=l.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function Ct(l,e){let t=tt(l,e);return t?mt[t]==="Class":!1}function xt(l,e){let t=tt(l,e);return t?Et.has(t):!1}function Tt(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=tt(l,r);if(n){let s=mt[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=l.split(".").pop()??l;return t.has(o)?"Instance":"Unknown"}var ft=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function yt(l,e,t,r,n,o,s,a,i){let c=e.type,p=e.subClassOf;if(p){let f=Array.isArray(p)?p:[p];for(let d of f)typeof d=="string"&&o.push({source:l,target:G(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:l,target:G(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:G(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(ft.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&Nt(h)&&o.push({source:l,target:G(h,s,a,i),type:"propertyValue",label:f,propertyId:G(f,s,a,i)})}let y=t==="ObjectProperty"||t==="DatatypeProperty",m=e.domain&&e.range;if((y||m)&&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:G(f,s,a,i),target:G(d,s,a,i),type:"objectRelationship",label:e.label??l.split("/").pop()??"",propertyId:l})}}function Ze(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(ft.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,y=`${l}/${c}`,m=r.get(c),f=m?m.split(".").pop()??m:"Unknown",d={};for(let[h,k]of Object.entries(u))(typeof k!="object"||k===null)&&(d[h]=k);n.push({id:y,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:l,target:y,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),m&&o.push({source:y,target:G(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),Ze(y,u,t,r,n,o,s,a,i)}}function Nt(l){return!(!l||l.includes(" ")||l.includes(`
|
|
2
|
+
`)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function G(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.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}/${l}@${t}`:l}var Q=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 b=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 Te=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ee=class l{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&&l.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new b;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 te=class l{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&&l.RESERVED_WORDS.has(n.toLowerCase())){let s=new b;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(!l.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 b;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(!l.VALID_PROPERTIES.has(n)&&!l.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new b;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 re=class l{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 p=c?.toString();p&&p==="Property"&&!r&&i.push(p)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let p=this.getPropertyValue(s,"range"),u=this.determinePropertyType(p),y=new b;y.ruleType=this.ruleName,y.severity="Error",y.entityName=n,y.propertyName="type",y.actualValue=c,y.expectedValue=u,y.message=`Invalid property type '${c}'. Use '${u}' instead.`,y.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(y)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":l.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 ne=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 b;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 oe=class{get ruleName(){return"EmbeddedKanonakNoExplicitType"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&this.checkForEmbeddedTypeViolations(r,n,t,0);return t}checkForEmbeddedTypeViolations(e,t,r,n){for(let[o,s]of Object.entries(t)){let a=o;if(n>0&&a.toLowerCase()==="type"){let i=s?.toString(),c=e.split(".")[0],p=new b;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue="type",p.message=`Embedded object at '${e}' cannot have explicit 'type' property.`,p.suggestion=`Remove the 'type: ${i}' line.
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var mr=Object.defineProperty;var yr=(l,e)=>()=>(l&&(e=l(l=0)),e);var fr=(l,e)=>{for(var t in e)mr(l,t,{get:e[t],enumerable:!0})};var Nt={};fr(Nt,{KanonakUri:()=>K});var K,Ve=yr(()=>{"use strict";K=class l{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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});var Ge=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 this.versionsEqual(s,t.version);case 1:return this.isCompatibleVersion(s,t.version);case 2:return this.isMajorCompatible(s,t.version);case 3:return this.compareVersions(s,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((o,s)=>{let a=o.metadata.namespace_.version,i=s.metadata.namespace_.version;return!a&&!i?0:a?i?this.compareVersions(i,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}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}};import*as C from"fs/promises";import*as D from"path";import*as ze 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=ze.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),ze.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 p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},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 p=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:p,versionOperator:f,version:m,alias:y,minVersion:m,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:m.toString()};return y&&(g.alias=y),g},toString:()=>`${p} ${u} ${m.toString()} as ${y}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=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:p,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:m.toString()}),toString:()=>`${p} ${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 Y=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 E,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 this.versionsEqual(a,t.version);case 1:return this.isCompatibleVersion(a,t.version);case 2:return this.isMajorCompatible(a,t.version);case 3:return this.compareVersions(a,t.minVersion)>=0;default:return!1}});return o.length===0?null:(o.sort((s,a)=>{let i=s.metadata.namespace_.version,c=a.metadata.namespace_.version;return this.compareVersions(c,i)}),o[0])}async saveDocumentAsync(e,t){let r,n=e.metadata.namespace_?.toString();if(n&&n.includes("@")&&n.includes("/")){let i=n.split("/"),c=i[0],u=i[1].replace("@","@")+".kan.yml";r=D.join(this.rootPath,c,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 C.mkdir(o,{recursive:!0});let s=this.parser.save(e);await C.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 C.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 C.readdir(n);for(let s of o)s.includes(t)&&s.endsWith(".kan.yml")&&await C.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=`file://${r}`,o;for(let[i,c]of this.documentCache.entries())if(this.filePathsByIdentifier.get(i)===r&&c.metadata.namespace_){o=c.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 C.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await C.access(r),t=r}catch{return null}}try{return await C.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await C.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await C.access(r),t=r}catch{return null}}return`file://${t}`}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 C.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async n=>{try{let o=await C.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 i=o.metadata.namespace_.toString();this.documentCache.set(i,o),this.documentCache.set(n,o),this.documentCache.set(a,o),this.filePathsByIdentifier.set(i,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)}}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}async findYamlFiles(e,t){let r=[];try{let n=await C.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 Se from"fs";var wt=(r=>(r.NotFound="NotFound",r.Workspace="Workspace",r.Cache="Cache",r))(wt||{}),je=class{cache;workspace;constructor(e,t,r){let n=r??new E;Se.existsSync(e)||Se.mkdirSync(e,{recursive:!0}),Se.existsSync(t)||Se.mkdirSync(t,{recursive:!0}),this.cache=new Y(e,!0,n),this.workspace=new Y(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 dr}from"os";import{join as gr}from"path";function Te(){let l=process.env.KANONAK_PACKAGE_CACHE;return l||gr(dr(),".kanonak","packages")}var qe=class l{static createComposite(e,t,r){let n=e??Te(),o=t??".";return new je(n,o,r)}static createFromEnvironment(e){let t=Te(),r=process.env.KANONAK_WORKSPACE_PATH??".";return l.createComposite(t,r,e)}};import{VersionOperator as Xe}from"@kanonak-protocol/types/document/models/enums";var hr="https://{publisher}/index.txt",kr="https://{publisher}/{package}/{version}.kan.yml",Ot={version:1},Ee=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 Ot}if(r.status===404)return Ot;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??hr;return Tt(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??kr;return Tt(o,{publisher:e,package:t,version:r})}};function Tt(l,e){let t=l;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: ${l}`);return t}var J=class l{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Ee,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 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 l.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
|
|
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 i=t.get(s);i?i.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=l.parseVersion(e);if(!n)return!1;switch(r){case Xe.Any:return!0;case Xe.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case Xe.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case Xe.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=l.parseVersion(e),n=l.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 Ye=class{parser=new E;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 J({fetchFn:e.fetchFn}):new J}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 p=this.getFromCache(e,t.packageName,r);if(p){let u=this.parser.parse(p);return this.documents.set(n,u),this.contentCache.set(n,p),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 i=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,i);let c=this.parser.parse(i);return this.documents.set(n,c),this.contentCache.set(n,i),c}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 L=class{};var U=class extends L{statement=[]};var B=class extends U{namespace;name;icon};var M=class extends U{};Ve();var A=class l extends L{subject;static parse(e){let t=new l;return t.subject=K.parse(e),t}};var x=class{predicate;object};var T=class extends x{};var Z=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var Q=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var ee=class extends T{};var te=class l extends x{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=A.parse(t),r}};var W=class extends x{};var H=class extends x{};Ve();function S(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var V=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 K(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 p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);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}/${p.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.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 p=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 K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),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,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)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 G=class l{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"&&l.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 l.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 Ke=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new V(e),o=new G(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new B;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}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 p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}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=o.getPropertyTypeClassification(i),p=a.range?.toString(),u;if(c==="ObjectProperty")u="ObjectProperty";else if(c==="DatatypeProperty")u="DatatypeProperty";else{let y=p&&p.includes(".")?p.substring(p.lastIndexOf(".")+1):p??"";(p?o.isKnownXsdDatatypeName(p):!1)||y==="Literal"?u="DatatypeProperty":u="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:u,range:p,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(typeof t=="string")return Z.parse(e,t);if(typeof t=="number")return Q.parse(e,t);if(typeof t=="boolean"){let n=new ee;return n.predicate=A.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 te;return i.predicate=A.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new M;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new W;return p.predicate=A.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new M;u.statement=await this.parseStatements(p,n,o,s,{}),i.push(u)}else if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&i.push(u)}if(i.length>0){let p=new H;return p.predicate=A.parse(e),p.object=i,p}let c=new W;return c.predicate=A.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,n,o);p&&a.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new M;p.statement=await this.parseStatements(c,n,o,s,{}),a.push(p)}let i=new H;return i.predicate=A.parse(e),i.object=a,i}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new A;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(Ve(),Nt)),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("."),p=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)===p){let g=new A;return g.subject=new s(m,f.packageName,u,f.version),g}}}let i=new A;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 B&&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 B&&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,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof Z)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 te)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof H){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof W){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 A?t.push(r.subject.name):r instanceof M&&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 br=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 N(l){let e=l;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 F(l,e){return br.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return N(e)}static isCoreOntologyType(e){return F(e.publisher,e.package_)}static isClassType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=N(e);return!t||!F(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=N(e);return!t||!F(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(l.isSchemaDefinitionType(e))return!1;let r=N(e);return r?t.has(r.name):!1}};var At=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(At||{}),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||{}),Je=class{static async buildFromRepository(e){let r=await new Ke().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&&(w.isClassType(m)&&a.add(m.name),(w.isObjectPropertyType(m)||w.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 p=new Map;for(let u of r){let m=u;m.name&&p.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=Mt(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=p.get(g),R="Unknown";if(b){let j=b;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,$={};for(let[j,Pt]of Object.entries(h))j!=="type"&&(typeof Pt!="object"||Pt===null)&&($[j]=Pt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:$}),Ft(v,h,R,a,i,s,y,f,d),It(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,p=Mt(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(vr(d,p)&&a.add(y),Pr(d,p)&&(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=wr(d,y,a,p),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}),Ft(h,f,g,a,i,r,s,o,p),It(h,f,i,c,t,r,s,o,p)}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 Mt(l,e){let t=new Map;if(l.metadata?.imports)for(let[r,n]of Object.entries(l.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 Lt={"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"},Rr=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Ct(l,e){if(l.includes(".")){let t=l.indexOf("."),r=l.substring(0,t),n=l.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function vr(l,e){let t=Ct(l,e);return t?Lt[t]==="Class":!1}function Pr(l,e){let t=Ct(l,e);return t?Rr.has(t):!1}function wr(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=Ct(l,r);if(n){let s=Lt[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=l.split(".").pop()??l;return t.has(o)?"Instance":"Unknown"}var Ut=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Ft(l,e,t,r,n,o,s,a,i){let c=e.type,p=e.subClassOf;if(p){let f=Array.isArray(p)?p:[p];for(let d of f)typeof d=="string"&&o.push({source:l,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:l,target:z(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:z(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Ut.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&Ir(h)&&o.push({source:l,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??l.split("/").pop()??"",propertyId:l})}}function It(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(Ut.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,m=`${l}/${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:l,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)"}),It(m,u,t,r,n,o,s,a,i)}}function Ir(l){return!(!l||l.includes(" ")||l.includes(`
|
|
3
|
-
`)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function z(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.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}/${l}@${t}`:l}import Ar from"ignore";import*as Qe from"fs";import*as xe from"path";var Ze=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=xe.join(e,".gitignore");if(Qe.existsSync(t))try{let r=Qe.readFileSync(t,"utf8");this.ignoreInstance=Ar(),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 et=class{propertyUri;propertyType;range;isImported;definedInNamespace};Ve();Ve();var tt=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],i=this.findPackageNameForAlias(r,s);if(i){for(let c of t.values())if(c.entityName===a&&c.uri.package_===i)return c.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new K(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}};async function Wt(l,e){let t=[],r=await l.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[c,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let u=p.type;!u||typeof u!="string"||u!=="Package"&&Dr(u,e)&&t.push({entityName:c,entity:p,documentNamespace:`${s}/${a}@${i}`,publisher:s,package_:a,version:i})}}return t}function Dr(l,e){let t=Bt(l),r=Bt(e);return t===r}function Bt(l){let e=l.lastIndexOf(".");if(e!==-1)return l.substring(e+1);let t=l.lastIndexOf("/");return t!==-1?l.substring(t+1):l}var re=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 rt=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ne=class l{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&&l.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 oe=class l{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=[];for(let[
|
|
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 i=t.get(s);i?i.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=l.parseVersion(e);if(!n)return!1;switch(r){case Xe.Any:return!0;case Xe.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case Xe.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case Xe.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=l.parseVersion(e),n=l.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 Ye=class{parser=new E;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 J({fetchFn:e.fetchFn}):new J}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 p=this.getFromCache(e,t.packageName,r);if(p){let u=this.parser.parse(p);return this.documents.set(n,u),this.contentCache.set(n,p),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 i=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,i);let c=this.parser.parse(i);return this.documents.set(n,c),this.contentCache.set(n,i),c}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 L=class{};var U=class extends L{statement=[]};var B=class extends U{namespace;name;icon};var M=class extends U{};Ve();var A=class l extends L{subject;static parse(e){let t=new l;return t.subject=K.parse(e),t}};var x=class{predicate;object};var T=class extends x{};var Z=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var Q=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var ee=class extends T{};var te=class l extends x{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=A.parse(t),r}};var W=class extends x{};var H=class extends x{};Ve();function S(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var V=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 K(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 p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);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}/${p.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.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 p=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 K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),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,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)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 G=class l{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"&&l.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 l.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 Ke=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new V(e),o=new G(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new B;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}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 p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}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(typeof t=="string")return Z.parse(e,t);if(typeof t=="number")return Q.parse(e,t);if(typeof t=="boolean"){let n=new ee;return n.predicate=A.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 te;return i.predicate=A.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new M;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new W;return p.predicate=A.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new M;u.statement=await this.parseStatements(p,n,o,s,{}),i.push(u)}else if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&i.push(u)}if(i.length>0){let p=new H;return p.predicate=A.parse(e),p.object=i,p}let c=new W;return c.predicate=A.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,n,o);p&&a.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new M;p.statement=await this.parseStatements(c,n,o,s,{}),a.push(p)}let i=new H;return i.predicate=A.parse(e),i.object=a,i}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new A;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(Ve(),Nt)),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("."),p=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)===p){let g=new A;return g.subject=new s(m,f.packageName,u,f.version),g}}}let i=new A;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 B&&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 B&&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,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof Z)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 te)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof H){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof W){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 A?t.push(r.subject.name):r instanceof M&&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 br=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 N(l){let e=l;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 F(l,e){return br.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return N(e)}static isCoreOntologyType(e){return F(e.publisher,e.package_)}static isClassType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=N(e);return!t||!F(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=N(e);return!t||!F(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(l.isSchemaDefinitionType(e))return!1;let r=N(e);return r?t.has(r.name):!1}};var At=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(At||{}),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||{}),Je=class{static async buildFromRepository(e){let r=await new Ke().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&&(w.isClassType(m)&&a.add(m.name),(w.isObjectPropertyType(m)||w.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 p=new Map;for(let u of r){let m=u;m.name&&p.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=Mt(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=p.get(g),R="Unknown";if(b){let j=b;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,$={};for(let[j,Pt]of Object.entries(h))j!=="type"&&(typeof Pt!="object"||Pt===null)&&($[j]=Pt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:$}),Ft(v,h,R,a,i,s,y,f,d),It(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,p=Mt(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(vr(d,p)&&a.add(y),Pr(d,p)&&(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=wr(d,y,a,p),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}),Ft(h,f,g,a,i,r,s,o,p),It(h,f,i,c,t,r,s,o,p)}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 Mt(l,e){let t=new Map;if(l.metadata?.imports)for(let[r,n]of Object.entries(l.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 Lt={"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"},Rr=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Ct(l,e){if(l.includes(".")){let t=l.indexOf("."),r=l.substring(0,t),n=l.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function vr(l,e){let t=Ct(l,e);return t?Lt[t]==="Class":!1}function Pr(l,e){let t=Ct(l,e);return t?Rr.has(t):!1}function wr(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=Ct(l,r);if(n){let s=Lt[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=l.split(".").pop()??l;return t.has(o)?"Instance":"Unknown"}var Ut=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Ft(l,e,t,r,n,o,s,a,i){let c=e.type,p=e.subClassOf;if(p){let f=Array.isArray(p)?p:[p];for(let d of f)typeof d=="string"&&o.push({source:l,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:l,target:z(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:z(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Ut.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&Ir(h)&&o.push({source:l,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??l.split("/").pop()??"",propertyId:l})}}function It(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(Ut.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,m=`${l}/${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:l,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)"}),It(m,u,t,r,n,o,s,a,i)}}function Ir(l){return!(!l||l.includes(" ")||l.includes(`
|
|
3
|
+
`)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function z(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.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}/${l}@${t}`:l}import Ar from"ignore";import*as Qe from"fs";import*as xe from"path";var Ze=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=xe.join(e,".gitignore");if(Qe.existsSync(t))try{let r=Qe.readFileSync(t,"utf8");this.ignoreInstance=Ar(),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 et=class{propertyUri;propertyType;range;isImported;definedInNamespace};Ve();Ve();var tt=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],i=this.findPackageNameForAlias(r,s);if(i){for(let c of t.values())if(c.entityName===a&&c.uri.package_===i)return c.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new K(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}};async function Wt(l,e){let t=[],r=await l.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[c,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let u=p.type;!u||typeof u!="string"||u!=="Package"&&Dr(u,e)&&t.push({entityName:c,entity:p,documentNamespace:`${s}/${a}@${i}`,publisher:s,package_:a,version:i})}}return t}function Dr(l,e){let t=Bt(l),r=Bt(e);return t===r}function Bt(l){let e=l.lastIndexOf(".");if(e!==-1)return l.substring(e+1);let t=l.lastIndexOf("/");return t!==-1?l.substring(t+1):l}var re=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 rt=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ne=class l{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&&l.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 oe=class l{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&&l.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(!l.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(!l.VALID_PROPERTIES.has(n)&&!l.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 se=class l{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 p=c?.toString();p&&p==="Property"&&!r&&i.push(p)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let p=this.getPropertyValue(s,"range"),u=this.determinePropertyType(p),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":l.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 ae=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:
|
|
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.`,i.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(i)}}return t}};var ie=class{get ruleName(){return"EmbeddedKanonakNoExplicitType"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&this.checkForEmbeddedTypeViolations(r,n,t,0);return t}checkForEmbeddedTypeViolations(e,t,r,n){for(let[o,s]of Object.entries(t)){let a=o;if(n>0&&a.toLowerCase()==="type"){let i=s?.toString(),c=e.split(".")[0],p=new k;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue="type",p.message=`Embedded object at '${e}' cannot have explicit 'type' property.`,p.suggestion=`Remove the 'type: ${i}' line.
|
package/dist/parsing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.defineProperty;var q=(u,e)=>()=>(u&&(e=u(u=0)),e);var U=(u,e)=>{for(var t in e)F(u,t,{get:e[t],enumerable:!0})};var L={};U(L,{KanonakUri:()=>b});var b,D=q(()=>{"use strict";b=class u{constructor(e,t,n,a){this.publisher=e;this.package_=t;this.name=n;this.version=a}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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let n=t[0],a=t[1],r=n.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${n}. Expected format: publisher/package/name`);let o=a.split(".").map(Number),i={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(o[0]||0)&&s.minor===(o[1]||0)&&s.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:s=>(o[0]||0)!==s.major?(o[0]||0)-s.major:(o[1]||0)!==s.minor?(o[1]||0)-s.minor:(o[2]||0)-s.patch};return new u(r[0],r[1],r[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as x from"js-yaml";var P=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let a=x.load(e);if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let r=this.extractMetadata(a),o=this.extractBody(a,r);return n={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(a){let r=a,o={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 t.push(o),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=a}return Object.assign(t,e.body),x.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 n=[];for(let a of Object.values(t))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===t&&r.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:r=>e!==r.major?e-r.major:t!==r.minor?t-r.minor:n-r.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){t.type_="Package";let r=n,o=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return o&&r&&(t.namespace_={publisher:o,package_:r,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===o&&s.package_===r&&(!i||!s.version||i.equals(s.version)),getHashCode:()=>{let s=0;for(let c=0;c<o.length;c++)s=(s<<5)-s+o.charCodeAt(c);for(let c=0;c<r.length;c++)s=(s<<5)-s+r.charCodeAt(c);return s|0}}),a.imports&&Array.isArray(a.imports)&&(t.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},a;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){a=r;break}for(let[r,o]of Object.entries(e))r!==a&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(n[r]=o);return n}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===r[1]&&i.package_===r[2]&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let s=0;s<r[1].length;s++)i=(i<<5)-i+r[1].charCodeAt(s);for(let s=0;s<r[2].length;s++)i=(i<<5)-i+r[2].charCodeAt(s);return i|0}}}}let t=e.publisher||"",n=e.package||"",a=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:a,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===t&&r.package_===n&&(!a||!r.version||a.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);return r|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 n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");t[a]||(t[a]=[]);for(let r of n.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,a);t[a].push(o)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),r=a.publisher||"";t[r]||(t[r]=[]),t[r].push(a)}return t}parseImportsLegacy(e){let t={};for(let[n,a]of Object.entries(e))Array.isArray(a)&&(t[n]=a.map(r=>this.parseImport(r,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let o=this.parseVersion(r),i=this.parseVersionOperator(a),s=this.calculateMaxVersion(a,o),c=e.alias;return{package_:`${n} ${a} ${o.toString()}`,publisher:t,packageName:n,versionOperator:i,version:o,alias:c,minVersion:o,maxVersion:s,toEmbeddedObject:()=>{let p={package:n,match:a,version:o.toString()};return c&&(p.alias=c),p},toString:()=>c?`${n} ${a} ${o.toString()} as ${c}`:`${n} ${a} ${o.toString()}`}}parseImport(e,t){if(typeof e=="string"){let s=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(s){let p=s[1].trim(),m=s[2],l=this.parseVersion(s[3].trim()),d=s[4].trim(),g=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:g,version:l,alias:d,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let k={package:p,match:m,version:l.toString()};return d&&(k.alias=d),k},toString:()=>`${p} ${m} ${l.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(m),g=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:l,alias:void 0,minVersion:l,maxVersion:g,toEmbeddedObject:()=>({package:p,match:m,version:l.toString()}),toString:()=>`${p} ${m} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),a=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",a);return{package_:e.package||"",publisher:t,packageName:r,versionOperator:n,version:a,alias:e.alias,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let s={package:r,match:o,version:a.toString()};return e.alias&&(s.alias=e.alias),s},toString:()=>`${r} ${o} ${a.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[n,a]of Object.entries(e)){let r={publisher:n,packages:a.map(o=>{let i=["=","~","^","*"][o.versionOperator],s={package:o.packageName,match:i,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(s.alias=o.alias),s})};t.push(r)}return t}};var R=class{};var S=class extends R{statement=[]};var I=class extends S{namespace;name;icon};var K=class extends S{};D();var f=class u extends R{subject;static parse(e){let t=new u;return t.subject=b.parse(e),t}};var y=class{predicate;object};var v=class extends y{};var j=class u extends v{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var A=class u extends v{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var V=class extends v{};var E=class u extends y{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=f.parse(t),n}};var $=class extends y{};var w=class extends y{};D();function M(u){if(Array.isArray(u))return u.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=u?.toString();return e?[e]:[]}var O=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",a=this.cache.get(n);if(a){let o=a.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let a=e.split("."),r=a[0],o=a[1],i=await this.findDocumentForAlias(t,r);return i?await this.resolveAllEntitiesAsync(o,i):[]}return n.filter(a=>a.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let a=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`;for(let[i,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.push({entityName:i,uri:new b(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:s,definedInNamespace:r,isImported:n.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${a.length} entities from ${r}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(s,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,o);a.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${l.message}`,l),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return a}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let a=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`,i=0;for(let[s,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!a.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(s,{entityName:s,uri:new b(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:c,definedInNamespace:r,isImported:n.length>0,importPath:o}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(l,t,o),g=0;for(let[h,k]of d.entries())if(a.has(h)||(a.set(h,k),g++),m.alias&&!h.includes(".")){let C=`${m.alias}.${h}`;a.has(C)||(a.set(C,k),g++)}this.logger?.debug?.(`Merged ${g} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let d=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return a}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,a]of Object.entries(e.metadata.imports))for(let r of a){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,a)}async isSubclassOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let i=M(o);for(let s of i)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,n,a))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,a)}async isSubpropertyOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let i=M(o);for(let s of i)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,n,a))return!0}return!1}};var _=class u{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"&&u.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 u.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let a=n.entity.type;if(a){let r=String(a);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,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 N=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),a=new O(e),r=new _(a);for(let o of n)for(let[i,s]of Object.entries(o.body)){let c=new I;c.namespace=o.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(s,o,a,r,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,n,a,r){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[i,s]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,r,a);if(!c)continue;let p=await this.parsePropertyValue(i,s,c,t,n,a);p&&o.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return o}async getPropertyMetadata(e,t,n,a,r){let o=await n.resolveEntityAsync(e,t);if(!o)return;let i=o.entity,s=i.type?.toString()??"",c=r.getPropertyTypeClassification(s),p=i.range?.toString(),m;if(c==="ObjectProperty")m="ObjectProperty";else if(c==="DatatypeProperty")m="DatatypeProperty";else{let d=p&&p.includes(".")?p.substring(p.lastIndexOf(".")+1):p??"";(p?r.isKnownXsdDatatypeName(p):!1)||d==="Literal"?m="DatatypeProperty":m="ObjectProperty"}return{propertyUri:o.uri.toString(),propertyType:m,range:p,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,n,a,r,o){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,a,r,o);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,a,r,o)}}parseDatatypeValue(e,t,n){if(typeof t=="string")return j.parse(e,t);if(typeof t=="number")return A.parse(e,t);if(typeof t=="boolean"){let a=new V;return a.predicate=f.parse(e),a.object=t,a}}async parseObjectValue(e,t,n,a,r,o){if(typeof t=="string"){let i=await this.resolveReference(t,a,r);if(!i)return;let s=new E;return s.predicate=f.parse(e),s.object=i,s}if(typeof t=="object"&&!Array.isArray(t)){let i=new K;if(i.statement=await this.parseStatements(t,a,r,o,{}),i.statement.length>0){let p=new $;return p.predicate=f.parse(e),p.object=i,p}let s=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new K;m.statement=await this.parseStatements(p,a,r,o,{}),s.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&s.push(m)}if(s.length>0){let p=new w;return p.predicate=f.parse(e),p.object=s,p}let c=new $;return c.predicate=f.parse(e),c.object=i,c}}async parseListValue(e,t,n,a,r,o){let i=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,a,r);p&&i.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new K;p.statement=await this.parseStatements(c,a,r,o,{}),i.push(p)}let s=new w;return s.predicate=f.parse(e),s.object=i,s}async resolveReference(e,t,n){let a=await n.resolveEntityAsync(e,t);if(a){let o=new f;return o.subject=a.uri,o}let r=t.metadata?.namespace_;if(r){let{KanonakUri:o}=await Promise.resolve().then(()=>(D(),L)),i=r.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,d]of Object.entries(t.metadata.imports))for(let g of d)if((g.alias??g.packageName)===p){let k=new f;return k.subject=new o(l,g.packageName,m,g.version),k}}}let s=new f;return s.subject=new o(r.publisher,r.package_,e,i),s}return null}async saveKanonaks(e,t){let n=new Map;for(let a of e)a instanceof I&&a.namespace&&(n.has(a.namespace)||n.set(a.namespace,[]),n.get(a.namespace).push(a));for(let[a,r]of n){let o=await this.convertKanonaksToDocument(a,r),i=`${a.split("@")[0]}.yml`;await t.saveDocumentAsync(o,i)}}async serializeToYaml(e,t){let n=e.filter(o=>o instanceof I&&o.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let a=await this.convertKanonaksToDocument(t,n);return new P().save(a)}async convertKanonaksToDocument(e,t){let a={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let i of Object.values(this.imports))o.push(...i);return o}},body:{}},r=new Map;for(let o of t){let i={};for(let s of o.statement){let[c,p]=this.convertStatementToProperty(s);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(s,e,r)}a.body[o.name]=i}return a}convertStatementToProperty(e){if(e instanceof j)return[e.predicate.subject.name,e.object];if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof V)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof w){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof $){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof f?t.push(n.subject.name):n instanceof K&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[a,r]=this.convertStatementToProperty(n);a&&r!==null&&r!==void 0&&(t[a]=r)}return t}collectImportsFromStatement(e,t,n){}};var T=class{propertyUri;propertyType;range;isImported;definedInNamespace};export{N as KanonakObjectParser,P as KanonakParser,T as PropertyMetadata};
|
|
1
|
+
var F=Object.defineProperty;var q=(l,e)=>()=>(l&&(e=l(l=0)),e);var U=(l,e)=>{for(var t in e)F(l,t,{get:e[t],enumerable:!0})};var L={};U(L,{KanonakUri:()=>b});var b,x=q(()=>{"use strict";b=class l{constructor(e,t,n,a){this.publisher=e;this.package_=t;this.name=n;this.version=a}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!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let n=t[0],a=t[1],r=n.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${n}. Expected format: publisher/package/name`);let o=a.split(".").map(Number),i={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(o[0]||0)&&s.minor===(o[1]||0)&&s.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:s=>(o[0]||0)!==s.major?(o[0]||0)-s.major:(o[1]||0)!==s.minor?(o[1]||0)-s.minor:(o[2]||0)-s.patch};return new l(r[0],r[1],r[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as O from"js-yaml";var $=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let a=O.load(e);if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let r=this.extractMetadata(a),o=this.extractBody(a,r);return n={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(a){let r=a,o={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 t.push(o),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=a}return Object.assign(t,e.body),O.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 n=[];for(let a of Object.values(t))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===t&&r.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:r=>e!==r.major?e-r.major:t!==r.minor?t-r.minor:n-r.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){t.type_="Package";let r=n,o=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return o&&r&&(t.namespace_={publisher:o,package_:r,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===o&&s.package_===r&&(!i||!s.version||i.equals(s.version)),getHashCode:()=>{let s=0;for(let c=0;c<o.length;c++)s=(s<<5)-s+o.charCodeAt(c);for(let c=0;c<r.length;c++)s=(s<<5)-s+r.charCodeAt(c);return s|0}}),a.imports&&Array.isArray(a.imports)&&(t.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},a;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){a=r;break}for(let[r,o]of Object.entries(e))r!==a&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(n[r]=o);return n}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===r[1]&&i.package_===r[2]&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let s=0;s<r[1].length;s++)i=(i<<5)-i+r[1].charCodeAt(s);for(let s=0;s<r[2].length;s++)i=(i<<5)-i+r[2].charCodeAt(s);return i|0}}}}let t=e.publisher||"",n=e.package||"",a=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:a,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===t&&r.package_===n&&(!a||!r.version||a.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);return r|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 n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");t[a]||(t[a]=[]);for(let r of n.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,a);t[a].push(o)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),r=a.publisher||"";t[r]||(t[r]=[]),t[r].push(a)}return t}parseImportsLegacy(e){let t={};for(let[n,a]of Object.entries(e))Array.isArray(a)&&(t[n]=a.map(r=>this.parseImport(r,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let o=this.parseVersion(r),i=this.parseVersionOperator(a),s=this.calculateMaxVersion(a,o),c=e.alias;return{package_:`${n} ${a} ${o.toString()}`,publisher:t,packageName:n,versionOperator:i,version:o,alias:c,minVersion:o,maxVersion:s,toEmbeddedObject:()=>{let p={package:n,match:a,version:o.toString()};return c&&(p.alias=c),p},toString:()=>c?`${n} ${a} ${o.toString()} as ${c}`:`${n} ${a} ${o.toString()}`}}parseImport(e,t){if(typeof e=="string"){let s=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(s){let p=s[1].trim(),m=s[2],u=this.parseVersion(s[3].trim()),d=s[4].trim(),y=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,u);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:u,alias:d,minVersion:u,maxVersion:h,toEmbeddedObject:()=>{let k={package:p,match:m,version:u.toString()};return d&&(k.alias=d),k},toString:()=>`${p} ${m} ${u.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],u=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(m),y=this.calculateMaxVersion(m,u);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:u,alias:void 0,minVersion:u,maxVersion:y,toEmbeddedObject:()=>({package:p,match:m,version:u.toString()}),toString:()=>`${p} ${m} ${u.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),a=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",a);return{package_:e.package||"",publisher:t,packageName:r,versionOperator:n,version:a,alias:e.alias,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let s={package:r,match:o,version:a.toString()};return e.alias&&(s.alias=e.alias),s},toString:()=>`${r} ${o} ${a.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[n,a]of Object.entries(e)){let r={publisher:n,packages:a.map(o=>{let i=["=","~","^","*"][o.versionOperator],s={package:o.packageName,match:i,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(s.alias=o.alias),s})};t.push(r)}return t}};var R=class{};var S=class extends R{statement=[]};var P=class extends S{namespace;name;icon};var K=class extends S{};x();var f=class l extends R{subject;static parse(e){let t=new l;return t.subject=b.parse(e),t}};var g=class{predicate;object};var v=class extends g{};var j=class l extends v{static parse(e,t){let n=new l;return n.predicate=f.parse(e),n.object=t,n}};var A=class l extends v{static parse(e,t){let n=new l;return n.predicate=f.parse(e),n.object=t,n}};var E=class extends v{};var V=class l extends g{static parse(e,t){let n=new l;return n.predicate=f.parse(e),n.object=f.parse(t),n}};var I=class extends g{};var w=class extends g{};x();function T(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var D=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",a=this.cache.get(n);if(a){let o=a.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let a=e.split("."),r=a[0],o=a[1],i=await this.findDocumentForAlias(t,r);return i?await this.resolveAllEntitiesAsync(o,i):[]}return n.filter(a=>a.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let a=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`;for(let[i,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.push({entityName:i,uri:new b(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:s,definedInNamespace:r,isImported:n.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${a.length} entities from ${r}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(s,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let u=await this.buildAllEntitiesIndexAsync(m,t,o);a.push(...u),this.logger?.debug?.(`Added ${u.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(m){let u=m;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${u.message}`,u),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return a}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let a=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`,i=0;for(let[s,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!a.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(s,{entityName:s,uri:new b(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:c,definedInNamespace:r,isImported:n.length>0,importPath:o}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(c,m);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(u,t,o),y=0;for(let[h,k]of d.entries())if(a.has(h)||(a.set(h,k),y++),m.alias&&!h.includes(".")){let M=`${m.alias}.${h}`;a.has(M)||(a.set(M,k),y++)}this.logger?.debug?.(`Merged ${y} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(u){let d=u;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${r}. See inner exception for details.`,{cause:u})}}return a}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,a]of Object.entries(e.metadata.imports))for(let r of a){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,a)}async isSubclassOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let i=T(o);for(let s of i)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,n,a))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,a)}async isSubpropertyOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let i=T(o);for(let s of i)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,n,a))return!0}return!1}};var _=class l{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"&&l.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 l.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let a=n.entity.type;if(a){let r=String(a);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,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 N=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),a=new D(e),r=new _(a);for(let o of n)for(let[i,s]of Object.entries(o.body)){let c=new P;c.namespace=o.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(s,o,a,r,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,n,a,r){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[i,s]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,r,a);if(!c)continue;let p=await this.parsePropertyValue(i,s,c,t,n,a);p&&o.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return o}async getPropertyMetadata(e,t,n,a,r){let o=await n.resolveEntityAsync(e,t);if(!o)return;let i=o.entity,s=i.type?.toString()??"",c=s.includes(".")?s.substring(s.lastIndexOf(".")+1):s;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=r.getPropertyTypeClassification(s),u=i.range?.toString(),d;if(m==="ObjectProperty")d="ObjectProperty";else if(m==="DatatypeProperty")d="DatatypeProperty";else{let h=u&&u.includes(".")?u.substring(u.lastIndexOf(".")+1):u??"";(u?r.isKnownXsdDatatypeName(u):!1)||h==="Literal"?d="DatatypeProperty":d="ObjectProperty"}return{propertyUri:o.uri.toString(),propertyType:d,range:u,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,n,a,r,o){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,a,r,o);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,a,r,o)}}parseDatatypeValue(e,t,n){if(typeof t=="string")return j.parse(e,t);if(typeof t=="number")return A.parse(e,t);if(typeof t=="boolean"){let a=new E;return a.predicate=f.parse(e),a.object=t,a}}async parseObjectValue(e,t,n,a,r,o){if(typeof t=="string"){let i=await this.resolveReference(t,a,r);if(!i)return;let s=new V;return s.predicate=f.parse(e),s.object=i,s}if(typeof t=="object"&&!Array.isArray(t)){let i=new K;if(i.statement=await this.parseStatements(t,a,r,o,{}),i.statement.length>0){let p=new I;return p.predicate=f.parse(e),p.object=i,p}let s=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new K;m.statement=await this.parseStatements(p,a,r,o,{}),s.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&s.push(m)}if(s.length>0){let p=new w;return p.predicate=f.parse(e),p.object=s,p}let c=new I;return c.predicate=f.parse(e),c.object=i,c}}async parseListValue(e,t,n,a,r,o){let i=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,a,r);p&&i.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new K;p.statement=await this.parseStatements(c,a,r,o,{}),i.push(p)}let s=new w;return s.predicate=f.parse(e),s.object=i,s}async resolveReference(e,t,n){let a=await n.resolveEntityAsync(e,t);if(a){let o=new f;return o.subject=a.uri,o}let r=t.metadata?.namespace_;if(r){let{KanonakUri:o}=await Promise.resolve().then(()=>(x(),L)),i=r.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[u,d]of Object.entries(t.metadata.imports))for(let y of d)if((y.alias??y.packageName)===p){let k=new f;return k.subject=new o(u,y.packageName,m,y.version),k}}}let s=new f;return s.subject=new o(r.publisher,r.package_,e,i),s}return null}async saveKanonaks(e,t){let n=new Map;for(let a of e)a instanceof P&&a.namespace&&(n.has(a.namespace)||n.set(a.namespace,[]),n.get(a.namespace).push(a));for(let[a,r]of n){let o=await this.convertKanonaksToDocument(a,r),i=`${a.split("@")[0]}.yml`;await t.saveDocumentAsync(o,i)}}async serializeToYaml(e,t){let n=e.filter(o=>o instanceof P&&o.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let a=await this.convertKanonaksToDocument(t,n);return new $().save(a)}async convertKanonaksToDocument(e,t){let a={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let i of Object.values(this.imports))o.push(...i);return o}},body:{}},r=new Map;for(let o of t){let i={};for(let s of o.statement){let[c,p]=this.convertStatementToProperty(s);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(s,e,r)}a.body[o.name]=i}return a}convertStatementToProperty(e){if(e instanceof j)return[e.predicate.subject.name,e.object];if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof V)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof w){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof I){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof f?t.push(n.subject.name):n instanceof K&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[a,r]=this.convertStatementToProperty(n);a&&r!==null&&r!==void 0&&(t[a]=r)}return t}collectImportsFromStatement(e,t,n){}};var C=class{propertyUri;propertyType;range;isImported;definedInNamespace};export{N as KanonakObjectParser,$ as KanonakParser,C as PropertyMetadata};
|
package/dist/validation/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var P=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(n=>(n.Warning="Warning",n.Error="Error",n))(b||{});var g=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 h{resolvedDocuments=[];currentEntityPath;withPath(e){let n=new h;return n.resolvedDocuments=this.resolvedDocuments,n.currentEntityPath=e,n}};import*as Z from"js-yaml";var G=class{parse(e){let n=this.parseWithErrors(e);if(!n.isValid){let t=n.errors[0];throw new Error(`YAML parse error at line ${t.line}, column ${t.column}: ${t.message}`)}return n.document}parseWithErrors(e){let n=[],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:n,isValid:!0};let r=this.extractMetadata(i),o=this.extractBody(i,r);return t={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:t,errors:n,isValid:!0}}catch(i){let r=i,o={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 n.push(o),{document:void 0,errors:n,isValid:!1}}}save(e){let n={};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)),n[t.package_]=i}return Object.assign(n,e.body),Z.dump(n,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let n=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!n)return[];let t=[];for(let i of Object.values(n))t.push(...i);return t},enumerable:!0,configurable:!0}),e}createVersion(e,n,t){return{major:e,minor:n,patch:t,toString:()=>`${e}.${n}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===n&&r.patch===t,getHashCode:()=>e<<20|n<<10|t,compareTo:r=>e!==r.major?e-r.major:n!==r.minor?n-r.minor:t-r.patch}}extractMetadata(e){let n=this.createEmptyMetadata();for(let[t,i]of Object.entries(e))if(i&&typeof i=="object"&&i.type==="Package"){n.type_="Package";let r=t,o=i.publisher,p=i.version?this.parseVersion(i.version):void 0;return o&&r&&(n.namespace_={publisher:o,package_:r,version:p,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===o&&a.package_===r&&(!p||!a.version||p.equals(a.version)),getHashCode:()=>{let a=0;for(let s=0;s<o.length;s++)a=(a<<5)-a+o.charCodeAt(s);for(let s=0;s<r.length;s++)a=(a<<5)-a+r.charCodeAt(s);return a|0}}),i.imports&&Array.isArray(i.imports)&&(n.imports=this.parseImportsV3(i.imports)),this.addAllImportsGetter(n)}if(e.kanonak&&typeof e.kanonak=="object"){let t=e.kanonak;return(t.publisher||t.package||t.version)&&(n.namespace_=this.parseNamespace(t)),t.imports&&typeof t.imports=="object"&&(n.imports=this.parseImportsLegacy(t.imports)),this.addAllImportsGetter(n)}return n}extractBody(e,n){let t={},i;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){i=r;break}for(let[r,o]of Object.entries(e))r!==i&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(t[r]=o);return t}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:p=>!p||typeof p!="object"?!1:p.publisher===r[1]&&p.package_===r[2]&&(!o||!p.version||o.equals(p.version)),getHashCode:()=>{let p=0;for(let a=0;a<r[1].length;a++)p=(p<<5)-p+r[1].charCodeAt(a);for(let a=0;a<r[2].length;a++)p=(p<<5)-p+r[2].charCodeAt(a);return p|0}}}}let n=e.publisher||"",t=e.package||"",i=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:n,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===n&&r.package_===t&&(!i||!r.version||i.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);return r|0}}}parseVersion(e){if(typeof e=="string"){let n=e.split(".").map(Number);return this.createVersion(n[0]||0,n[1]||0,n[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let n={};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");n[i]||(n[i]=[]);for(let r of t.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,i);n[i].push(o)}}else{let i=this.parseImportFromEmbeddedObject(t,t.publisher),r=i.publisher||"";n[r]||(n[r]=[]),n[r].push(i)}return n}parseImportsLegacy(e){let n={};for(let[t,i]of Object.entries(e))Array.isArray(i)&&(n[t]=i.map(r=>this.parseImport(r,t)));return n}parseImportFromEmbeddedObject(e,n){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 o=this.parseVersion(r),p=this.parseVersionOperator(i),a=this.calculateMaxVersion(i,o),s=e.alias;return{package_:`${t} ${i} ${o.toString()}`,publisher:n,packageName:t,versionOperator:p,version:o,alias:s,minVersion:o,maxVersion:a,toEmbeddedObject:()=>{let c={package:t,match:i,version:o.toString()};return s&&(c.alias=s),c},toString:()=>s?`${t} ${i} ${o.toString()} as ${s}`:`${t} ${i} ${o.toString()}`}}parseImport(e,n){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let c=a[1].trim(),l=a[2],m=this.parseVersion(a[3].trim()),y=a[4].trim(),u=this.parseVersionOperator(l),f=this.calculateMaxVersion(l,m);return{package_:e,publisher:n,packageName:c,versionOperator:u,version:m,alias:y,minVersion:m,maxVersion:f,toEmbeddedObject:()=>{let d={package:c,match:l,version:m.toString()};return y&&(d.alias=y),d},toString:()=>`${c} ${l} ${m.toString()} as ${y}`}}let s=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(s){let c=s[1].trim(),l=s[2],m=this.parseVersion(s[3].trim()),y=this.parseVersionOperator(l),u=this.calculateMaxVersion(l,m);return{package_:e,publisher:n,packageName:c,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:u,toEmbeddedObject:()=>({package:c,match:l,version:m.toString()}),toString:()=>`${c} ${l} ${m.toString()}`}}}let t=this.parseVersionOperator(e.operator||"~"),i=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][t],p=this.calculateMaxVersion(e.operator||"~",i);return{package_:e.package||"",publisher:n,packageName:r,versionOperator:t,version:i,alias:e.alias,minVersion:i,maxVersion:p,toEmbeddedObject:()=>{let a={package:r,match:o,version:i.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${r} ${o} ${i.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,n){switch(e){case"~":return this.createVersion(n.major,n.minor+1,0);case"^":return n.major===0?this.createVersion(0,n.minor+1,0):this.createVersion(n.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let n=[];for(let[t,i]of Object.entries(e)){let r={publisher:t,packages:i.map(o=>{let p=["=","~","^","*"][o.versionOperator],a={package:o.packageName,match:p,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(a.alias=o.alias),a})};n.push(r)}return n}};var I=class h{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 n=[];for(let[t,i]of Object.entries(e.body))i&&typeof i=="object"&&!Array.isArray(i)&&this.validateEntity(t,i,n);return n}validateEntity(e,n,t){for(let[i,r]of Object.entries(n)){let o=r?.toString()??"";if(o&&h.NAMESPACE_PREFIX_PATTERN.test(o)){let p=this.getSuggestionForPrefixedValue(o),a=e.split(".")[0],s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=a,s.propertyName=e,s.actualValue=i,s.expectedValue=p,s.message=`Invalid namespace prefix '${o}'. Use '${p}' 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 n=e.toLowerCase();if(n==="rdfs:class"||n==="owl:class")return"Class";if(n==="rdfs:property"||n==="rdf:property")return"DatatypeProperty or ObjectProperty";if(n.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var D=class h{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 n=[];for(let[t,i]of Object.entries(e.body)){if(h.RESERVED_WORDS.has(t.toLowerCase())){let r=new g;r.ruleType=this.ruleName,r.severity="Error",r.entityName=t,r.message=`Entity name '${t}' is a reserved word and cannot be used.`,r.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",n.push(r);continue}if(!h.VALID_NAME_PATTERN.test(t)){let r;/^\d/.test(t)?r="Entity names must start with a letter, not a number.":t.includes(" ")?r="Entity names cannot contain spaces. Use camelCase or underscores instead.":r="Entity names must start with a letter and contain only letters, numbers, and underscores.";let o=new g;o.ruleType=this.ruleName,o.severity="Error",o.entityName=t,o.message=`Invalid entity name '${t}'. ${r}`,o.suggestion=r,n.push(o)}i&&typeof i=="object"&&!Array.isArray(i)&&this.validatePropertyNames(t,i,n)}return n}validatePropertyNames(e,n,t){for(let i of Object.keys(n))if(!h.VALID_PROPERTIES.has(i)&&!h.VALID_PROPERTY_NAME_PATTERN.test(i)){let r=new g;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 h{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 n=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return n;let t=this.isPropertyDefinedAsClass(e);for(let[i,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r,p=o.type;if(p){let a=[];if(Array.isArray(p))for(let s of p){let c=s?.toString();c&&c==="Property"&&!t&&a.push(c)}else{let s=p?.toString();s&&s==="Property"&&!t&&a.push(s)}for(let s of a){let c=this.getPropertyValue(o,"range"),l=this.determinePropertyType(c),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=i,m.propertyName="type",m.actualValue=s,m.expectedValue=l,m.message=`Invalid property type '${s}'. Use '${l}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",n.push(m)}}}return n}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":h.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,n){let t=e[n];return t?t.toString():null}isPropertyDefinedAsClass(e){let n=e.body.Property;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n.type;if(i){let r=i.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var $=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let n=[];for(let[t,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i,o="type"in r,p=r.type?.toString().trim();if(!o||!p){let a=new g;a.ruleType=this.ruleName,a.severity="Error",a.entityName=t,a.propertyName="type",a.message=`Subject Kanonak '${t}' must have a 'type' property.`,a.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=(n=>(n.Warning="Warning",n.Error="Error",n))(b||{});var g=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 h{resolvedDocuments=[];currentEntityPath;withPath(e){let n=new h;return n.resolvedDocuments=this.resolvedDocuments,n.currentEntityPath=e,n}};import*as Z from"js-yaml";var G=class{parse(e){let n=this.parseWithErrors(e);if(!n.isValid){let t=n.errors[0];throw new Error(`YAML parse error at line ${t.line}, column ${t.column}: ${t.message}`)}return n.document}parseWithErrors(e){let n=[],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:n,isValid:!0};let r=this.extractMetadata(i),o=this.extractBody(i,r);return t={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:t,errors:n,isValid:!0}}catch(i){let r=i,o={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 n.push(o),{document:void 0,errors:n,isValid:!1}}}save(e){let n={};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)),n[t.package_]=i}return Object.assign(n,e.body),Z.dump(n,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let n=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!n)return[];let t=[];for(let i of Object.values(n))t.push(...i);return t},enumerable:!0,configurable:!0}),e}createVersion(e,n,t){return{major:e,minor:n,patch:t,toString:()=>`${e}.${n}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===n&&r.patch===t,getHashCode:()=>e<<20|n<<10|t,compareTo:r=>e!==r.major?e-r.major:n!==r.minor?n-r.minor:t-r.patch}}extractMetadata(e){let n=this.createEmptyMetadata();for(let[t,i]of Object.entries(e))if(i&&typeof i=="object"&&i.type==="Package"){n.type_="Package";let r=t,o=i.publisher,p=i.version?this.parseVersion(i.version):void 0;return o&&r&&(n.namespace_={publisher:o,package_:r,version:p,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===o&&a.package_===r&&(!p||!a.version||p.equals(a.version)),getHashCode:()=>{let a=0;for(let s=0;s<o.length;s++)a=(a<<5)-a+o.charCodeAt(s);for(let s=0;s<r.length;s++)a=(a<<5)-a+r.charCodeAt(s);return a|0}}),i.imports&&Array.isArray(i.imports)&&(n.imports=this.parseImportsV3(i.imports)),this.addAllImportsGetter(n)}if(e.kanonak&&typeof e.kanonak=="object"){let t=e.kanonak;return(t.publisher||t.package||t.version)&&(n.namespace_=this.parseNamespace(t)),t.imports&&typeof t.imports=="object"&&(n.imports=this.parseImportsLegacy(t.imports)),this.addAllImportsGetter(n)}return n}extractBody(e,n){let t={},i;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){i=r;break}for(let[r,o]of Object.entries(e))r!==i&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(t[r]=o);return t}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:p=>!p||typeof p!="object"?!1:p.publisher===r[1]&&p.package_===r[2]&&(!o||!p.version||o.equals(p.version)),getHashCode:()=>{let p=0;for(let a=0;a<r[1].length;a++)p=(p<<5)-p+r[1].charCodeAt(a);for(let a=0;a<r[2].length;a++)p=(p<<5)-p+r[2].charCodeAt(a);return p|0}}}}let n=e.publisher||"",t=e.package||"",i=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:n,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===n&&r.package_===t&&(!i||!r.version||i.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);return r|0}}}parseVersion(e){if(typeof e=="string"){let n=e.split(".").map(Number);return this.createVersion(n[0]||0,n[1]||0,n[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let n={};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");n[i]||(n[i]=[]);for(let r of t.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,i);n[i].push(o)}}else{let i=this.parseImportFromEmbeddedObject(t,t.publisher),r=i.publisher||"";n[r]||(n[r]=[]),n[r].push(i)}return n}parseImportsLegacy(e){let n={};for(let[t,i]of Object.entries(e))Array.isArray(i)&&(n[t]=i.map(r=>this.parseImport(r,t)));return n}parseImportFromEmbeddedObject(e,n){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 o=this.parseVersion(r),p=this.parseVersionOperator(i),a=this.calculateMaxVersion(i,o),s=e.alias;return{package_:`${t} ${i} ${o.toString()}`,publisher:n,packageName:t,versionOperator:p,version:o,alias:s,minVersion:o,maxVersion:a,toEmbeddedObject:()=>{let c={package:t,match:i,version:o.toString()};return s&&(c.alias=s),c},toString:()=>s?`${t} ${i} ${o.toString()} as ${s}`:`${t} ${i} ${o.toString()}`}}parseImport(e,n){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let c=a[1].trim(),l=a[2],m=this.parseVersion(a[3].trim()),y=a[4].trim(),u=this.parseVersionOperator(l),f=this.calculateMaxVersion(l,m);return{package_:e,publisher:n,packageName:c,versionOperator:u,version:m,alias:y,minVersion:m,maxVersion:f,toEmbeddedObject:()=>{let d={package:c,match:l,version:m.toString()};return y&&(d.alias=y),d},toString:()=>`${c} ${l} ${m.toString()} as ${y}`}}let s=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(s){let c=s[1].trim(),l=s[2],m=this.parseVersion(s[3].trim()),y=this.parseVersionOperator(l),u=this.calculateMaxVersion(l,m);return{package_:e,publisher:n,packageName:c,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:u,toEmbeddedObject:()=>({package:c,match:l,version:m.toString()}),toString:()=>`${c} ${l} ${m.toString()}`}}}let t=this.parseVersionOperator(e.operator||"~"),i=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][t],p=this.calculateMaxVersion(e.operator||"~",i);return{package_:e.package||"",publisher:n,packageName:r,versionOperator:t,version:i,alias:e.alias,minVersion:i,maxVersion:p,toEmbeddedObject:()=>{let a={package:r,match:o,version:i.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${r} ${o} ${i.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,n){switch(e){case"~":return this.createVersion(n.major,n.minor+1,0);case"^":return n.major===0?this.createVersion(0,n.minor+1,0):this.createVersion(n.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let n=[];for(let[t,i]of Object.entries(e)){let r={publisher:t,packages:i.map(o=>{let p=["=","~","^","*"][o.versionOperator],a={package:o.packageName,match:p,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(a.alias=o.alias),a})};n.push(r)}return n}};var I=class h{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 n=[];for(let[t,i]of Object.entries(e.body))i&&typeof i=="object"&&!Array.isArray(i)&&this.validateEntity(t,i,n);return n}validateEntity(e,n,t){for(let[i,r]of Object.entries(n)){let o=r?.toString()??"";if(o&&h.NAMESPACE_PREFIX_PATTERN.test(o)){let p=this.getSuggestionForPrefixedValue(o),a=e.split(".")[0],s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=a,s.propertyName=e,s.actualValue=i,s.expectedValue=p,s.message=`Invalid namespace prefix '${o}'. Use '${p}' 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 n=e.toLowerCase();if(n==="rdfs:class"||n==="owl:class")return"Class";if(n==="rdfs:property"||n==="rdf:property")return"DatatypeProperty or ObjectProperty";if(n.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var D=class h{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 n=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[i,r]of Object.entries(e.body)){if(!t&&h.RESERVED_WORDS.has(i.toLowerCase())){let o=new g;o.ruleType=this.ruleName,o.severity="Error",o.entityName=i,o.message=`Entity name '${i}' is a reserved word and cannot be used.`,o.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",n.push(o);continue}if(!h.VALID_NAME_PATTERN.test(i)){let o;/^\d/.test(i)?o="Entity names must start with a letter, not a number.":i.includes(" ")?o="Entity names cannot contain spaces. Use camelCase or underscores instead.":o="Entity names must start with a letter and contain only letters, numbers, and underscores.";let p=new g;p.ruleType=this.ruleName,p.severity="Error",p.entityName=i,p.message=`Invalid entity name '${i}'. ${o}`,p.suggestion=o,n.push(p)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(i,r,n)}return n}validatePropertyNames(e,n,t){for(let i of Object.keys(n))if(!h.VALID_PROPERTIES.has(i)&&!h.VALID_PROPERTY_NAME_PATTERN.test(i)){let r=new g;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 h{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 n=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return n;let t=this.isPropertyDefinedAsClass(e);for(let[i,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r,p=o.type;if(p){let a=[];if(Array.isArray(p))for(let s of p){let c=s?.toString();c&&c==="Property"&&!t&&a.push(c)}else{let s=p?.toString();s&&s==="Property"&&!t&&a.push(s)}for(let s of a){let c=this.getPropertyValue(o,"range"),l=this.determinePropertyType(c),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=i,m.propertyName="type",m.actualValue=s,m.expectedValue=l,m.message=`Invalid property type '${s}'. Use '${l}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",n.push(m)}}}return n}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":h.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,n){let t=e[n];return t?t.toString():null}isPropertyDefinedAsClass(e){let n=e.body.Property;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n.type;if(i){let r=i.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var $=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let n=[];for(let[t,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i,o="type"in r,p=r.type?.toString().trim();if(!o||!p){let a=new g;a.ruleType=this.ruleName,a.severity="Error",a.entityName=t,a.propertyName="type",a.message=`Subject Kanonak '${t}' must have a 'type' property.`,a.suggestion=`Add a type statement like:
|
|
2
2
|
type: Scene
|
|
3
3
|
|
|
4
4
|
Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,a.expectedValue="A valid class name (Scene, Character, Story, etc.)",n.push(a)}}return n}};var E=class{get ruleName(){return"EmbeddedKanonakNoExplicitType"}validate(e){let n=[];for(let[t,i]of Object.entries(e.body))typeof i=="object"&&i!==null&&!Array.isArray(i)&&this.checkForEmbeddedTypeViolations(t,i,n,0);return n}checkForEmbeddedTypeViolations(e,n,t,i){for(let[r,o]of Object.entries(n)){let p=r;if(i>0&&p.toLowerCase()==="type"){let a=o?.toString(),s=e.split(".")[0],c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=s,c.propertyName=e,c.actualValue="type",c.message=`Embedded object at '${e}' cannot have explicit 'type' property.`,c.suggestion=`Remove the 'type: ${a}' line.
|
|
@@ -6,14 +6,14 @@ Only embedded objects can infer type from their parent property's range. Subject
|
|
|
6
6
|
Type is automatically inferred from the containing property's range.
|
|
7
7
|
If you need a different type, modify the 'range' of the parent property and version it appropriately.
|
|
8
8
|
|
|
9
|
-
Example: If the parent property is 'hasCharacter' with range 'Character', all embedded objects in that property will be typed as 'Character' automatically.`,c.expectedValue="No explicit type (inferred from parent property's range)",t.push(c)}if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(let a=0;a<o.length;a++){let s=o[a];typeof s=="object"&&s!==null&&!Array.isArray(s)&&this.checkForEmbeddedTypeViolations(`${e}.${p}[${a}]`,s,t,i+1)}else this.checkForEmbeddedTypeViolations(`${e}.${p}`,o,t,i+1)}}};var w=class{ruleName="ImportExistence";async validateAsync(e,n){let t=[];if(!e.metadata?.imports)return t;let i=await n.getAllDocumentsAsync();for(let[r,o]of Object.entries(e.metadata.imports))for(let p of o)if(!await n.getHighestCompatibleVersionAsync(r,p)){let s=await this.determineImportErrorAsync(n,r,p,i),c=new g;c.ruleType=this.ruleName,c.severity="Error",c.message=s.message,c.suggestion=s.suggestion,c.entityName=`Import: ${r}/${p.packageName}`,c.actualValue=p.toString(),c.expectedValue=s.expectedValue,t.push(c)}return t}async determineImportErrorAsync(e,n,t,i){let r=await e.getDocumentsByNamespaceAsync(n,t.packageName);if(r.length===0){let s=i.filter(y=>y.metadata.namespace_?.publisher===n).map(y=>y.metadata.namespace_.package_).filter((y,u,f)=>f.indexOf(y)===u),c=this.findSimilarPackages(t.packageName,s),l=`Import '${n}/${t.package_}' not found - package does not exist`,m=c.length>0?`Did you mean: ${c.slice(0,3).join(", ")}?`:s.length>0?`Available packages in ${n}: ${s.slice(0,5).join(", ")}`:`No packages found for publisher '${n}'. Verify the publisher name is correct.`;return{message:l,suggestion:m,expectedValue:"Existing package"}}let p=r.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),a=this.getAcceptableVersionRange(t);return{message:`Import '${n}/${t.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${p}. Required: ${a}`,expectedValue:a}}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,n){if(n.length===0)return[];let t=n.filter(o=>o.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(o.toLowerCase()));if(t.length>0)return t.sort((o,p)=>o.length-p.length);let i=n.map(o=>({package:o,distance:this.levenshteinDistance(e.toLowerCase(),o.toLowerCase())})).sort((o,p)=>o.distance-p.distance),r=Math.max(3,Math.floor(e.length*.4));return i.filter(o=>o.distance<=r).map(o=>o.package)}levenshteinDistance(e,n){if(!e||e.length===0)return n?.length??0;if(!n||n.length===0)return e.length;let t=e.length,i=n.length,r=Array(t+1).fill(null).map(()=>Array(i+1).fill(0));for(let o=0;o<=t;o++)r[o][0]=o;for(let o=0;o<=i;o++)r[0][o]=o;for(let o=1;o<=t;o++)for(let p=1;p<=i;p++){let a=e[o-1]===n[p-1]?0:1;r[o][p]=Math.min(Math.min(r[o-1][p]+1,r[o][p-1]+1),r[o-1][p-1]+a)}return r[t][i]}};var Y=class h{constructor(e,n,t,i){this.publisher=e;this.package_=n;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 n=e.split("@");if(n.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let t=n[0],i=n[1],r=t.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${t}. Expected format: publisher/package/name`);let o=i.split(".").map(Number),p={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:a=>!a||typeof a!="object"?!1:a.major===(o[0]||0)&&a.minor===(o[1]||0)&&a.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:a=>(o[0]||0)!==a.major?(o[0]||0)-a.major:(o[1]||0)!==a.minor?(o[1]||0)-a.minor:(o[2]||0)-a.patch};return new h(r[0],r[1],r[2],p)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}};function k(h){if(Array.isArray(h))return h.map(n=>n?.toString()??"").filter(n=>n.length>0);let e=h?.toString();return e?[e]:[]}var V=class{cache=new Map;repository;logger;constructor(e,n){this.repository=e,this.logger=n}async resolveEntityAsync(e,n){let t=n.metadata?.namespace_?.toString()??"unknown",i=this.cache.get(t);if(i){let o=i.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(n,new Set,"");return this.cache.set(t,r),r.get(e)??null}async resolveAllEntitiesAsync(e,n){let t=await this.buildAllEntitiesIndexAsync(n,new Set,"");if(e.includes(".")){let i=e.split("."),r=i[0],o=i[1],p=await this.findDocumentForAlias(n,r);return p?await this.resolveAllEntitiesAsync(o,p):[]}return t.filter(i=>i.entityName===e)}async buildAllEntitiesIndexAsync(e,n,t){let i=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),n.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),i;n.add(r);let o=t.length===0?r:`${t} \u2192 ${r}`;for(let[p,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){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:p,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,p,s),entity:a,definedInNamespace:r,isImported:t.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${i.length} entities from ${r}`),e.metadata?.imports){let p=Object.values(e.metadata.imports).reduce((a,s)=>a+s.length,0);this.logger?.debug?.(`Processing ${p} import(s) for ${r}`);for(let[a,s]of Object.entries(e.metadata.imports))for(let c of s)try{this.logger?.debug?.(`Resolving import: ${a}/${c.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(a,c);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,n,o);i.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${c.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${a}/${c.packageName} for namespace ${r}. Error: ${m.message}`,m),new Error(`Failed to process import ${a}/${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,n,t){let i=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),n.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),i;n.add(r);let o=t.length===0?r:`${t} \u2192 ${r}`,p=0;for(let[a,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)&&!i.has(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};i.set(a,{entityName:a,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:s,definedInNamespace:r,isImported:t.length>0,importPath:o}),p++}if(this.logger?.debug?.(`Indexed ${p} entities from ${r}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${a} 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 m=await this.repository.getHighestCompatibleVersionAsync(s,l);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,n,o),u=0;for(let[f,d]of y.entries())if(i.has(f)||(i.set(f,d),u++),l.alias&&!f.includes(".")){let R=`${l.alias}.${f}`;i.has(R)||(i.set(R,d),u++)}this.logger?.debug?.(`Merged ${u} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${l.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${s}/${l.packageName} for namespace ${r}. Error: ${y.message}`,y),new Error(`Failed to process import ${s}/${l.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return i}async findDocumentForAlias(e,n){if(!e.metadata?.imports)return null;for(let[t,i]of Object.entries(e.metadata.imports))for(let r of i){if(r.alias===n)return await this.repository.getHighestCompatibleVersionAsync(t,r);if(!r.alias&&r.packageName===n)return await this.repository.getHighestCompatibleVersionAsync(t,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,n,t){if(e===n)return!0;let i=new Set;return await this.isSubclassOfRecursiveAsync(e,n,t,i)}async isSubclassOfRecursiveAsync(e,n,t,i){if(i.has(e))return!1;i.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let p=k(o);for(let a of p)if(a===n||await this.isSubclassOfRecursiveAsync(a,n,t,i))return!0}return!1}async isSubpropertyOfAsync(e,n,t){if(e===n)return!0;let i=new Set;return await this.isSubpropertyOfRecursiveAsync(e,n,t,i)}async isSubpropertyOfRecursiveAsync(e,n,t,i){if(i.has(e))return!1;i.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let p=k(o);for(let a of p)if(a===n||await this.isSubpropertyOfRecursiveAsync(a,n,t,i))return!0}return!1}};var j=class{ruleName="UnresolvedReference";async validateAsync(e,n){let t=[],i=new V(n),r=await i.buildEntityIndexAsync(e),o=new Set;for(let[p,a]of r.entries()){let s=a.entity.type;if(s){let c=s.toString();(c==="ObjectProperty"||c.endsWith(".ObjectProperty"))&&o.add(p)}}for(let[p,a]of Object.entries(e.body)){if(!a||typeof a!="object"||Array.isArray(a))continue;let s=a,c=this.getPropertyValue(s,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[l,m]of Object.entries(s))l==="type"||l==="label"||l==="comment"||!(o.has(l)||Array.from(o).some(u=>u.endsWith(`.${l}`)))||await this.validateReferenceValue(p,l,m,e,i,t)}return t}async validateReferenceValue(e,n,t,i,r,o){if(t!=null){if(typeof t=="string")await r.resolveEntityAsync(t,i)||o.push(this.createUnresolvedReferenceError(e,n,t));else if(Array.isArray(t))for(let p=0;p<t.length;p++){let a=t[p];typeof a=="string"&&(await r.resolveEntityAsync(a,i)||o.push(this.createUnresolvedReferenceError(e,`${n}[${p}]`,a)))}}}createUnresolvedReferenceError(e,n,t){let i=`The entity '${t}' cannot be found in the current document or any imported namespaces.
|
|
9
|
+
Example: If the parent property is 'hasCharacter' with range 'Character', all embedded objects in that property will be typed as 'Character' automatically.`,c.expectedValue="No explicit type (inferred from parent property's range)",t.push(c)}if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(let a=0;a<o.length;a++){let s=o[a];typeof s=="object"&&s!==null&&!Array.isArray(s)&&this.checkForEmbeddedTypeViolations(`${e}.${p}[${a}]`,s,t,i+1)}else this.checkForEmbeddedTypeViolations(`${e}.${p}`,o,t,i+1)}}};var w=class{ruleName="ImportExistence";async validateAsync(e,n){let t=[];if(!e.metadata?.imports)return t;let i=await n.getAllDocumentsAsync();for(let[r,o]of Object.entries(e.metadata.imports))for(let p of o)if(!await n.getHighestCompatibleVersionAsync(r,p)){let s=await this.determineImportErrorAsync(n,r,p,i),c=new g;c.ruleType=this.ruleName,c.severity="Error",c.message=s.message,c.suggestion=s.suggestion,c.entityName=`Import: ${r}/${p.packageName}`,c.actualValue=p.toString(),c.expectedValue=s.expectedValue,t.push(c)}return t}async determineImportErrorAsync(e,n,t,i){let r=await e.getDocumentsByNamespaceAsync(n,t.packageName);if(r.length===0){let s=i.filter(y=>y.metadata.namespace_?.publisher===n).map(y=>y.metadata.namespace_.package_).filter((y,u,f)=>f.indexOf(y)===u),c=this.findSimilarPackages(t.packageName,s),l=`Import '${n}/${t.package_}' not found - package does not exist`,m=c.length>0?`Did you mean: ${c.slice(0,3).join(", ")}?`:s.length>0?`Available packages in ${n}: ${s.slice(0,5).join(", ")}`:`No packages found for publisher '${n}'. Verify the publisher name is correct.`;return{message:l,suggestion:m,expectedValue:"Existing package"}}let p=r.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),a=this.getAcceptableVersionRange(t);return{message:`Import '${n}/${t.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${p}. Required: ${a}`,expectedValue:a}}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,n){if(n.length===0)return[];let t=n.filter(o=>o.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(o.toLowerCase()));if(t.length>0)return t.sort((o,p)=>o.length-p.length);let i=n.map(o=>({package:o,distance:this.levenshteinDistance(e.toLowerCase(),o.toLowerCase())})).sort((o,p)=>o.distance-p.distance),r=Math.max(3,Math.floor(e.length*.4));return i.filter(o=>o.distance<=r).map(o=>o.package)}levenshteinDistance(e,n){if(!e||e.length===0)return n?.length??0;if(!n||n.length===0)return e.length;let t=e.length,i=n.length,r=Array(t+1).fill(null).map(()=>Array(i+1).fill(0));for(let o=0;o<=t;o++)r[o][0]=o;for(let o=0;o<=i;o++)r[0][o]=o;for(let o=1;o<=t;o++)for(let p=1;p<=i;p++){let a=e[o-1]===n[p-1]?0:1;r[o][p]=Math.min(Math.min(r[o-1][p]+1,r[o][p-1]+1),r[o-1][p-1]+a)}return r[t][i]}};var Y=class h{constructor(e,n,t,i){this.publisher=e;this.package_=n;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 n=e.split("@");if(n.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let t=n[0],i=n[1],r=t.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${t}. Expected format: publisher/package/name`);let o=i.split(".").map(Number),p={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:a=>!a||typeof a!="object"?!1:a.major===(o[0]||0)&&a.minor===(o[1]||0)&&a.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:a=>(o[0]||0)!==a.major?(o[0]||0)-a.major:(o[1]||0)!==a.minor?(o[1]||0)-a.minor:(o[2]||0)-a.patch};return new h(r[0],r[1],r[2],p)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}};function v(h){if(Array.isArray(h))return h.map(n=>n?.toString()??"").filter(n=>n.length>0);let e=h?.toString();return e?[e]:[]}var V=class{cache=new Map;repository;logger;constructor(e,n){this.repository=e,this.logger=n}async resolveEntityAsync(e,n){let t=n.metadata?.namespace_?.toString()??"unknown",i=this.cache.get(t);if(i){let o=i.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(n,new Set,"");return this.cache.set(t,r),r.get(e)??null}async resolveAllEntitiesAsync(e,n){let t=await this.buildAllEntitiesIndexAsync(n,new Set,"");if(e.includes(".")){let i=e.split("."),r=i[0],o=i[1],p=await this.findDocumentForAlias(n,r);return p?await this.resolveAllEntitiesAsync(o,p):[]}return t.filter(i=>i.entityName===e)}async buildAllEntitiesIndexAsync(e,n,t){let i=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),n.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),i;n.add(r);let o=t.length===0?r:`${t} \u2192 ${r}`;for(let[p,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){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:p,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,p,s),entity:a,definedInNamespace:r,isImported:t.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${i.length} entities from ${r}`),e.metadata?.imports){let p=Object.values(e.metadata.imports).reduce((a,s)=>a+s.length,0);this.logger?.debug?.(`Processing ${p} import(s) for ${r}`);for(let[a,s]of Object.entries(e.metadata.imports))for(let c of s)try{this.logger?.debug?.(`Resolving import: ${a}/${c.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(a,c);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,n,o);i.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${c.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${a}/${c.packageName} for namespace ${r}. Error: ${m.message}`,m),new Error(`Failed to process import ${a}/${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,n,t){let i=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),n.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),i;n.add(r);let o=t.length===0?r:`${t} \u2192 ${r}`,p=0;for(let[a,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)&&!i.has(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};i.set(a,{entityName:a,uri:new Y(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:s,definedInNamespace:r,isImported:t.length>0,importPath:o}),p++}if(this.logger?.debug?.(`Indexed ${p} entities from ${r}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${a} 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 m=await this.repository.getHighestCompatibleVersionAsync(s,l);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,n,o),u=0;for(let[f,d]of y.entries())if(i.has(f)||(i.set(f,d),u++),l.alias&&!f.includes(".")){let R=`${l.alias}.${f}`;i.has(R)||(i.set(R,d),u++)}this.logger?.debug?.(`Merged ${u} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${l.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${s}/${l.packageName} for namespace ${r}. Error: ${y.message}`,y),new Error(`Failed to process import ${s}/${l.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return i}async findDocumentForAlias(e,n){if(!e.metadata?.imports)return null;for(let[t,i]of Object.entries(e.metadata.imports))for(let r of i){if(r.alias===n)return await this.repository.getHighestCompatibleVersionAsync(t,r);if(!r.alias&&r.packageName===n)return await this.repository.getHighestCompatibleVersionAsync(t,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,n,t){if(e===n)return!0;let i=new Set;return await this.isSubclassOfRecursiveAsync(e,n,t,i)}async isSubclassOfRecursiveAsync(e,n,t,i){if(i.has(e))return!1;i.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let p=v(o);for(let a of p)if(a===n||await this.isSubclassOfRecursiveAsync(a,n,t,i))return!0}return!1}async isSubpropertyOfAsync(e,n,t){if(e===n)return!0;let i=new Set;return await this.isSubpropertyOfRecursiveAsync(e,n,t,i)}async isSubpropertyOfRecursiveAsync(e,n,t,i){if(i.has(e))return!1;i.add(e);let r=await this.resolveEntityAsync(e,t);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let p=v(o);for(let a of p)if(a===n||await this.isSubpropertyOfRecursiveAsync(a,n,t,i))return!0}return!1}};var j=class{ruleName="UnresolvedReference";async validateAsync(e,n){let t=[],i=new V(n),r=await i.buildEntityIndexAsync(e),o=new Set;for(let[p,a]of r.entries()){let s=a.entity.type;if(s){let c=s.toString();(c==="ObjectProperty"||c.endsWith(".ObjectProperty"))&&o.add(p)}}for(let[p,a]of Object.entries(e.body)){if(!a||typeof a!="object"||Array.isArray(a))continue;let s=a,c=this.getPropertyValue(s,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[l,m]of Object.entries(s))l==="type"||l==="label"||l==="comment"||!(o.has(l)||Array.from(o).some(u=>u.endsWith(`.${l}`)))||await this.validateReferenceValue(p,l,m,e,i,t)}return t}async validateReferenceValue(e,n,t,i,r,o){if(t!=null){if(typeof t=="string")await r.resolveEntityAsync(t,i)||o.push(this.createUnresolvedReferenceError(e,n,t));else if(Array.isArray(t))for(let p=0;p<t.length;p++){let a=t[p];typeof a=="string"&&(await r.resolveEntityAsync(a,i)||o.push(this.createUnresolvedReferenceError(e,`${n}[${p}]`,a)))}}}createUnresolvedReferenceError(e,n,t){let i=`The entity '${t}' cannot be found in the current document or any imported namespaces.
|
|
10
10
|
|
|
11
11
|
Possible solutions:
|
|
12
12
|
\u2022 Add import if the entity is defined in another namespace:
|
|
13
13
|
kanonak namespace add-import <publisher>/<package>@<version>
|
|
14
14
|
\u2022 Check for typos in the reference name '${t}'
|
|
15
15
|
\u2022 Define '${t}' in the current namespace or an appropriate namespace
|
|
16
|
-
\u2022 Use 'kanonak search type ${t} --include-imports' to locate the entity`,r=new g;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,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,n){let t=e[n];return t?t.toString():null}};var S=class{ruleName="TypeAmbiguity";async validateAsync(e,n){let t=[],i=new Map,r=[];if(e.metadata?.imports)for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){r.push({doc:s,import:a,publisher:o});let c=await this.getTransitiveImportsAsync(n,s,new Set);r.push(...c.map(l=>({doc:l,import:null,publisher:o})))}}for(let{doc:o,import:p}of r){let a=o.metadata?.namespace_?.toString()??"unknown";for(let s of Object.keys(o.body))i.has(s)||i.set(s,[]),i.get(s).push({namespace:a,import:p})}for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p;this.checkAmbiguousReference(a,"type",i,o,t),this.checkAmbiguousReference(a,"subClassOf",i,o,t),this.checkAmbiguousReference(a,"subPropertyOf",i,o,t),this.checkAmbiguousReference(a,"domain",i,o,t),this.checkAmbiguousReference(a,"range",i,o,t)}return t}checkAmbiguousReference(e,n,t,i,r){let o=e[n];if(!o)return;let p=k(o);for(let a of p){if(a.includes("."))continue;let s=t.get(a);if(s&&s.length>1){let c=s.map(u=>u.namespace).join(", "),l=[];for(let{namespace:u,import:f}of s)if(f?.alias)l.push(`${f.alias}.${a}`);else{let d=u.split("/"),v=d[d.length-1]?.split("@")[0]??"alias";l.push(`${v}.${a}`)}let m=l.length>0?`Use one of: ${l.join(", ")}`:"Consider adding namespace aliases to your imports",y=new g;y.ruleType=this.ruleName,y.severity="Warning",y.entityName=i,y.propertyName=n,y.actualValue=a,y.message=`Type '${a}' is ambiguous. It's defined in: ${c}`,y.suggestion=m,r.push(y)}}}async getTransitiveImportsAsync(e,n,t){let i=[],r=n.metadata?.namespace_?.toString()??"";if(t.has(r))return i;if(t.add(r),n.metadata?.imports)for(let[o,p]of Object.entries(n.metadata.imports))for(let a of p){let s=await e.getHighestCompatibleVersionAsync(o,a);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,n){let t=[],i=new Map,r=new Set;await this.buildClassHierarchy(e,n,i,r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p,s=a.type,c=a.subClassOf;if(s?.toString()==="Class"&&c){let l=o,m=this.detectCycle(l,i);if(m){let y=m.join(" \u2192 "),u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Circular class hierarchy detected: ${y}`,u.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",u.entityName=l,u.propertyName="subClassOf",u.actualValue=y,t.push(u);break}}}return t}async buildClassHierarchy(e,n,t,i){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&i.has(r))){r&&i.add(r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p,s=a.type,c=a.subClassOf;if(s?.toString()==="Class"&&c){let l=k(c);l.length>0&&t.set(o,l)}}if(e.metadata?.imports)for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);s&&await this.buildClassHierarchy(s,n,t,i)}}}detectCycle(e,n){let t=[],i=new Set;return this.detectCycleRecursive(e,n,t,i)}detectCycleRecursive(e,n,t,i){if(t.includes(e)){let o=t.indexOf(e),p=t.slice(o);return p.push(e),p}if(i.has(e))return null;t.push(e),i.add(e);let r=n.get(e);if(r)for(let o of r){let p=this.detectCycleRecursive(o,n,t,i);if(p)return p}return t.pop(),null}};var K=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,n){let t=[],i=new Map,r=new Set;await this.buildPropertyHierarchy(e,n,i,r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)&&p.subPropertyOf){let c=o,l=this.detectCycle(c,i);if(l){let m=l.join(" \u2192 "),y=new g;y.ruleType=this.ruleName,y.severity="Error",y.message=`Circular property hierarchy detected: ${m}`,y.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",y.entityName=c,y.propertyName="subPropertyOf",y.actualValue=m,t.push(y);break}}return t}async buildPropertyHierarchy(e,n,t,i){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&i.has(r))){r&&i.add(r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p,s=a.type;if(s){let c=s.toString();if(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty"){let l=a.subPropertyOf;if(l){let m=k(l);m.length>0&&t.set(o,m)}}}}if(e.metadata?.imports)for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);s&&await this.buildPropertyHierarchy(s,n,t,i)}}}detectCycle(e,n){let t=[],i=new Set;return this.detectCycleRecursive(e,n,t,i)}detectCycleRecursive(e,n,t,i){if(t.includes(e)){let o=t.indexOf(e),p=t.slice(o);return p.push(e),p}if(i.has(e))return null;t.push(e),i.add(e);let r=n.get(e);if(r)for(let o of r){let p=this.detectCycleRecursive(o,n,t,i);if(p)return p}return t.pop(),null}};var C=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,n){let t=[];for(let[i,r]of Object.entries(e.body)){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r,p=o.type?.toString();if(p==="DatatypeProperty"||p==="ObjectProperty"||p?.endsWith(".DatatypeProperty")||p?.endsWith(".ObjectProperty")){let a="range"in o,s=o.range?.toString().trim();if(!a||!s){let c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName="range",c.message=`Property '${i}' must have a 'range' defined.`,c.suggestion=p==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",c.expectedValue=p==="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,n){let t=[],i=new Set;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=o.type?.toString();(a==="Class"||a&&a.endsWith(".Class"))&&i.add(r)}for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=k(o.subClassOf);for(let s=0;s<a.length;s++){let c=a[s];if(this.builtInClasses.has(c)||i.has(c))continue;if(!await this.isClassAvailableInImports(e,n,c)){let m=a.length>1?`[${s}]`:"",y=new g;y.ruleType=this.ruleName,y.severity="Error",y.message=`Class '${c}' referenced in subClassOf${m} is not defined or imported`,y.suggestion=`Define '${c}' as a Class, or import a namespace that contains it`,y.entityName=r,y.propertyName="subClassOf",y.actualValue=c,y.expectedValue="Defined or imported class",t.push(y)}}}return t}async isClassAvailableInImports(e,n,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let o=t.split(".",2);i=o[0],r=o[1]}for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){if(i!==null&&a.alias!==i)continue;let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let u=l.type?.toString();if(u==="Class"||u&&u.endsWith(".Class"))return!0}let m=new Set;if(await this.isClassAvailableInImportsRecursive(s,n,c,m))return!0}}return!1}async isClassAvailableInImportsRecursive(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let m=c.type?.toString();if(m==="Class"||m&&m.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(s,n,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,n){let t=[],i=new Set;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=o.type?.toString();(a==="DatatypeProperty"||a==="ObjectProperty"||a==="AnnotationProperty")&&i.add(r)}for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=k(o.subPropertyOf);for(let s=0;s<a.length;s++){let c=a[s];if(this.builtInProperties.has(c)||i.has(c))continue;if(!await this.isPropertyAvailableInImports(e,n,c)){let m=a.length>1?`[${s}]`:"",y=new g;y.ruleType=this.ruleName,y.severity="Error",y.message=`Property '${c}' referenced in subPropertyOf${m} is not defined or imported`,y.suggestion=`Define '${c}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,y.entityName=r,y.propertyName="subPropertyOf",y.actualValue=c,y.expectedValue="Defined or imported property",t.push(y)}}}return t}async isPropertyAvailableInImports(e,n,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let o=t.split(".",2);i=o[0],r=o[1]}for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){if(i!==null&&a.alias!==i)continue;let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let u=l.type?.toString();if(u==="DatatypeProperty"||u==="ObjectProperty"||u==="AnnotationProperty")return!0}let m=new Set;if(await this.isPropertyAvailableInImportsRecursive(s,n,c,m))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let m=c.type?.toString();if(m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(s,n,t,i))return!0}}return!1}};var _=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,n){let t=[],i=e.metadata.namespace_?.toString();if(!i)return t;let r=new Map,o=new Set;await this.buildImportGraph(e,n,r,o);let p=this.detectCycle(i,r);if(p){let a=p.join(" \u2192 "),s=new g;s.ruleType=this.ruleName,s.severity="Error",s.message=`Circular namespace import detected: ${a}`,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=a,t.push(s)}return t}async buildImportGraph(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(!(!r||i.has(r))&&(i.add(r),e.metadata.imports)){let o=[];for(let[p,a]of Object.entries(e.metadata.imports))for(let s of a){let c=`${p}/${s.packageName}@${s.version}`;o.push(c);let l=await n.getHighestCompatibleVersionAsync(p,s);l&&await this.buildImportGraph(l,n,t,i)}o.length>0&&t.set(r,o)}}detectCycle(e,n){let t=[],i=new Set;return this.detectCycleRecursive(e,n,t,i)}detectCycleRecursive(e,n,t,i){let r=t.indexOf(e);if(r>=0){let p=t.slice(r);return p.push(e),p}if(i.has(e))return null;t.push(e),i.add(e);let o=n.get(e);if(o)for(let p of o){let a=this.detectCycleRecursive(p,n,t,i);if(a)return a}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,n){let t=[],i=new Set;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=o.type?.toString();this.isPropertyType(a)&&i.add(r)}for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let p=o,a=p.type?.toString();if(this.isPropertyType(a)||this.isClassType(a))continue;for(let[s,c]of Object.entries(p)){if(!s||this.metadataKeys.has(s))continue;let l=s,m=null;if(s.includes(".")){let u=s.lastIndexOf(".");m=s.substring(0,u),l=s.substring(u+1)}if(i.has(l))continue;if(!await this.isPropertyAvailableInImports(e,n,l,m)){let u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Property '${s}' is not defined or imported`,u.suggestion=m?`The property '${l}' is not found in the imported namespace with alias '${m}'.
|
|
16
|
+
\u2022 Use 'kanonak search type ${t} --include-imports' to locate the entity`,r=new g;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,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,n){let t=e[n];return t?t.toString():null}};var S=class{ruleName="TypeAmbiguity";async validateAsync(e,n){let t=[],i=new Map,r=[];if(e.metadata?.imports)for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){r.push({doc:s,import:a,publisher:o});let c=await this.getTransitiveImportsAsync(n,s,new Set);r.push(...c.map(l=>({doc:l,import:null,publisher:o})))}}for(let{doc:o,import:p}of r){let a=o.metadata?.namespace_?.toString()??"unknown";for(let s of Object.keys(o.body))i.has(s)||i.set(s,[]),i.get(s).push({namespace:a,import:p})}for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p;this.checkAmbiguousReference(a,"type",i,o,t),this.checkAmbiguousReference(a,"subClassOf",i,o,t),this.checkAmbiguousReference(a,"subPropertyOf",i,o,t),this.checkAmbiguousReference(a,"domain",i,o,t),this.checkAmbiguousReference(a,"range",i,o,t)}return t}checkAmbiguousReference(e,n,t,i,r){let o=e[n];if(!o)return;let p=v(o);for(let a of p){if(a.includes("."))continue;let s=t.get(a);if(s&&s.length>1){let c=s.map(u=>u.namespace).join(", "),l=[];for(let{namespace:u,import:f}of s)if(f?.alias)l.push(`${f.alias}.${a}`);else{let d=u.split("/"),k=d[d.length-1]?.split("@")[0]??"alias";l.push(`${k}.${a}`)}let m=l.length>0?`Use one of: ${l.join(", ")}`:"Consider adding namespace aliases to your imports",y=new g;y.ruleType=this.ruleName,y.severity="Warning",y.entityName=i,y.propertyName=n,y.actualValue=a,y.message=`Type '${a}' is ambiguous. It's defined in: ${c}`,y.suggestion=m,r.push(y)}}}async getTransitiveImportsAsync(e,n,t){let i=[],r=n.metadata?.namespace_?.toString()??"";if(t.has(r))return i;if(t.add(r),n.metadata?.imports)for(let[o,p]of Object.entries(n.metadata.imports))for(let a of p){let s=await e.getHighestCompatibleVersionAsync(o,a);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,n){let t=[],i=new Map,r=new Set;await this.buildClassHierarchy(e,n,i,r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p,s=a.type,c=a.subClassOf;if(s?.toString()==="Class"&&c){let l=o,m=this.detectCycle(l,i);if(m){let y=m.join(" \u2192 "),u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Circular class hierarchy detected: ${y}`,u.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",u.entityName=l,u.propertyName="subClassOf",u.actualValue=y,t.push(u);break}}}return t}async buildClassHierarchy(e,n,t,i){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&i.has(r))){r&&i.add(r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p,s=a.type,c=a.subClassOf;if(s?.toString()==="Class"&&c){let l=v(c);l.length>0&&t.set(o,l)}}if(e.metadata?.imports)for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);s&&await this.buildClassHierarchy(s,n,t,i)}}}detectCycle(e,n){let t=[],i=new Set;return this.detectCycleRecursive(e,n,t,i)}detectCycleRecursive(e,n,t,i){if(t.includes(e)){let o=t.indexOf(e),p=t.slice(o);return p.push(e),p}if(i.has(e))return null;t.push(e),i.add(e);let r=n.get(e);if(r)for(let o of r){let p=this.detectCycleRecursive(o,n,t,i);if(p)return p}return t.pop(),null}};var C=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,n){let t=[],i=new Map,r=new Set;await this.buildPropertyHierarchy(e,n,i,r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)&&p.subPropertyOf){let c=o,l=this.detectCycle(c,i);if(l){let m=l.join(" \u2192 "),y=new g;y.ruleType=this.ruleName,y.severity="Error",y.message=`Circular property hierarchy detected: ${m}`,y.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",y.entityName=c,y.propertyName="subPropertyOf",y.actualValue=m,t.push(y);break}}return t}async buildPropertyHierarchy(e,n,t,i){let r=e.metadata?.namespace_?.toString()??"";if(!(r&&i.has(r))){r&&i.add(r);for(let[o,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)){let a=p,s=a.type;if(s){let c=s.toString();if(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty"){let l=a.subPropertyOf;if(l){let m=v(l);m.length>0&&t.set(o,m)}}}}if(e.metadata?.imports)for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);s&&await this.buildPropertyHierarchy(s,n,t,i)}}}detectCycle(e,n){let t=[],i=new Set;return this.detectCycleRecursive(e,n,t,i)}detectCycleRecursive(e,n,t,i){if(t.includes(e)){let o=t.indexOf(e),p=t.slice(o);return p.push(e),p}if(i.has(e))return null;t.push(e),i.add(e);let r=n.get(e);if(r)for(let o of r){let p=this.detectCycleRecursive(o,n,t,i);if(p)return p}return t.pop(),null}};var K=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,n){let t=[];for(let[i,r]of Object.entries(e.body)){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r,p=o.type?.toString();if(p==="DatatypeProperty"||p==="ObjectProperty"||p?.endsWith(".DatatypeProperty")||p?.endsWith(".ObjectProperty")){let a="range"in o,s=o.range?.toString().trim();if(!a||!s){let c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName="range",c.message=`Property '${i}' must have a 'range' defined.`,c.suggestion=p==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",c.expectedValue=p==="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,n){let t=[],i=new Set;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=o.type?.toString();(a==="Class"||a&&a.endsWith(".Class"))&&i.add(r)}for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=v(o.subClassOf);for(let s=0;s<a.length;s++){let c=a[s];if(this.builtInClasses.has(c)||i.has(c))continue;if(!await this.isClassAvailableInImports(e,n,c)){let m=a.length>1?`[${s}]`:"",y=new g;y.ruleType=this.ruleName,y.severity="Error",y.message=`Class '${c}' referenced in subClassOf${m} is not defined or imported`,y.suggestion=`Define '${c}' as a Class, or import a namespace that contains it`,y.entityName=r,y.propertyName="subClassOf",y.actualValue=c,y.expectedValue="Defined or imported class",t.push(y)}}}return t}async isClassAvailableInImports(e,n,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let o=t.split(".",2);i=o[0],r=o[1]}for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){if(i!==null&&a.alias!==i)continue;let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let u=l.type?.toString();if(u==="Class"||u&&u.endsWith(".Class"))return!0}let m=new Set;if(await this.isClassAvailableInImportsRecursive(s,n,c,m))return!0}}return!1}async isClassAvailableInImportsRecursive(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let m=c.type?.toString();if(m==="Class"||m&&m.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(s,n,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,n){let t=[],i=new Set;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=o.type?.toString();(a==="DatatypeProperty"||a==="ObjectProperty"||a==="AnnotationProperty")&&i.add(r)}for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=v(o.subPropertyOf);for(let s=0;s<a.length;s++){let c=a[s];if(this.builtInProperties.has(c)||i.has(c))continue;if(!await this.isPropertyAvailableInImports(e,n,c)){let m=a.length>1?`[${s}]`:"",y=new g;y.ruleType=this.ruleName,y.severity="Error",y.message=`Property '${c}' referenced in subPropertyOf${m} is not defined or imported`,y.suggestion=`Define '${c}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,y.entityName=r,y.propertyName="subPropertyOf",y.actualValue=c,y.expectedValue="Defined or imported property",t.push(y)}}}return t}async isPropertyAvailableInImports(e,n,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let o=t.split(".",2);i=o[0],r=o[1]}for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){if(i!==null&&a.alias!==i)continue;let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let u=l.type?.toString();if(u==="DatatypeProperty"||u==="ObjectProperty"||u==="AnnotationProperty")return!0}let m=new Set;if(await this.isPropertyAvailableInImportsRecursive(s,n,c,m))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let m=c.type?.toString();if(m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(s,n,t,i))return!0}}return!1}};var _=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,n){let t=[],i=e.metadata.namespace_?.toString();if(!i)return t;let r=new Map,o=new Set;await this.buildImportGraph(e,n,r,o);let p=this.detectCycle(i,r);if(p){let a=p.join(" \u2192 "),s=new g;s.ruleType=this.ruleName,s.severity="Error",s.message=`Circular namespace import detected: ${a}`,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=a,t.push(s)}return t}async buildImportGraph(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(!(!r||i.has(r))&&(i.add(r),e.metadata.imports)){let o=[];for(let[p,a]of Object.entries(e.metadata.imports))for(let s of a){let c=`${p}/${s.packageName}@${s.version}`;o.push(c);let l=await n.getHighestCompatibleVersionAsync(p,s);l&&await this.buildImportGraph(l,n,t,i)}o.length>0&&t.set(r,o)}}detectCycle(e,n){let t=[],i=new Set;return this.detectCycleRecursive(e,n,t,i)}detectCycleRecursive(e,n,t,i){let r=t.indexOf(e);if(r>=0){let p=t.slice(r);return p.push(e),p}if(i.has(e))return null;t.push(e),i.add(e);let o=n.get(e);if(o)for(let p of o){let a=this.detectCycleRecursive(p,n,t,i);if(a)return a}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,n){let t=[],i=new Set;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let a=o.type?.toString();this.isPropertyType(a)&&i.add(r)}for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let p=o,a=p.type?.toString();if(this.isPropertyType(a)||this.isClassType(a))continue;for(let[s,c]of Object.entries(p)){if(!s||this.metadataKeys.has(s))continue;let l=s,m=null;if(s.includes(".")){let u=s.lastIndexOf(".");m=s.substring(0,u),l=s.substring(u+1)}if(i.has(l))continue;if(!await this.isPropertyAvailableInImports(e,n,l,m)){let u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Property '${s}' is not defined or imported`,u.suggestion=m?`The property '${l}' is not found in the imported namespace with alias '${m}'.
|
|
17
17
|
1. Verify the namespace is imported with the correct alias
|
|
18
18
|
2. Check if the property name is spelled correctly
|
|
19
19
|
3. Ensure the imported namespace version contains this property`:`The property '${s}' is not defined in this namespace or any imported namespace.
|
|
@@ -34,14 +34,14 @@ ${c}`,y.expectedValue="Unambiguous reference (use namespace alias to disambiguat
|
|
|
34
34
|
2. Import the namespace that contains '${l}', OR
|
|
35
35
|
3. Use a qualified reference like 'alias.${l}' if already imported with an alias`:`For DatatypeProperty:
|
|
36
36
|
1. Use a primitive type (string, integer, boolean, dateTime, etc.), OR
|
|
37
|
-
2. If '${l}' should be a class, change property type to ObjectProperty`,u.entityName=r,u.propertyName="range",u.actualValue=l,u.expectedValue=y==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",t.push(u)}}}return t}async isTypeAvailableInImports(e,n,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let o=t.split(".",2);i=o[0],r=o[1]}for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){if(i!==null&&a.alias!==i)continue;let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let u=l.type?.toString();if(this.isValidRangeTargetType(u))return!0}let m=new Set;if(await this.isTypeAvailableInImportsRecursive(s,n,c,m))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let m=c.type?.toString();if(this.isValidRangeTargetType(m))return!0}if(await this.isTypeAvailableInImportsRecursive(s,n,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,n){let t=[],i=new Map,r=new V(n);await r.buildEntityIndexAsync(e);for(let[o,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let a=p,s=!1,c=a.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=a.range,m=[];if(Array.isArray(l))for(let y of l){let u=y?.toString();u&&m.push(u)}else{let y=l?.toString();y&&m.push(y)}for(let y of m)this.xsdTypes.has(y)||(i.has(y)||i.set(y,[]),i.get(y).push(o))}}for(let[o,p]of i)if(!await r.resolveEntityAsync(o,e))for(let s of p){let c=new g;c.ruleType=this.ruleName,c.severity="Warning",c.message=`ObjectProperty references class '${o}' which may not be imported`,c.suggestion=`Ensure the namespace containing '${o}' is imported, or define '${o}' in this document`,c.entityName=s,c.propertyName="range",c.actualValue=o,t.push(c)}return t}};var J=class h{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"&&h.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 n=e.includes(".")?e.split(".")[1]:e;return h.KNOWN_XSD_DATATYPES.has(n.toLowerCase())}async isClassTypeAsync(e,n){if(this.isKnownXsdDatatypeName(e))return!1;let t=await this.resourceResolver.resolveEntityAsync(e,n);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,n){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(n)||e==="Property"&&this.isLiteralType(n))}isEffectiveObjectProperty(e,n){return!!(e==="ObjectProperty"||e==="Property"&&n&&!this.isXsdDatatype(n)&&!this.isLiteralType(n))}};var q=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"ObjectPropertyValue"}async validateAsync(e,n){let t=[],i=new V(n),r=new J(i),o=await i.buildEntityIndexAsync(e),p=await this.buildPropertyMetadataAsync(e,n,i,o);for(let[a,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&await this.scanEntityForObjectProperties(s,a,"",p,i,r,e,t);return t}async scanEntityForObjectProperties(e,n,t,i,r,o,p,a){for(let[s,c]of Object.entries(e)){if(this.standardProperties.has(s))continue;let l=s,m=s.lastIndexOf(".");m>0&&m<s.length-1&&(l=s.substring(m+1));let y=i.get(l);if(y&&o.isEffectiveObjectProperty(y.propertyType,y.rangeUri)){let f=t?`${t}.${s}`:s;if(typeof c=="string"&&c.trim().length>0){let d=c.trim();if(d.includes(",")){let
|
|
37
|
+
2. If '${l}' should be a class, change property type to ObjectProperty`,u.entityName=r,u.propertyName="range",u.actualValue=l,u.expectedValue=y==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",t.push(u)}}}return t}async isTypeAvailableInImports(e,n,t){if(!e.metadata.imports)return!1;let i=null,r=t;if(t.includes(".")){let o=t.split(".",2);i=o[0],r=o[1]}for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){if(i!==null&&a.alias!==i)continue;let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=i!==null?r:t,l=s.body[c];if(l&&typeof l=="object"&&!Array.isArray(l)){let u=l.type?.toString();if(this.isValidRangeTargetType(u))return!0}let m=new Set;if(await this.isTypeAvailableInImportsRecursive(s,n,c,m))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,n,t,i){let r=e.metadata.namespace_?.toString()??"";if(r&&i.has(r)||(r&&i.add(r),!e.metadata.imports))return!1;for(let[o,p]of Object.entries(e.metadata.imports))for(let a of p){let s=await n.getHighestCompatibleVersionAsync(o,a);if(s){let c=s.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let m=c.type?.toString();if(this.isValidRangeTargetType(m))return!0}if(await this.isTypeAvailableInImportsRecursive(s,n,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,n){let t=[],i=new Map,r=new V(n);await r.buildEntityIndexAsync(e);for(let[o,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let a=p,s=!1,c=a.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=a.range,m=[];if(Array.isArray(l))for(let y of l){let u=y?.toString();u&&m.push(u)}else{let y=l?.toString();y&&m.push(y)}for(let y of m)this.xsdTypes.has(y)||(i.has(y)||i.set(y,[]),i.get(y).push(o))}}for(let[o,p]of i)if(!await r.resolveEntityAsync(o,e))for(let s of p){let c=new g;c.ruleType=this.ruleName,c.severity="Warning",c.message=`ObjectProperty references class '${o}' which may not be imported`,c.suggestion=`Ensure the namespace containing '${o}' is imported, or define '${o}' in this document`,c.entityName=s,c.propertyName="range",c.actualValue=o,t.push(c)}return t}};var J=class h{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"&&h.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 n=e.includes(".")?e.split(".")[1]:e;return h.KNOWN_XSD_DATATYPES.has(n.toLowerCase())}async isClassTypeAsync(e,n){if(this.isKnownXsdDatatypeName(e))return!1;let t=await this.resourceResolver.resolveEntityAsync(e,n);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,n){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(n)||e==="Property"&&this.isLiteralType(n))}isEffectiveObjectProperty(e,n){return!!(e==="ObjectProperty"||e==="Property"&&n&&!this.isXsdDatatype(n)&&!this.isLiteralType(n))}};var q=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"ObjectPropertyValue"}async validateAsync(e,n){let t=[],i=new V(n),r=new J(i),o=await i.buildEntityIndexAsync(e),p=await this.buildPropertyMetadataAsync(e,n,i,o);for(let[a,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&await this.scanEntityForObjectProperties(s,a,"",p,i,r,e,t);return t}async scanEntityForObjectProperties(e,n,t,i,r,o,p,a){for(let[s,c]of Object.entries(e)){if(this.standardProperties.has(s))continue;let l=s,m=s.lastIndexOf(".");m>0&&m<s.length-1&&(l=s.substring(m+1));let y=i.get(l);if(y&&o.isEffectiveObjectProperty(y.propertyType,y.rangeUri)){let f=t?`${t}.${s}`:s;if(typeof c=="string"&&c.trim().length>0){let d=c.trim();if(d.includes(",")){let k=d.split(",").map(A=>A.trim()).filter(A=>A.length>0);a.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:
|
|
38
38
|
${s}:
|
|
39
|
-
- ${
|
|
40
|
-
${
|
|
41
|
-
`)}`,entityName:n,propertyName:s,propertyPath:f,actualValue:d,expectedValue:`A single reference to ${y.range??"an entity"} OR a YAML list`});continue}let R=await r.resolveEntityAsync(d,p);if(R)y.range&&(await this.validateRangeType(R,y.range,r,p)||a.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${y.range}, but '${d}' may not be a ${y.range}`,suggestion:`Ensure '${d}' is defined with appropriate type`,entityName:n,propertyName:s,propertyPath:f,actualValue:d,expectedValue:y.range}));else{let
|
|
39
|
+
- ${k[0]}
|
|
40
|
+
${k.slice(1).map(A=>` - ${A}`).join(`
|
|
41
|
+
`)}`,entityName:n,propertyName:s,propertyPath:f,actualValue:d,expectedValue:`A single reference to ${y.range??"an entity"} OR a YAML list`});continue}let R=await r.resolveEntityAsync(d,p);if(R)y.range&&(await this.validateRangeType(R,y.range,r,p)||a.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${y.range}, but '${d}' may not be a ${y.range}`,suggestion:`Ensure '${d}' is defined with appropriate type`,entityName:n,propertyName:s,propertyPath:f,actualValue:d,expectedValue:y.range}));else{let k=y.range??"entity";a.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${d}' which is not defined or imported`,suggestion:`Define '${d}' or import a namespace that contains it. Expected range: ${k}`,entityName:n,propertyName:s,propertyPath:f,actualValue:d,expectedValue:"Defined or imported entity"})}}else if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let d=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(c,n,d,i,r,o,p,a)}else if(Array.isArray(c))for(let d=0;d<c.length;d++){let R=c[d];if(typeof R=="string"&&R.trim().length>0){let k=R.trim(),A=await r.resolveEntityAsync(k,p);if(A){if(y.range&&!await this.validateRangeType(A,y.range,r,p)){let Q=t?`${t}.${s}[${d}]`:`${s}[${d}]`;a.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${y.range}, but '${k}' may not be a ${y.range}`,suggestion:`Ensure '${k}' is defined with appropriate type`,entityName:n,propertyName:`${s}[${d}]`,propertyPath:Q,actualValue:k,expectedValue:y.range})}}else{let re=y.range??"entity",Q=t?`${t}.${s}[${d}]`:`${s}[${d}]`;a.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${k}' which is not defined or imported`,suggestion:`Define '${k}' or import a namespace that contains it. Expected range: ${re}`,entityName:n,propertyName:`${s}[${d}]`,propertyPath:Q,actualValue:k,expectedValue:"Defined or imported entity"})}}else if(typeof R=="object"&&R!==null&&!Array.isArray(R)){let k=t?`${t}.${s}[${d}]`:`${s}[${d}]`;await this.scanEntityForObjectProperties(R,n,k,i,r,o,p,a)}}}if(typeof c=="object"&&c!==null&&!Array.isArray(c)&&!i.has(s)){let u=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(c,n,u,i,r,o,p,a)}else if(Array.isArray(c))for(let u=0;u<c.length;u++){let f=c[u];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let d=t?`${t}.${s}[${u}]`:`${s}[${u}]`;await this.scanEntityForObjectProperties(f,n,d,i,r,o,p,a)}}}}async validateRangeType(e,n,t,i){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(n))return!0;let o=e.entity.type;if(o){let p=[];if(Array.isArray(o))for(let a of o){let s=a?.toString();s&&s.trim().length>0&&p.push(s)}else{let a=o?.toString();a&&a.trim().length>0&&p.push(a)}for(let a of p){let s=a.includes(".")?a.split(".")[1]:a;if(s===n||n==="Property"&&(s==="DatatypeProperty"||s==="ObjectProperty"||s==="AnnotationProperty")||n==="Class"&&s==="Class"||await t.isSubclassOfAsync(a,n,i))return!0}}return!1}async buildPropertyMetadataAsync(e,n,t,i){let r=new Map;for(let[o,p]of i){let a=p.entity.type;if(a){let s=[];if(Array.isArray(a))for(let m of a){let y=m?.toString();y&&y.trim().length>0&&s.push(y)}else{let m=a?.toString();m&&m.trim().length>0&&s.push(m)}let c=!1,l="Property";for(let m of s){let y=m.includes(".")?m.split(".")[1]:m;if(y==="Property"||y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty"){c=!0,l=m;break}}if(c){let m={propertyType:l},y=p.entity.range;if(y){let u=y?.toString();if(u&&u.trim().length>0){m.range=u;let f=await t.resolveEntityAsync(u,e);f&&(m.rangeUri=f.uri)}}r.set(o,m)}}}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,n){let t=[],i=new Map;for(let[o,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let a=p,s=this.getPropertyValue(a,"type");(s==="DatatypeProperty"||s?.endsWith(".DatatypeProperty")||s==="ObjectProperty"||s?.endsWith(".ObjectProperty")||s==="AnnotationProperty"||s?.endsWith(".AnnotationProperty"))&&i.set(o,a)}let r=await this.buildCompleteClassHierarchyAsync(e,n);for(let[o,p]of Object.entries(e.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let a=p,s=this.getPropertyValue(a,"type");if(!s||s==="Class"||s.endsWith(".Class")||s.endsWith("Property")||s==="AnnotationProperty")continue;this.validateEntityProperties(a,o,s,i,r,t)}return t}async buildCompleteClassHierarchyAsync(e,n){let t=new Map,i=new Set,r=async(p,a)=>{if(!i.has(a)){i.add(a);for(let[s,c]of Object.entries(p.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=c,m=this.getPropertyValue(l,"type");if(m==="Class"||m?.endsWith(".Class")){let y=l.subClassOf;if(y===void 0){for(let f of Object.keys(l))if(f.endsWith(".subClassOf")){y=l[f];break}}let u=v(y);u.length>0&&t.set(s,u)}}if(p.metadata.imports)for(let[s,c]of Object.entries(p.metadata.imports))for(let l of c)try{let m=await n.getHighestCompatibleVersionAsync(s,l);if(m){let y=`${s}/${l.packageName}@${l.version}`;await r(m,y)}}catch{}}},o=e.metadata.namespace_?.toString()??"unknown";return await r(e,o),t}validateEntityProperties(e,n,t,i,r,o){for(let[p,a]of Object.entries(e)){if(this.standardProperties.has(p))continue;let s=p,c=p.lastIndexOf(".");c>0&&c<p.length-1&&(s=p.substring(c+1));let l=i.get(s);if(!l)continue;let m=this.getPropertyValue(l,"domain");if(m){if(!this.isTypeCompatibleWithDomain(t,m,r)){let y=n.split(".")[0];o.push({ruleType:this.ruleName,severity:"Error",entityName:y,propertyName:n,actualValue:p,message:`Property '${p}' has domain '${m}' but is used on '${t}' at '${n}'`,suggestion:`Either:
|
|
42
42
|
1. Use this property only on '${m}' instances
|
|
43
43
|
2. Change the property domain to include '${t}'
|
|
44
|
-
3. Create a different property for '${t}'`,expectedValue:`Property used on ${m} or its subclasses`})}if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let y=a,u=this.getPropertyValue(y,"type");if(u){let f=`${n}.${p}`;this.validateEntityProperties(y,f,u,i,r,o)}else{let f=this.getPropertyValue(l,"range");if(f){let d=`${n}.${p}`;this.validateEntityProperties(y,d,f,i,r,o)}}}else if(Array.isArray(a))for(let y=0;y<a.length;y++){let u=a[y];if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=u,d=this.getPropertyValue(f,"type");if(d){let R=`${n}.${p}[${y}]`;this.validateEntityProperties(f,R,d,i,r,o)}else{let R=this.getPropertyValue(l,"range");if(R){let
|
|
44
|
+
3. Create a different property for '${t}'`,expectedValue:`Property used on ${m} or its subclasses`})}if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let y=a,u=this.getPropertyValue(y,"type");if(u){let f=`${n}.${p}`;this.validateEntityProperties(y,f,u,i,r,o)}else{let f=this.getPropertyValue(l,"range");if(f){let d=`${n}.${p}`;this.validateEntityProperties(y,d,f,i,r,o)}}}else if(Array.isArray(a))for(let y=0;y<a.length;y++){let u=a[y];if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=u,d=this.getPropertyValue(f,"type");if(d){let R=`${n}.${p}[${y}]`;this.validateEntityProperties(f,R,d,i,r,o)}else{let R=this.getPropertyValue(l,"range");if(R){let k=`${n}.${p}[${y}]`;this.validateEntityProperties(f,k,R,i,r,o)}}}}}}}isTypeCompatibleWithDomain(e,n,t){if(e===n)return!0;let i=new Set,r=[e];for(;r.length>0;){let o=r.shift();if(i.has(o))continue;i.add(o);let p=t.get(o);if(p)for(let a of p){if(a===n)return!0;r.push(a)}}return!1}getPropertyValue(e,n){if(n in e){let t=e[n];return this.extractFirstValue(t)}for(let t of Object.keys(e))if(t.endsWith(`.${n}`)){let i=e[t];return this.extractFirstValue(i)}}extractFirstValue(e){if(Array.isArray(e)){let n=[];for(let t of e)n.push(t?.toString()??"");return n.length>0?n[0]:void 0}return e?.toString()}};var B=class{get ruleName(){return"PropertyValueType"}async validateAsync(e,n){let t=[],i=new Map;for(let[r,o]of Object.entries(e.body))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let p=o,a=this.getPropertyValue(p,"type");(a==="DatatypeProperty"||a==="ObjectProperty")&&i.set(r,p)}for(let[r,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o))continue;let p=o,a=this.getPropertyValue(p,"type");if(!(!a||a==="Class"||a.endsWith("Property")||a==="AnnotationProperty"))for(let[s,c]of Object.entries(p)){if(s==="type"||s==="label"||s==="comment")continue;let l=s,m=s.lastIndexOf(".");m>0&&m<s.length-1&&(l=s.substring(m+1));let y=i.get(l);if(!y)continue;let u=this.getPropertyValue(y,"type"),f=this.getPropertyValue(y,"range");if(u==="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:
|
|
45
45
|
1. Create a class for this data and change '${s}' to an ObjectProperty
|
|
46
46
|
2. Store as a JSON string to keep it as DatatypeProperty
|
|
47
|
-
3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${f}'`});else if(!this.validateDatatypeValue(f,c)){let d={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&&(d.expectedValue=f),t.push(d)}}else if(u==="ObjectProperty")if(Array.isArray(c))for(let d=0;d<c.length;d++){let R=c[d];typeof R!="string"&&(typeof R!="object"||R===null||Array.isArray(R))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:`${s}[${d}]`,message:`ObjectProperty '${s}' array item ${d} 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,n){switch(e?.toLowerCase()){case"string":return typeof n=="string";case"integer":case"int":return typeof n=="number"&&Number.isInteger(n);case"decimal":return typeof n=="number";case"boolean":return typeof n=="boolean";case"float":case"double":return typeof n=="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,n){if(n in e){let t=e[n];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
|
|
47
|
+
3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${f}'`});else if(!this.validateDatatypeValue(f,c)){let d={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&&(d.expectedValue=f),t.push(d)}}else if(u==="ObjectProperty")if(Array.isArray(c))for(let d=0;d<c.length;d++){let R=c[d];typeof R!="string"&&(typeof R!="object"||R===null||Array.isArray(R))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:r,propertyName:`${s}[${d}]`,message:`ObjectProperty '${s}' array item ${d} 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,n){switch(e?.toLowerCase()){case"string":return typeof n=="string";case"integer":case"int":return typeof n=="number"&&Number.isInteger(n);case"decimal":return typeof n=="number";case"boolean":return typeof n=="boolean";case"float":case"double":return typeof n=="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,n){if(n in e){let t=e[n];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,n){let t=[],i=new Map,r=new Set;for(let[p,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a.type;if(c)if(Array.isArray(c))for(let l of c){let m=l?.toString();if(m==="Class"||m&&m.endsWith(".Class")){r.add(p);break}}else{let l=c?.toString();(l==="Class"||l&&l.endsWith(".Class"))&&r.add(p)}}for(let[p,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let s=a,c=s.type;if(c)if(Array.isArray(c)){let l=!1;for(let m of c){let y=m?.toString();if(y&&this.isDefinitionType(y)){l=!0;break}}if(!l)for(let m of c){let y=m?.toString();y&&y.trim().length>0&&(i.has(y)||i.set(y,[]),i.get(y).push(p))}}else{let l=c?.toString();l&&l.trim().length>0&&(this.isDefinitionType(l)||(i.has(l)||i.set(l,[]),i.get(l).push(p)))}this.checkNestedTypes(s,p,i,p)}let o=new V(n);for(let[p,a]of i){if(this.builtInClasses.has(p)||r.has(p))continue;let s=await o.resolveEntityAsync(p,e);if(!(s&&this.isClassEntity(s.entity))){let l=Array.from(new Set(a)).sort();for(let m of l)t.push({ruleType:this.ruleName,severity:"Error",message:`Class '${p}' is not defined or imported`,suggestion:`Define '${p}' as a Class in this document, or import a namespace that contains it`,entityName:m,propertyName:"type",actualValue:p,expectedValue:"Defined or imported class"})}}return t}checkNestedTypes(e,n,t,i){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=e,o=r.type;if(o){let p=new Set(["Class","DatatypeProperty","ObjectProperty","AnnotationProperty"]);if(Array.isArray(o))for(let a of o){let s=a?.toString();s&&s.trim().length>0&&!p.has(s)&&(t.has(s)||t.set(s,[]),t.get(s).push(i))}else{let a=o?.toString();a&&a.trim().length>0&&!p.has(a)&&(t.has(a)||t.set(a,[]),t.get(a).push(i))}}for(let[p,a]of Object.entries(r))if(p!=="type"){let s=`${i}.${p}`;this.checkNestedTypes(a,n,t,s)}}else if(Array.isArray(e))for(let r=0;r<e.length;r++){let o=`${i}[${r}]`;this.checkNestedTypes(e[r],n,t,o)}}isClassEntity(e){if(!e)return!1;let n=e.type;if(!n)return!1;if(Array.isArray(n))for(let t of n){let i=t?.toString();if(i==="Class"||i&&i.endsWith(".Class"))return!0}else{let t=n?.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 $,new E],this.repositoryRules=[new w,new j,new S,new N,new C,new K,new x,new T,new _,new M,new W,new L,new F,new H,new U,new q,new X,new B,new z]}async validateAsync(e,n){let t=new P;for(let i of this.documentRules)try{let r=i.validate(e);this.addErrorsToResult(t,r)}catch(r){let o=new g;o.ruleType=i.ruleName,o.severity="Error",o.message=`Validation rule '${i.ruleName}' failed: ${r instanceof Error?r.message:String(r)}`,t.errors.push(o)}if(n){let i=[];for(let r of this.repositoryRules)try{let o=await r.validateAsync(e,n);this.addErrorsToResult(t,o)}catch(o){let p=o instanceof Error?o.message:String(o);i.push({ruleName:r.ruleName,cause:p})}if(i.length>0){let r=new Map;for(let{ruleName:o,cause:p}of i){let a=r.get(p);a?a.push(o):r.set(p,[o])}for(let[o,p]of r){let a=new g;a.ruleType=p[0],a.severity="Error",p.length===1?a.message=`Validation rule '${p[0]}' failed: ${o}`:a.message=`${o} (affects ${p.length} rules: ${p.join(", ")})`,t.errors.push(a)}}}return t.isValid=t.errors.length===0,t}async validateYamlAsync(e,n){let t=this.parser.parseWithErrors(e);if(!t.isValid){let i=new P;i.isValid=!1;for(let r of t.errors){let o=new g;o.ruleType="ParseError",o.severity="Error",o.lineNumber=r.line,o.column=r.column,o.message=r.message,r.keyName&&(o.entityName=r.keyName),r.errorType==="DuplicateKey"&&(o.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),i.errors.push(o)}return i}return await this.validateAsync(t.document,n)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let n=this.documentRules.findIndex(t=>t instanceof e);n>=0&&this.documentRules.splice(n,1)}removeRepositoryRule(e){let n=this.repositoryRules.findIndex(t=>t instanceof e);n>=0&&this.repositoryRules.splice(n,1)}addErrorsToResult(e,n){for(let t of n)t.severity==="Error"?e.errors.push(t):this.includeWarnings&&e.warnings.push(t)}};export{F as AmbiguousReferenceRule,z as ClassDefinitionRule,N as ClassHierarchyCycleRule,W as DefinitionPropertyReferenceRule,E as EmbeddedKanonakNoExplicitTypeRule,w as ImportExistenceRule,M as InstancePropertyReferenceRule,te as KanonakObjectValidator,_ as NamespaceImportCycleRule,I as NamespacePrefixRule,U as ObjectPropertyImportRule,q as ObjectPropertyValueValidationRule,g as OntologyValidationError,P as OntologyValidationResult,X as PropertyDomainRule,C as PropertyHierarchyCycleRule,H as PropertyRangeReferenceRule,K as PropertyRangeRequiredRule,O as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,D as ResourceNamingRule,x as SubClassOfReferenceRule,T as SubPropertyOfReferenceRule,$ as SubjectKanonakTypeRequiredRule,S as TypeAmbiguityRule,j as UnresolvedReferenceRule,ee as ValidationContext,b as ValidationSeverity,L as XsdImportRule};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
"yaml-parser"
|
|
99
99
|
],
|
|
100
100
|
"dependencies": {
|
|
101
|
-
"@kanonak-protocol/types": "^1.
|
|
101
|
+
"@kanonak-protocol/types": "^1.6.0",
|
|
102
102
|
"ignore": "^7.0.5",
|
|
103
103
|
"js-yaml": "^4.1.0"
|
|
104
104
|
},
|