@kanonak-protocol/sdk 3.9.0 → 3.10.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/index.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
1
|
var sn=Object.defineProperty;var an=(i,e)=>()=>(i&&(e=i(i=0)),e);var cn=(i,e)=>{for(var t in e)sn(i,t,{get:e[t],enumerable:!0})};var hr={};cn(hr,{KanonakUri:()=>T});function yn(i,e,t){return{major:i,minor:e,patch:t,toString:()=>`${i}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===i&&r.minor===e&&r.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:r=>i!==r.major?i-r.major:e!==r.minor?e-r.minor:t-r.patch}}var T,le=an(()=>{"use strict";T=class i{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=n.indexOf("@");if(s===-1)return new i(r,n,o,void 0);let a=n.substring(0,s),c=n.substring(s+1);if(!a||!c)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let p=c.split(".").map(Number),l=yn(p[0]||0,p[1]||0,p[2]||0);return new i(r,a,o,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});function F(i,e){return i.major!==e.major?i.major-e.major:i.minor!==e.minor?i.minor-e.minor:i.patch-e.patch}function _e(i,e){return i.major===e.major&&i.minor===e.minor&&i.patch===e.patch}function Gt(i){return`${i.major}.${i.minor}.${i.patch}`}function zt(i,e,t){let r=`${i}.${e}.${t}`;return{major:i,minor:e,patch:t,toString:()=>r,equals:n=>n?.major===i&&n?.minor===e&&n?.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:n=>i!==n.major?i-n.major:e!==n.minor?e-n.minor:t-n.patch}}function mr(i){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(i);return e?zt(Number(e[1]),Number(e[2]),Number(e[3])):null}function Ue(i,e){return F(i,e)>=0&&i.major===e.major&&i.minor===e.minor}function Le(i,e){return e.major===0?F(i,e)>=0&&i.major===0&&i.minor===e.minor:F(i,e)>=0&&i.major===e.major}function yr(i,e={}){let{requestedVersion:t}=e;if(i.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let n=i.find(o=>{let s=o.metadata.namespace_?.version;return!!s&&Gt(s)===t});return n?{chosen:n,alternatives:i.filter(o=>o!==n),multipleVersionsPresent:i.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:i,multipleVersionsPresent:i.length>1,exactRequestedVersionMissing:!0}}if(i.length===1)return{chosen:i[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let r=[...i].sort((n,o)=>{let s=n.metadata.namespace_?.version,a=o.metadata.namespace_?.version;return!s&&!a?0:s?a?F(a,s):-1:1});return{chosen:r[0],alternatives:r.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}var mt=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let r=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===e&&n.metadata?.namespace_?.package_===t&&r.push(n);return r}async getHighestCompatibleVersionAsync(e,t){let r=[];for(let o of this.documents.values())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t.packageName&&o.metadata?.namespace_?.version!==void 0&&r.push(o);if(r.length===0)return null;let n=r.filter(o=>{let s=o.metadata.namespace_.version;if(!s)return!1;switch(t.versionOperator){case 0:return _e(s,t.version);case 1:return Ue(s,t.version);case 2:return Le(s,t.version);case 3:return F(s,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((o,s)=>{let a=o.metadata.namespace_.version,c=s.metadata.namespace_.version;return!a&&!c?0:a?c?F(c,a):-1:1}),n[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let r=this.parser.save(e);this.documentContents.set(t,r)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let r=[];for(let[n,o]of this.documents.entries())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t&&r.push(n);for(let n of r)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let r=this.documents.get(e);return r!==void 0?this.parser.save(r):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}};import*as K from"fs/promises";import*as D from"path";import{pathToFileURL as fr}from"url";import*as yt from"js-yaml";var $=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=yt.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),yt.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:c=>!c||typeof c!="object"?!1:c.publisher===s&&c.package_===o&&(!a||!c.version||a.equals(c.version)),getHashCode:()=>{let c=0;for(let p=0;p<s.length;p++)c=(c<<5)-c+s.charCodeAt(p);for(let p=0;p<o.length;p++)c=(c<<5)-c+o.charCodeAt(p);return c|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<o[1].length;c++)a=(a<<5)-a+o[1].charCodeAt(c);for(let c=0;c<o[2].length;c++)a=(a<<5)-a+o[2].charCodeAt(c);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),c=this.calculateMaxVersion(n,s),p=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:p,minVersion:s,maxVersion:c,toEmbeddedObject:()=>{let l={package:r,match:n,version:s.toString()};return p&&(l.alias=p),l},toString:()=>p?`${r} ${n} ${s.toString()} as ${p}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let c=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(c){let l=c[1].trim(),u=c[2],m=this.parseVersion(c[3].trim()),y=c[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:l,versionOperator:f,version:m,alias:y,minVersion:m,maxVersion:d,toEmbeddedObject:()=>{let g={package:l,match:u,version:m.toString()};return y&&(g.alias=y),g},toString:()=>`${l} ${u} ${m.toString()} as ${y}`}}let p=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(p){let l=p[1].trim(),u=p[2],m=this.parseVersion(p[3].trim()),y=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:l,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:f,toEmbeddedObject:()=>({package:l,match:u,version:m.toString()}),toString:()=>`${l} ${u} ${m.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let c={package:o,match:s,version:n.toString()};return e.alias&&(c.alias=e.alias),c},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],c={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(c.alias=s.alias),c})};t.push(o)}return t}};var ce=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,r){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=D.resolve(e),this.recursive=t,this.parser=r??new $,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let r=D.join(this.rootPath,e);if(t=this.documentCache.get(r),t)return t;for(let n of[".kan.yml",".yml",".yaml"])if(!e.endsWith(n)){let o=e+n;if(t=this.documentCache.get(o),t)return t;let s=D.join(this.rootPath,o);if(t=this.documentCache.get(s),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values());return Array.from(r).filter(n=>n.metadata.namespace_?.publisher===e&&n.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values()),n=Array.from(r).filter(s=>s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0);if(n.length===0)return null;let o=n.filter(s=>{let a=s.metadata.namespace_.version;switch(t.versionOperator){case 0:return _e(a,t.version);case 1:return Ue(a,t.version);case 2:return Le(a,t.version);case 3:return F(a,t.minVersion)>=0;default:return!1}});return o.length===0?null:(o.sort((s,a)=>{let c=s.metadata.namespace_.version,p=a.metadata.namespace_.version;return F(p,c)}),o[0])}async saveDocumentAsync(e,t){let r,n=e.metadata.namespace_?.toString();if(n&&n.includes("@")&&n.includes("/")){let c=n.split("/"),p=c[0],u=c[1].replace("@","@")+".kan.yml";r=D.join(this.rootPath,p,u)}else r=D.join(this.rootPath,t),!r.endsWith(".yml")&&!r.endsWith(".yaml")&&!r.endsWith(".kan.yml")&&(r+=".kan.yml");let o=D.dirname(r);await K.mkdir(o,{recursive:!0});let s=this.parser.save(e);await K.writeFile(r,s,"utf8"),n&&this.documentCache.set(n,e),this.documentCache.set(r,e);let a=D.relative(this.rootPath,r);this.documentCache.set(a,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let r=this.filePathsByIdentifier.get(e);if(!r)return;try{await K.unlink(r)}catch{}let n=t.metadata.namespace_?.toString();n&&this.documentCache.delete(n),this.documentCache.delete(e),this.documentCache.delete(r);let o=D.relative(this.rootPath,r);this.documentCache.delete(o)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=[];for(let[o,s]of this.documentCache.entries()){let a=s.metadata.namespace_?.toString()||"";a.includes(e)&&a.includes(t)&&r.push([o,s])}let n=D.join(this.rootPath,e);try{let o=await K.readdir(n);for(let s of o)s.includes(t)&&s.endsWith(".kan.yml")&&await K.unlink(D.join(n,s))}catch{}for(let[o]of r)this.documentCache.delete(o)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let r of e){let n=fr(r).toString(),o;for(let[c,p]of this.documentCache.entries())if(this.filePathsByIdentifier.get(c)===r&&p.metadata.namespace_){o=p.metadata.namespace_.toString();break}let s=o??D.relative(this.rootPath,r),a=this.parsingErrors.has(r);t.push({identifier:s,uri:n,hasParseError:a})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await K.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await K.access(r),t=r}catch{return null}}try{return await K.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await K.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await K.access(r),t=r}catch{return null}}return fr(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await K.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async n=>{try{let o=await K.readFile(n,"utf8"),s=this.parser.parse(o);return{filePath:n,document:s,error:null}}catch(o){return{filePath:n,document:null,error:o instanceof Error?o.message:String(o)}}}),r=await Promise.all(t);for(let{filePath:n,document:o,error:s}of r){let a=D.relative(this.rootPath,n);if(o&&o.metadata.namespace_){let c=o.metadata.namespace_.toString();this.documentCache.set(c,o),this.documentCache.set(n,o),this.documentCache.set(a,o),this.filePathsByIdentifier.set(c,n),this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n)}else this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n);s&&this.parsingErrors.set(n,s)}}async findYamlFiles(e,t){let r=[];try{let n=await K.readdir(e,{withFileTypes:!0});for(let o of n){let s=D.join(e,o.name);if(o.isDirectory()&&t){let a=await this.findYamlFiles(s,t);r.push(...a)}else o.isFile()&&o.name.endsWith(".kan.yml")&&r.push(s)}}catch{}return r}};import*as Me from"fs";var Xt=(r=>(r.NotFound="NotFound",r.Workspace="Workspace",r.Cache="Cache",r))(Xt||{}),Fe=class{cache;workspace;constructor(e,t,r){let n=r??new $;Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),Me.existsSync(t)||Me.mkdirSync(t,{recursive:!0}),this.cache=new ce(e,!0,n),this.workspace=new ce(t,!0,n)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),r=new Map;for(let n of t)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}for(let n of e)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}return Array.from(r.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let r=await this.workspace.getDocumentsByNamespaceAsync(e,t),n=await this.cache.getDocumentsByNamespaceAsync(e,t),o=new Map;for(let s of n)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}for(let s of r)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}return Array.from(o.values())}async getHighestCompatibleVersionAsync(e,t){let r=await this.workspace.getHighestCompatibleVersionAsync(e,t);return r||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),r=[];return r.push(...e),r.push(...t),r}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as pn}from"os";import{join as ln}from"path";function Qe(){let i=process.env.KANONAK_PACKAGE_CACHE;return i||ln(pn(),".kanonak","packages")}var ft=class i{static createComposite(e,t,r){let n=e??Qe(),o=t??".";return new Fe(n,o,r)}static createFromEnvironment(e){let t=Qe(),r=process.env.KANONAK_WORKSPACE_PATH??".";return i.createComposite(t,r,e)}};import{VersionOperator as dt}from"@kanonak-protocol/types/document/models/enums";var un="https://{publisher}/index.txt",mn="https://{publisher}/{package}/{version}.kan.yml",dr={version:1},Be=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let r=await this.fetchConfig(e);return this.cache.set(e,r),r}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await fetch(t)}catch{return dr}if(r.status===404)return dr;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${t} (${r.status} ${r.statusText})`);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let o={version:n.version};return typeof n.index=="string"&&(o.index=n.index),typeof n.package=="string"&&(o.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(o.auth=n.auth),o}resolveIndexUrl(e,t){let r=t.index??un;return gr(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??mn;return gr(o,{publisher:e,package:t,version:r})}};function gr(i,e){let t=i;for(let[n,o]of Object.entries(e))t=t.replaceAll(`{${n}}`,o);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${i}`);return t}var pe=class i{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Be,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(o=>this.isVersionCompatible(o,t.version,t.versionOperator));return n.length===0?null:(n.sort((o,s)=>this.compareVersionStrings(s,o)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((o,s)=>this.compareVersionStrings(s,o))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let r=[];for(let[n,o]of t){if(o.length===0)continue;let s=[...o].sort((a,c)=>this.compareVersionStrings(c,a));r.push({packageName:n,version:s[0]})}return r.sort((n,o)=>n.packageName.localeCompare(o.packageName)),r}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let o=await n.text();return i.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
|
|
2
|
-
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("/");if(o===-1)continue;let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)continue;let c=t.get(s);c?c.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=i.parseVersion(e);if(!n)return!1;switch(r){case dt.Any:return!0;case dt.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case dt.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case dt.Major:return n.major!==t.major?!1:n.minor>t.minor?!0:n.minor===t.minor?n.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let r=parseInt(t[0],10),n=parseInt(t[1],10),o=t.length>=3?parseInt(t[2],10):0;return isNaN(r)||isNaN(n)||isNaN(o)?null:{major:r,minor:n,patch:o}}compareVersionStrings(e,t){let r=i.parseVersion(e),n=i.parseVersion(t);return!r&&!n?0:r?n?r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch:1:-1}};var gt=class{parser=new $;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new pe({fetchFn:e.fetchFn}):new pe}async getHighestCompatibleVersionAsync(e,t){let r=await this.publisherIndex.resolveVersion(e,t);if(!r)return null;let n=`${e}/${t.packageName}@${r}`,o=this.documents.get(n);if(o)return o;if(this.getFromCache){let l=this.getFromCache(e,t.packageName,r);if(l){let u=this.parser.parse(l);return this.documents.set(n,u),this.contentCache.set(n,l),u}}let s=await this.publisherIndex.getPackageUrl(e,t.packageName,r),a=this.fetchFn?await this.fetchFn(s,e):await fetch(s);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${s} (${a.status} ${a.statusText})`);let c=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,c);let p=this.parser.parse(c);return this.documents.set(n,p),this.contentCache.set(n,c),p}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,o]=t;return this.publisherIndex.getPackageUrl(r,n,o)}};var z=class{};var re=class extends z{statement=[]};var N=class extends re{namespace;name;icon};var _=class extends re{name};le();var w=class i extends z{subject;static parse(e){let t=new i;return t.subject=T.parse(e),t}};var Z=class extends z{value};var B=class{predicate;object};var X=class extends B{};var W=class i extends X{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=t,r}};var Q=class i extends X{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=t,r}};var ee=class extends X{};var U=class i extends B{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=w.parse(t),r}};var H=class extends B{};var L=class extends B{};le();function E(i){if(Array.isArray(i))return i.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=i?.toString();return e?[e]:[]}var j=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,c]of Object.entries(e.body))if(!a.includes(".")&&c&&typeof c=="object"&&!Array.isArray(c)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new T(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${c}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(c,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${l.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${c}/${l.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[c,p]of Object.entries(e.body))if(!c.includes(".")&&p&&typeof p=="object"&&!Array.isArray(p)&&!n.has(c)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(c,{entityName:c,uri:new T(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,l),entity:p,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((p,l)=>p+l.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${o}`);for(let[p,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${p}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(p,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,t,s),f=0;for(let[d,g]of y.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${u.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${p}/${u.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${p}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=E(s);for(let c of a)if(c===t||await this.isSubclassOfRecursiveAsync(c,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=E(s);for(let c of a)if(c===t||await this.isSubpropertyOfRecursiveAsync(c,t,r,n))return!0}return!1}};var ne=class i{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&i.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return i.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var oe=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new j(e),o=new ne(n);for(let c of r){let p=c.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(c.body)){let m=new N,y=this.resolveCanonicalEntity(l,c,p);m.namespace=y.namespace,m.name=y.name,m.statement=[];let f=await this.parseStatements(u,c,n,o,e);m.statement.push(...f),t.push(m)}}let s=new Map,a=[];for(let c of t)if(c instanceof N){let p=`${c.namespace}/${c.name}`,l=s.get(p);l?l.statement.push(...c.statement):(s.set(p,c),a.push(c))}else a.push(c);return a}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let n=e.indexOf("."),o=e.substring(0,n),s=e.substring(n+1);for(let[a,c]of Object.entries(t.metadata.imports))for(let p of c)if((p.alias??p.packageName)===o){let u=p.version;return{namespace:`${a}/${p.packageName}@${u.major}.${u.minor}.${u.patch}`,name:s}}return{namespace:r,name:e}}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,c]of Object.entries(e))try{let p=await this.getPropertyMetadata(a,t,r,o,n);if(!p)continue;let l=await this.parsePropertyValue(a,c,p,t,r,n);l&&s.push(l)}catch(p){console.error(`Error parsing property ${a}:`,p)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,c=a.type?.toString()??"",p=c.includes(".")?c.substring(c.lastIndexOf(".")+1):c;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let u=o.getPropertyTypeClassification(c),m=a.range?.toString(),y;if(u==="ObjectProperty")y="ObjectProperty";else if(u==="DatatypeProperty")y="DatatypeProperty";else{let d=m&&m.includes(".")?m.substring(m.lastIndexOf(".")+1):m??"";(m?o.isKnownXsdDatatypeName(m):!1)||d==="Literal"?y="DatatypeProperty":y="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:y,range:m,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return W.parse(e,t.toISOString());if(typeof t=="string")return W.parse(e,t);if(typeof t=="number")return Q.parse(e,t);if(typeof t=="boolean"){let n=new ee;return n.predicate=w.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let c=new U;return c.predicate=w.parse(e),c.object=a,c}if(typeof t=="object"&&!Array.isArray(t)){let a=new _;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let l=new H;return l.predicate=w.parse(e),l.object=a,l}let c=[];for(let[l,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new _;m.name=l,m.statement=await this.parseStatements(u,n,o,s,{}),c.push(m)}else if(typeof u=="string"){let m=await this.resolveReference(u,n,o);m&&c.push(m)}if(c.length>0){let l=new L;return l.predicate=w.parse(e),l.object=c,l}let p=new H;return p.predicate=w.parse(e),p.object=a,p}}async parseListValue(e,t,r,n,o,s){let a=[],c=r.propertyType==="DatatypeProperty";for(let l of t){if(c&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new Z;u.value=l,a.push(u);continue}if(c&&l instanceof Date){let u=new Z;u.value=l.toISOString(),a.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,n,o);u&&a.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new _;u.statement=await this.parseStatements(l,n,o,s,{}),a.push(u)}}let p=new L;return p.predicate=w.parse(e),p.object=a,p}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new w;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(le(),hr)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),l=e.substring(0,p),u=e.substring(p+1);if(t.metadata?.imports){for(let[m,y]of Object.entries(t.metadata.imports))for(let f of y)if((f.alias??f.packageName)===l){let g=new w;return g.subject=new s(m,f.packageName,u,f.version),g}}}let c=new w;return c.subject=new s(o.publisher,o.package_,e,a),c}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof N&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),a=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,a)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof N&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new $().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let c of s.statement){let[p,l]=this.convertStatementToProperty(c);p&&l!==null&&l!==void 0&&(a[p]=l),this.collectImportsFromStatement(c,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof W)return[e.predicate.subject.name,e.object];if(e instanceof Q)return[e.predicate.subject.name,e.object];if(e instanceof ee)return[e.predicate.subject.name,e.object];if(e instanceof U)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof L){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof H){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof w?t.push(r.subject.name):r instanceof _&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var fn=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),kr={Class:{publisher:"kanonak.org",package_:"core-owl"},ObjectProperty:{publisher:"kanonak.org",package_:"core-owl"},DatatypeProperty:{publisher:"kanonak.org",package_:"core-owl"},AnnotationProperty:{publisher:"kanonak.org",package_:"core-owl"},Property:{publisher:"kanonak.org",package_:"core-rdf"},Datatype:{publisher:"kanonak.org",package_:"core-rdfs"},Resource:{publisher:"kanonak.org",package_:"core-rdfs"},Literal:{publisher:"kanonak.org",package_:"core-rdfs"},Thing:{publisher:"kanonak.org",package_:"core-owl"},Nothing:{publisher:"kanonak.org",package_:"core-owl"}};function Y(i){let e=i;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=kr[t];return r?{publisher:r.publisher,package_:r.package_,name:t}:{publisher:"",package_:"",name:t}}}if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t.object?.subject){let r=t.object.subject;if(!r.publisher&&!r.package_||r.publisher===""&&r.package_===""){let n=kr[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function te(i,e){return fn.has(`${i}/${e}`)}var I=class i{static getTypeUri(e){return Y(e)}static isCoreOntologyType(e){return te(e.publisher,e.package_)}static isClassType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=Y(e);return!t||!te(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=Y(e);return!t||!te(t.publisher,t.package_)?!1:t.name==="Class"||t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"||t.name==="Datatype"}static isInstanceOfKnownClass(e,t){if(i.isSchemaDefinitionType(e))return!1;let r=Y(e);return r?t.has(r.name):!1}};var Jt=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(Jt||{}),Zt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(Zt||{}),ht=class{static async buildFromRepository(e){let r=await new oe().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,c=new Set,p=new Map;for(let u of r){let m=u;m.name&&(I.isClassType(m)&&a.add(m.name),(I.isObjectPropertyType(m)||I.isGenericPropertyType(m))&&c.add(m.name))}for(let u of n)for(let[m,y]of Object.entries(u.body))c.has(m)&&y?.range&&typeof y.range=="string"&&p.set(m,y.range);let l=new Map;for(let u of r){let m=u;m.name&&l.set(m.name,m)}for(let u of n){let m=u.metadata.namespace_,y=m?`${m.publisher}/${m.package_}`:"",f=m?.version?`${m.version.major}.${m.version.minor}.${m.version.patch}`:"",d=br(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=l.get(g),R="Unknown";if(b){let V=b;I.isClassType(V)?R="Class":I.isObjectPropertyType(V)?R="ObjectProperty":I.isDatatypePropertyType(V)?R="DatatypeProperty":I.isAnnotationPropertyType(V)?R="AnnotationProperty":I.isDatatypeType(V)?R="Datatype":I.isGenericPropertyType(V)?R="ObjectProperty":I.isInstanceOfKnownClass(V,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,x={};for(let[V,qt]of Object.entries(h))V!=="type"&&(typeof qt!="object"||qt===null)&&(x[V]=qt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:x}),Rr(v,h,R,a,c,s,y,f,d),Yt(v,h,c,p,o,s,y,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,c=new Set,p=new Map,l=br(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(gn(d,l)&&a.add(y),hn(d,l)&&(c.add(y),f.range&&typeof f.range=="string"&&p.set(y,f.range)))}for(let[y,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=kn(d,y,a,l),h=s&&o?`${s}/${y}@${o}`:y,b={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(b[R]=v);t.push({id:h,label:f.label??y,type:g,namespace:s,properties:b}),Rr(h,f,g,a,c,r,s,o,l),Yt(h,f,c,p,t,r,s,o,l)}let u=new Set(t.map(y=>y.id)),m=r.filter(y=>u.has(y.source)&&u.has(y.target));return{nodes:t,edges:m}}};function br(i,e){let t=new Map;if(i.metadata?.imports)for(let[r,n]of Object.entries(i.metadata.imports))for(let o of n){let s=o.alias??o.packageName,a=o.version,c=`${a.major}.${a.minor}.${a.patch}`;t.set(s,{publisher:r,package_:o.packageName,version:c})}return t}var vr={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},dn=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Qt(i,e){if(i.includes(".")){let t=i.indexOf("."),r=i.substring(0,t),n=i.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function gn(i,e){let t=Qt(i,e);return t?vr[t]==="Class":!1}function hn(i,e){let t=Qt(i,e);return t?dn.has(t):!1}function kn(i,e,t,r){if(!i||i==="Package")return"Unknown";let n=Qt(i,r);if(n){let s=vr[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=i.split(".").pop()??i;return t.has(o)?"Instance":"Unknown"}var Pr=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Rr(i,e,t,r,n,o,s,a,c){let p=e.type,l=e.subClassOf;if(l){let f=Array.isArray(l)?l:[l];for(let d of f)typeof d=="string"&&o.push({source:i,target:se(d,s,a,c),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let f=Array.isArray(u)?u:[u];for(let d of f)typeof d=="string"&&o.push({source:i,target:se(d,s,a,c),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&p){let f=p.split(".").pop()??p;o.push({source:i,target:se(f,s,a,c),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Pr.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&bn(h)&&o.push({source:i,target:se(h,s,a,c),type:"propertyValue",label:f,propertyId:se(f,s,a,c)})}let m=t==="ObjectProperty"||t==="DatatypeProperty",y=e.domain&&e.range;if((m||y)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:se(f,s,a,c),target:se(d,s,a,c),type:"objectRelationship",label:e.label??i.split("/").pop()??"",propertyId:i})}}function Yt(i,e,t,r,n,o,s,a,c){for(let[p,l]of Object.entries(e)){if(Pr.has(p)||typeof l!="object"||l===null||Array.isArray(l))continue;let u=l,m=`${i}/${p}`,y=r.get(p),f=y?y.split(".").pop()??y:"Unknown",d={};for(let[h,b]of Object.entries(u))(typeof b!="object"||b===null)&&(d[h]=b);n.push({id:m,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${p}@${a}`:p;o.push({source:i,target:m,type:"propertyValue",label:p,propertyId:t.has(p)?g:void 0}),y&&o.push({source:m,target:se(f,s,a,c),type:"instanceOf",label:"type (inferred)"}),Yt(m,u,t,r,n,o,s,a,c)}}function bn(i){return!(!i||i.includes(" ")||i.includes(`
|
|
3
|
-
`)||i.startsWith("http://")||i.startsWith("https://")||/^\d{4}-\d{2}/.test(i)||/^\d+(\.\d+)?$/.test(i))}function se(i,e,t,r){if(i.includes("@")&&i.includes("/"))return i;if(i.includes(".")){let n=i.indexOf("."),o=i.substring(0,n),s=i.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${i}@${t}`:i}function We(i){return`${i.publisher}/${i.package_}/${i.name}`}function C(i,e,t){return`${i}/${e}/${t}`}function et(i){return`${i.s}|${i.p}|${er(i.o)}`}function er(i){switch(i.kind){case"uri":return`u:${i.key}`;case"literal":return`l:${i.datatype}:${i.lexical}`;case"blank":return`b:${i.id}`}}function A(i,e,t){return{s:i,p:e,o:{kind:"uri",key:t}}}var He=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=et(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),tr(this.byPIdx,e.p,e),tr(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&tr(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(et(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)n.add(o.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)o.o.kind==="uri"&&n.add(o.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${er(r)}`)}};function tr(i,e,t){let r=i.get(e);r?r.push(t):i.set(e,[t])}var qe=class{type=C("kanonak.org","core-rdf","type");subClassOf=C("kanonak.org","core-rdf","subClassOf");subPropertyOf=C("kanonak.org","core-rdf","subPropertyOf");domain=C("kanonak.org","core-rdf","domain");range=C("kanonak.org","core-rdf","range");equivalentClass=C("kanonak.org","core-owl","equivalentClass");equivalentProperty=C("kanonak.org","core-owl","equivalentProperty");inverseOf=C("kanonak.org","core-owl","inverseOf");sameAs=C("kanonak.org","core-owl","sameAs");transitiveProperty=C("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=C("kanonak.org","core-owl","SymmetricProperty")};var Rn={name:"rdfs2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},vn={name:"rdfs3",apply(i,e){let t=!1;for(let r of i.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,e.type,o))&&(t=!0)}return t}},Pn={name:"rdfs5",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subPropertyOf))s.o.kind==="uri"&&i.add(A(n,e.subPropertyOf,s.o.key))&&(t=!0)}return t}},wn={name:"rdfs7",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n)){let a={s:s.s,p:o,o:s.o};i.add(a)&&(t=!0)}}return t}},In={name:"rdfs9",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},Sn={name:"rdfs11",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subClassOf))s.o.kind==="uri"&&i.add(A(n,e.subClassOf,s.o.key))&&(t=!0)}return t}},tt=[Rn,vn,Pn,wn,In,Sn];var An={name:"prp-trp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let o=i.byPredicate(n);for(let s of o){if(s.o.kind!=="uri")continue;let a=s.o.key;for(let c of i.bySubjectPredicate(a,n))c.o.kind==="uri"&&s.s!==c.o.key&&i.add(A(s.s,n,c.o.key))&&(t=!0)}}return t}},Dn={name:"prp-symp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let o of i.byPredicate(n))o.o.kind==="uri"&&i.add(A(o.o.key,n,o.s))&&(t=!0);return t}},Kn={name:"prp-inv1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,o,s.s))&&(t=!0)}return t}},Cn={name:"prp-inv2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(o))s.o.kind==="uri"&&i.add(A(s.o.key,n,s.s))&&(t=!0)}return t}},$n={name:"prp-eqp1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n))i.add({s:s.s,p:o,o:s.o})&&(t=!0)}return t}},jn={name:"prp-eqp2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(o))i.add({s:s.s,p:n,o:s.o})&&(t=!0)}return t}},xn={name:"cax-eqc1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},En={name:"cax-eqc2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,o))i.add(A(s.s,e.type,n))&&(t=!0)}return t}},On={name:"eq-rep-s",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o){for(let s of i.snapshot())s.s===n&&i.add({s:o,p:s.p,o:s.o})&&(t=!0);for(let s of i.snapshot())s.s===o&&i.add({s:n,p:s.p,o:s.o})&&(t=!0)}}return t}},Vn={name:"eq-rep-o",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.snapshot())s.o.kind==="uri"&&(s.o.key===n?i.add(A(s.s,s.p,o))&&(t=!0):s.o.key===o&&i.add(A(s.s,s.p,n))&&(t=!0))}return t}},rt=[An,Dn,Kn,Cn,$n,jn,xn,En,On,Vn];var ze=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=Ge(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(Ge(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(Ge(e),this.vocabulary.type,Ge(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function Ge(i){return typeof i=="string"?i:C(i.publisher,i.package_,i.name)}var kt=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new qe,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new He,n=await new oe().parseKanonaks(e),o=new rr;for(let c of n)if(c instanceof N){let p=Tn(c);if(!p)continue;for(let l of c.statement)this.emitStatement(p,l,t,o)}let s=[...tt];this.profile==="owl-rl-classification"&&s.push(...rt);let a=0;for(;a<this.maxIterations;){let c=!1;for(let p of s)p.apply(t,this.vocabulary)&&(c=!0);if(!c)break;a++}return new ze(t,this.vocabulary)}emitStatement(e,t,r,n){let o=Nn(t);if(o){if(t instanceof W){r.add({s:e,p:o,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof Q){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof ee){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof U){let s=We(t.object.subject);r.add(A(e,o,s));return}if(t instanceof H){let s=n.next();r.add({s:e,p:o,o:{kind:"blank",id:s}}),this.emitEmbedded(s,t.object,r,n);return}if(t instanceof L){for(let s of t.object??[])this.emitListItem(e,o,s,r,n);return}}}emitListItem(e,t,r,n,o){if(r instanceof w)n.add(A(e,t,We(r.subject)));else if(r instanceof _){let s=o.next();n.add({s:e,p:t,o:{kind:"blank",id:s}}),this.emitEmbedded(s,r,n,o)}else if(r instanceof Z){let s=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:s}})}}emitEmbedded(e,t,r,n){let o=`_:${e}`;for(let s of t.statement)this.emitStatement(o,s,r,n)}},rr=class{counter=0;next(){return`b${this.counter++}`}};function Tn(i){let e=i.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let o=r.substring(0,n),s=r.substring(n+1);return!o||!s||!i.name?null:C(o,s,i.name)}function Nn(i){let e=i.predicate;return e?.subject?We(e.subject):null}import _n from"ignore";import*as Rt from"fs";import*as Xe from"path";var bt=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=Xe.join(e,".gitignore");if(Rt.existsSync(t))try{let r=Rt.readFileSync(t,"utf8");this.ignoreInstance=_n(),this.ignoreInstance.add(r)}catch{this.ignoreInstance=null}else this.ignoreInstance=null}shouldIgnore(e){if(!this.ignoreInstance)return!1;let r=Xe.relative(this.basePath,e).split(Xe.sep).join("/");return this.ignoreInstance.ignores(r)}};var vt=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as Un,LineCounter as Ln,isMap as Ye,isPair as O,isScalar as M,isSeq as Pt}from"yaml";var Je=class i{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new i,r=new Ln,n=Un(e,{lineCounter:r});if(n.errors.length>0||!Ye(n.contents))return t;or(n.contents,[],r,t);for(let o of n.contents.items){if(!O(o)||!M(o.key))continue;let s=String(o.key.value),a=o.key.range;if(!a)continue;t.entities.set(s,G(a,r));let c=o.value,p=c&&typeof c=="object"&&"range"in c?c.range:void 0;if(p?t.entityBlocks.set(s,G([a[0],a[1],p[2]],r)):t.entityBlocks.set(s,G(a,r)),Ye(o.value)){let l=new Map,u=new Map,m=new Map;for(let f of o.value.items){if(!O(f)||!M(f.key))continue;let d=String(f.key.value),g=f.key.range;g&&l.set(d,G(g,r));let h=f.value;if(h&&typeof h=="object"&&"range"in h&&Array.isArray(h.range)){let b=h.range;u.set(d,G(b,r))}if(Pt(h)){let b=[];for(let R of h.items)R&&typeof R=="object"&&"range"in R&&Array.isArray(R.range)&&b.push(G(R.range,r));b.length>0&&m.set(d,b)}}l.size>0&&t.properties.set(s,l),u.size>0&&t.propertyValues.set(s,u),m.size>0&&t.valueListItems.set(s,m);let y=Mn(o.value,r);y.length>0&&t.importPackages.set(s,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(nr(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,a;if(o)for(let[c,p]of o)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);if(n)for(let[c,p]of n)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function Mn(i,e){let t=[];if(!Ye(i))return t;let r=i.items.find(n=>O(n)&&M(n.key)&&String(n.key.value)==="imports");if(!r||!O(r)||!Pt(r.value))return t;for(let n of r.value.items){if(!Ye(n))continue;let o=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="publisher");if(!o||!O(o)||!M(o.value))continue;let s=String(o.value.value),a=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="packages");if(!(!a||!O(a)||!Pt(a.value)))for(let c of a.value.items){if(!Ye(c))continue;let p=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="package");if(!p||!O(p)||!M(p.value)||!p.value.range)continue;let l=String(p.value.value),u=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="version"),m=u&&O(u)&&M(u.value)?String(u.value.value):"",y=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="alias"),f=y&&O(y)&&M(y.value)?String(y.value.value):void 0,d=f!==void 0?{publisher:s,package_:l,version:m,alias:f,position:G(p.value.range,e)}:{publisher:s,package_:l,version:m,position:G(p.value.range,e)};t.push(d)}}return t}function nr(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function wr(i,e){let t=i.endLine-i.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function or(i,e,t,r){if(Ye(i)){for(let n of i.items){if(!O(n)||!M(n.key))continue;let o=String(n.key.value),s=[...e,o],a=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(a,G(n.key.range,t));let c=n.value,p=Ir(c);p&&r.setNestedValuePosition(a,G(p,t)),or(c,s,t,r)}return}if(Pt(i)){for(let n=0;n<i.items.length;n++){let o=i.items[n],s=[...e,n],a=JSON.stringify(s),c=Ir(o);c&&r.setNestedValuePosition(a,G(c,t)),or(o,s,t,r)}return}}function Ir(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function G(i,e){let t=e.linePos(i[0]),r=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function Sr(i,e){let r=(e??new $).parse(i),n=Je.fromContent(i);return{document:r,positions:n}}le();le();var wt=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,r){if(e.includes(".")){let o=e.split("."),s=o[0],a=o[1],c=this.findPackageNameForAlias(r,s);if(c){for(let p of t.values())if(p.entityName===a&&p.uri.package_===c)return p.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new T(e,t,r,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===t||!o.alias&&o.packageName===t)return o.packageName;return null}};le();function Ar(i){if(!i||i.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=i.trim(),t=e.split("/");if(t.length===1){let r=t[0];if(!r)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(r.includes("@"))throw new Error(`Invalid Kanonak address: "${i}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:r}}if(t.length===2){let[r,n]=t;if(!r||!n)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let o=n.indexOf("@");if(o===-1)return{kind:"package",publisher:r,package_:n};let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let c=Fn(a);return{kind:"package",publisher:r,package_:s,version:c}}return{kind:"resource",uri:T.parse(e)}}function Dr(i){switch(i.kind){case"publisher":return i.publisher;case"package":return i.version?`${i.publisher}/${i.package_}@${i.version.major}.${i.version.minor}.${i.version.patch}`:`${i.publisher}/${i.package_}`;case"resource":return i.uri.toString()}}function Fn(i){let e=i.split(".").map(Number);return Bn(e[0]||0,e[1]||0,e[2]||0)}function Bn(i,e,t){return{major:i,minor:e,patch:t,toString:()=>`${i}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===i&&r.minor===e&&r.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:r=>i!==r.major?i-r.major:e!==r.minor?e-r.minor:t-r.patch}}async function Cr(i,e){let t=[],r=await i.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,c=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[p,l]of Object.entries(n.body)){if(!l||typeof l!="object")continue;let u=l.type;!u||typeof u!="string"||u!=="Package"&&Wn(u,e)&&t.push({entityName:p,entity:l,documentNamespace:`${s}/${a}@${c}`,publisher:s,package_:a,version:c})}}return t}function Wn(i,e){let t=Kr(i),r=Kr(e);return t===r}function Kr(i){let e=i.lastIndexOf(".");if(e!==-1)return i.substring(e+1);let t=i.lastIndexOf("/");return t!==-1?i.substring(t+1):i}var ue=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var It=class i{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new i;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var me=class i{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&i.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),c=e.split(".")[0],p=new k;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue=n,p.expectedValue=a,p.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(p)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var ye=class i{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){let s=i.VALID_AUGMENTATION_PATTERN.test(n);if(!s&&!r&&i.RESERVED_WORDS.has(n.toLowerCase())){let a=new k;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Entity name '${n}' is a reserved word and cannot be used.`,a.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(a);continue}if(!s&&!i.VALID_NAME_PATTERN.test(n)){let a;/^\d/.test(n)?a="Entity names must start with a letter, not a number.":n.includes(" ")?a="Entity names cannot contain spaces. Use camelCase or underscores instead.":a="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.message=`Invalid entity name '${n}'. ${a}`,c.suggestion=a,t.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!i.VALID_PROPERTIES.has(n)&&!i.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var fe=class i{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let c=[];if(Array.isArray(a))for(let p of a){let l=p?.toString();l&&l==="Property"&&!r&&c.push(l)}else{let p=a?.toString();p&&p==="Property"&&!r&&c.push(p)}for(let p of c){let l=this.getPropertyValue(s,"range"),u=this.determinePropertyType(l),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=p,m.expectedValue=u,m.message=`Invalid property type '${p}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":i.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var de=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||r.includes("."))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=r,c.propertyName="type",c.message=`Subject Kanonak '${r}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
|
|
2
|
+
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("/");if(o===-1)continue;let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)continue;let c=t.get(s);c?c.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=i.parseVersion(e);if(!n)return!1;switch(r){case dt.Any:return!0;case dt.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case dt.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case dt.Major:return n.major!==t.major?!1:n.minor>t.minor?!0:n.minor===t.minor?n.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let r=parseInt(t[0],10),n=parseInt(t[1],10),o=t.length>=3?parseInt(t[2],10):0;return isNaN(r)||isNaN(n)||isNaN(o)?null:{major:r,minor:n,patch:o}}compareVersionStrings(e,t){let r=i.parseVersion(e),n=i.parseVersion(t);return!r&&!n?0:r?n?r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch:1:-1}};var gt=class{parser=new $;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new pe({fetchFn:e.fetchFn}):new pe}async getHighestCompatibleVersionAsync(e,t){let r=await this.publisherIndex.resolveVersion(e,t);if(!r)return null;let n=`${e}/${t.packageName}@${r}`,o=this.documents.get(n);if(o)return o;if(this.getFromCache){let l=this.getFromCache(e,t.packageName,r);if(l){let u=this.parser.parse(l);return this.documents.set(n,u),this.contentCache.set(n,l),u}}let s=await this.publisherIndex.getPackageUrl(e,t.packageName,r),a=this.fetchFn?await this.fetchFn(s,e):await fetch(s);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${s} (${a.status} ${a.statusText})`);let c=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,c);let p=this.parser.parse(c);return this.documents.set(n,p),this.contentCache.set(n,c),p}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,o]=t;return this.publisherIndex.getPackageUrl(r,n,o)}};var z=class{};var re=class extends z{statement=[]};var N=class extends re{namespace;name;icon};var _=class extends re{name};le();var w=class i extends z{subject;static parse(e){let t=new i;return t.subject=T.parse(e),t}};var Z=class extends z{value};var B=class{predicate;object};var X=class extends B{};var W=class i extends X{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=t,r}};var Q=class i extends X{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=t,r}};var ee=class extends X{};var U=class i extends B{static parse(e,t){let r=new i;return r.predicate=w.parse(e),r.object=w.parse(t),r}};var H=class extends B{};var L=class extends B{};le();function E(i){if(Array.isArray(i))return i.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=i?.toString();return e?[e]:[]}var x=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,c]of Object.entries(e.body))if(!a.includes(".")&&c&&typeof c=="object"&&!Array.isArray(c)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new T(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${c}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(c,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${l.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${c}/${l.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[c,p]of Object.entries(e.body))if(!c.includes(".")&&p&&typeof p=="object"&&!Array.isArray(p)&&!n.has(c)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(c,{entityName:c,uri:new T(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,l),entity:p,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((p,l)=>p+l.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${o}`);for(let[p,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${p}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(p,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,t,s),f=0;for(let[d,g]of y.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${u.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${p}/${u.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${p}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=E(s);for(let c of a)if(c===t||await this.isSubclassOfRecursiveAsync(c,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=E(s);for(let c of a)if(c===t||await this.isSubpropertyOfRecursiveAsync(c,t,r,n))return!0}return!1}};var ne=class i{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&i.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return i.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var oe=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new x(e),o=new ne(n);for(let c of r){let p=c.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(c.body)){let m=new N,y=this.resolveCanonicalEntity(l,c,p);m.namespace=y.namespace,m.name=y.name,m.statement=[];let f=await this.parseStatements(u,c,n,o,e);m.statement.push(...f),t.push(m)}}let s=new Map,a=[];for(let c of t)if(c instanceof N){let p=`${c.namespace}/${c.name}`,l=s.get(p);l?l.statement.push(...c.statement):(s.set(p,c),a.push(c))}else a.push(c);return a}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let n=e.indexOf("."),o=e.substring(0,n),s=e.substring(n+1);for(let[a,c]of Object.entries(t.metadata.imports))for(let p of c)if((p.alias??p.packageName)===o){let u=p.version;return{namespace:`${a}/${p.packageName}@${u.major}.${u.minor}.${u.patch}`,name:s}}return{namespace:r,name:e}}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,c]of Object.entries(e))try{let p=await this.getPropertyMetadata(a,t,r,o,n);if(!p)continue;let l=await this.parsePropertyValue(a,c,p,t,r,n);l&&s.push(l)}catch(p){console.error(`Error parsing property ${a}:`,p)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,c=a.type?.toString()??"",p=c.includes(".")?c.substring(c.lastIndexOf(".")+1):c;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let u=o.getPropertyTypeClassification(c),m=a.range?.toString(),y;if(u==="ObjectProperty")y="ObjectProperty";else if(u==="DatatypeProperty")y="DatatypeProperty";else{let d=m&&m.includes(".")?m.substring(m.lastIndexOf(".")+1):m??"";(m?o.isKnownXsdDatatypeName(m):!1)||d==="Literal"?y="DatatypeProperty":y="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:y,range:m,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return W.parse(e,t.toISOString());if(typeof t=="string")return W.parse(e,t);if(typeof t=="number")return Q.parse(e,t);if(typeof t=="boolean"){let n=new ee;return n.predicate=w.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let c=new U;return c.predicate=w.parse(e),c.object=a,c}if(typeof t=="object"&&!Array.isArray(t)){let a=new _;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let l=new H;return l.predicate=w.parse(e),l.object=a,l}let c=[];for(let[l,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new _;m.name=l,m.statement=await this.parseStatements(u,n,o,s,{}),c.push(m)}else if(typeof u=="string"){let m=await this.resolveReference(u,n,o);m&&c.push(m)}if(c.length>0){let l=new L;return l.predicate=w.parse(e),l.object=c,l}let p=new H;return p.predicate=w.parse(e),p.object=a,p}}async parseListValue(e,t,r,n,o,s){let a=[],c=r.propertyType==="DatatypeProperty";for(let l of t){if(c&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new Z;u.value=l,a.push(u);continue}if(c&&l instanceof Date){let u=new Z;u.value=l.toISOString(),a.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,n,o);u&&a.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new _;u.statement=await this.parseStatements(l,n,o,s,{}),a.push(u)}}let p=new L;return p.predicate=w.parse(e),p.object=a,p}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new w;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(le(),hr)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),l=e.substring(0,p),u=e.substring(p+1);if(t.metadata?.imports){for(let[m,y]of Object.entries(t.metadata.imports))for(let f of y)if((f.alias??f.packageName)===l){let g=new w;return g.subject=new s(m,f.packageName,u,f.version),g}}}let c=new w;return c.subject=new s(o.publisher,o.package_,e,a),c}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof N&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),a=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,a)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof N&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new $().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let c of s.statement){let[p,l]=this.convertStatementToProperty(c);p&&l!==null&&l!==void 0&&(a[p]=l),this.collectImportsFromStatement(c,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof W)return[e.predicate.subject.name,e.object];if(e instanceof Q)return[e.predicate.subject.name,e.object];if(e instanceof ee)return[e.predicate.subject.name,e.object];if(e instanceof U)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof L){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof H){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof w?t.push(r.subject.name):r instanceof _&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var fn=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),kr={Class:{publisher:"kanonak.org",package_:"core-owl"},ObjectProperty:{publisher:"kanonak.org",package_:"core-owl"},DatatypeProperty:{publisher:"kanonak.org",package_:"core-owl"},AnnotationProperty:{publisher:"kanonak.org",package_:"core-owl"},Property:{publisher:"kanonak.org",package_:"core-rdf"},Datatype:{publisher:"kanonak.org",package_:"core-rdfs"},Resource:{publisher:"kanonak.org",package_:"core-rdfs"},Literal:{publisher:"kanonak.org",package_:"core-rdfs"},Thing:{publisher:"kanonak.org",package_:"core-owl"},Nothing:{publisher:"kanonak.org",package_:"core-owl"}};function Y(i){let e=i;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=kr[t];return r?{publisher:r.publisher,package_:r.package_,name:t}:{publisher:"",package_:"",name:t}}}if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t.object?.subject){let r=t.object.subject;if(!r.publisher&&!r.package_||r.publisher===""&&r.package_===""){let n=kr[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function te(i,e){return fn.has(`${i}/${e}`)}var I=class i{static getTypeUri(e){return Y(e)}static isCoreOntologyType(e){return te(e.publisher,e.package_)}static isClassType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=Y(e);return t?te(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=Y(e);return!t||!te(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=Y(e);return!t||!te(t.publisher,t.package_)?!1:t.name==="Class"||t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"||t.name==="Datatype"}static isInstanceOfKnownClass(e,t){if(i.isSchemaDefinitionType(e))return!1;let r=Y(e);return r?t.has(r.name):!1}};var Jt=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(Jt||{}),Zt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(Zt||{}),ht=class{static async buildFromRepository(e){let r=await new oe().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,c=new Set,p=new Map;for(let u of r){let m=u;m.name&&(I.isClassType(m)&&a.add(m.name),(I.isObjectPropertyType(m)||I.isGenericPropertyType(m))&&c.add(m.name))}for(let u of n)for(let[m,y]of Object.entries(u.body))c.has(m)&&y?.range&&typeof y.range=="string"&&p.set(m,y.range);let l=new Map;for(let u of r){let m=u;m.name&&l.set(m.name,m)}for(let u of n){let m=u.metadata.namespace_,y=m?`${m.publisher}/${m.package_}`:"",f=m?.version?`${m.version.major}.${m.version.minor}.${m.version.patch}`:"",d=br(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let k=l.get(g),R="Unknown";if(k){let V=k;I.isClassType(V)?R="Class":I.isObjectPropertyType(V)?R="ObjectProperty":I.isDatatypePropertyType(V)?R="DatatypeProperty":I.isAnnotationPropertyType(V)?R="AnnotationProperty":I.isDatatypeType(V)?R="Datatype":I.isGenericPropertyType(V)?R="ObjectProperty":I.isInstanceOfKnownClass(V,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,j={};for(let[V,qt]of Object.entries(h))V!=="type"&&(typeof qt!="object"||qt===null)&&(j[V]=qt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:j}),Rr(v,h,R,a,c,s,y,f,d),Yt(v,h,c,p,o,s,y,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,c=new Set,p=new Map,l=br(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(gn(d,l)&&a.add(y),hn(d,l)&&(c.add(y),f.range&&typeof f.range=="string"&&p.set(y,f.range)))}for(let[y,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=kn(d,y,a,l),h=s&&o?`${s}/${y}@${o}`:y,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??y,type:g,namespace:s,properties:k}),Rr(h,f,g,a,c,r,s,o,l),Yt(h,f,c,p,t,r,s,o,l)}let u=new Set(t.map(y=>y.id)),m=r.filter(y=>u.has(y.source)&&u.has(y.target));return{nodes:t,edges:m}}};function br(i,e){let t=new Map;if(i.metadata?.imports)for(let[r,n]of Object.entries(i.metadata.imports))for(let o of n){let s=o.alias??o.packageName,a=o.version,c=`${a.major}.${a.minor}.${a.patch}`;t.set(s,{publisher:r,package_:o.packageName,version:c})}return t}var vr={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},dn=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Qt(i,e){if(i.includes(".")){let t=i.indexOf("."),r=i.substring(0,t),n=i.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function gn(i,e){let t=Qt(i,e);return t?vr[t]==="Class":!1}function hn(i,e){let t=Qt(i,e);return t?dn.has(t):!1}function kn(i,e,t,r){if(!i||i==="Package")return"Unknown";let n=Qt(i,r);if(n){let s=vr[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=i.split(".").pop()??i;return t.has(o)?"Instance":"Unknown"}var Pr=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Rr(i,e,t,r,n,o,s,a,c){let p=e.type,l=e.subClassOf;if(l){let f=Array.isArray(l)?l:[l];for(let d of f)typeof d=="string"&&o.push({source:i,target:se(d,s,a,c),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let f=Array.isArray(u)?u:[u];for(let d of f)typeof d=="string"&&o.push({source:i,target:se(d,s,a,c),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&p){let f=p.split(".").pop()??p;o.push({source:i,target:se(f,s,a,c),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Pr.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&bn(h)&&o.push({source:i,target:se(h,s,a,c),type:"propertyValue",label:f,propertyId:se(f,s,a,c)})}let m=t==="ObjectProperty"||t==="DatatypeProperty",y=e.domain&&e.range;if((m||y)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:se(f,s,a,c),target:se(d,s,a,c),type:"objectRelationship",label:e.label??i.split("/").pop()??"",propertyId:i})}}function Yt(i,e,t,r,n,o,s,a,c){for(let[p,l]of Object.entries(e)){if(Pr.has(p)||typeof l!="object"||l===null||Array.isArray(l))continue;let u=l,m=`${i}/${p}`,y=r.get(p),f=y?y.split(".").pop()??y:"Unknown",d={};for(let[h,k]of Object.entries(u))(typeof k!="object"||k===null)&&(d[h]=k);n.push({id:m,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${p}@${a}`:p;o.push({source:i,target:m,type:"propertyValue",label:p,propertyId:t.has(p)?g:void 0}),y&&o.push({source:m,target:se(f,s,a,c),type:"instanceOf",label:"type (inferred)"}),Yt(m,u,t,r,n,o,s,a,c)}}function bn(i){return!(!i||i.includes(" ")||i.includes(`
|
|
3
|
+
`)||i.startsWith("http://")||i.startsWith("https://")||/^\d{4}-\d{2}/.test(i)||/^\d+(\.\d+)?$/.test(i))}function se(i,e,t,r){if(i.includes("@")&&i.includes("/"))return i;if(i.includes(".")){let n=i.indexOf("."),o=i.substring(0,n),s=i.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${i}@${t}`:i}function We(i){return`${i.publisher}/${i.package_}/${i.name}`}function C(i,e,t){return`${i}/${e}/${t}`}function et(i){return`${i.s}|${i.p}|${er(i.o)}`}function er(i){switch(i.kind){case"uri":return`u:${i.key}`;case"literal":return`l:${i.datatype}:${i.lexical}`;case"blank":return`b:${i.id}`}}function A(i,e,t){return{s:i,p:e,o:{kind:"uri",key:t}}}var He=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=et(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),tr(this.byPIdx,e.p,e),tr(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&tr(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(et(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)n.add(o.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let o of r)o.o.kind==="uri"&&n.add(o.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${er(r)}`)}};function tr(i,e,t){let r=i.get(e);r?r.push(t):i.set(e,[t])}var qe=class{type=C("kanonak.org","core-rdf","type");subClassOf=C("kanonak.org","core-rdf","subClassOf");subPropertyOf=C("kanonak.org","core-rdf","subPropertyOf");domain=C("kanonak.org","core-rdf","domain");range=C("kanonak.org","core-rdf","range");equivalentClass=C("kanonak.org","core-owl","equivalentClass");equivalentProperty=C("kanonak.org","core-owl","equivalentProperty");inverseOf=C("kanonak.org","core-owl","inverseOf");sameAs=C("kanonak.org","core-owl","sameAs");transitiveProperty=C("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=C("kanonak.org","core-owl","SymmetricProperty")};var Rn={name:"rdfs2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},vn={name:"rdfs3",apply(i,e){let t=!1;for(let r of i.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,e.type,o))&&(t=!0)}return t}},Pn={name:"rdfs5",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subPropertyOf))s.o.kind==="uri"&&i.add(A(n,e.subPropertyOf,s.o.key))&&(t=!0)}return t}},wn={name:"rdfs7",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n)){let a={s:s.s,p:o,o:s.o};i.add(a)&&(t=!0)}}return t}},In={name:"rdfs9",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},Sn={name:"rdfs11",apply(i,e){let t=!1;for(let r of i.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.bySubjectPredicate(o,e.subClassOf))s.o.kind==="uri"&&i.add(A(n,e.subClassOf,s.o.key))&&(t=!0)}return t}},tt=[Rn,vn,Pn,wn,In,Sn];var An={name:"prp-trp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let o=i.byPredicate(n);for(let s of o){if(s.o.kind!=="uri")continue;let a=s.o.key;for(let c of i.bySubjectPredicate(a,n))c.o.kind==="uri"&&s.s!==c.o.key&&i.add(A(s.s,n,c.o.key))&&(t=!0)}}return t}},Dn={name:"prp-symp",apply(i,e){let t=!1,r=i.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let o of i.byPredicate(n))o.o.kind==="uri"&&i.add(A(o.o.key,n,o.s))&&(t=!0);return t}},Kn={name:"prp-inv1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(n))s.o.kind==="uri"&&i.add(A(s.o.key,o,s.s))&&(t=!0)}return t}},Cn={name:"prp-inv2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;for(let s of i.byPredicate(o))s.o.kind==="uri"&&i.add(A(s.o.key,n,s.s))&&(t=!0)}return t}},$n={name:"prp-eqp1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(n))i.add({s:s.s,p:o,o:s.o})&&(t=!0)}return t}},xn={name:"prp-eqp2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicate(o))i.add({s:s.s,p:n,o:s.o})&&(t=!0)}return t}},jn={name:"cax-eqc1",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,n))i.add(A(s.s,e.type,o))&&(t=!0)}return t}},En={name:"cax-eqc2",apply(i,e){let t=!1;for(let r of i.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.byPredicateObject(e.type,o))i.add(A(s.s,e.type,n))&&(t=!0)}return t}},On={name:"eq-rep-s",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o){for(let s of i.snapshot())s.s===n&&i.add({s:o,p:s.p,o:s.o})&&(t=!0);for(let s of i.snapshot())s.s===o&&i.add({s:n,p:s.p,o:s.o})&&(t=!0)}}return t}},Vn={name:"eq-rep-o",apply(i,e){let t=!1;for(let r of i.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,o=r.o.key;if(n!==o)for(let s of i.snapshot())s.o.kind==="uri"&&(s.o.key===n?i.add(A(s.s,s.p,o))&&(t=!0):s.o.key===o&&i.add(A(s.s,s.p,n))&&(t=!0))}return t}},rt=[An,Dn,Kn,Cn,$n,xn,jn,En,On,Vn];var ze=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=Ge(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=Ge(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(Ge(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(Ge(e),this.vocabulary.type,Ge(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function Ge(i){return typeof i=="string"?i:C(i.publisher,i.package_,i.name)}var kt=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new qe,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new He,n=await new oe().parseKanonaks(e),o=new rr;for(let c of n)if(c instanceof N){let p=Tn(c);if(!p)continue;for(let l of c.statement)this.emitStatement(p,l,t,o)}let s=[...tt];this.profile==="owl-rl-classification"&&s.push(...rt);let a=0;for(;a<this.maxIterations;){let c=!1;for(let p of s)p.apply(t,this.vocabulary)&&(c=!0);if(!c)break;a++}return new ze(t,this.vocabulary)}emitStatement(e,t,r,n){let o=Nn(t);if(o){if(t instanceof W){r.add({s:e,p:o,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof Q){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof ee){r.add({s:e,p:o,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof U){let s=We(t.object.subject);r.add(A(e,o,s));return}if(t instanceof H){let s=n.next();r.add({s:e,p:o,o:{kind:"blank",id:s}}),this.emitEmbedded(s,t.object,r,n);return}if(t instanceof L){for(let s of t.object??[])this.emitListItem(e,o,s,r,n);return}}}emitListItem(e,t,r,n,o){if(r instanceof w)n.add(A(e,t,We(r.subject)));else if(r instanceof _){let s=o.next();n.add({s:e,p:t,o:{kind:"blank",id:s}}),this.emitEmbedded(s,r,n,o)}else if(r instanceof Z){let s=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:s}})}}emitEmbedded(e,t,r,n){let o=`_:${e}`;for(let s of t.statement)this.emitStatement(o,s,r,n)}},rr=class{counter=0;next(){return`b${this.counter++}`}};function Tn(i){let e=i.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let o=r.substring(0,n),s=r.substring(n+1);return!o||!s||!i.name?null:C(o,s,i.name)}function Nn(i){let e=i.predicate;return e?.subject?We(e.subject):null}import _n from"ignore";import*as Rt from"fs";import*as Xe from"path";var bt=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=Xe.join(e,".gitignore");if(Rt.existsSync(t))try{let r=Rt.readFileSync(t,"utf8");this.ignoreInstance=_n(),this.ignoreInstance.add(r)}catch{this.ignoreInstance=null}else this.ignoreInstance=null}shouldIgnore(e){if(!this.ignoreInstance)return!1;let r=Xe.relative(this.basePath,e).split(Xe.sep).join("/");return this.ignoreInstance.ignores(r)}};var vt=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as Un,LineCounter as Ln,isMap as Ye,isPair as O,isScalar as M,isSeq as Pt}from"yaml";var Je=class i{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new i,r=new Ln,n=Un(e,{lineCounter:r});if(n.errors.length>0||!Ye(n.contents))return t;or(n.contents,[],r,t);for(let o of n.contents.items){if(!O(o)||!M(o.key))continue;let s=String(o.key.value),a=o.key.range;if(!a)continue;t.entities.set(s,G(a,r));let c=o.value,p=c&&typeof c=="object"&&"range"in c?c.range:void 0;if(p?t.entityBlocks.set(s,G([a[0],a[1],p[2]],r)):t.entityBlocks.set(s,G(a,r)),Ye(o.value)){let l=new Map,u=new Map,m=new Map;for(let f of o.value.items){if(!O(f)||!M(f.key))continue;let d=String(f.key.value),g=f.key.range;g&&l.set(d,G(g,r));let h=f.value;if(h&&typeof h=="object"&&"range"in h&&Array.isArray(h.range)){let k=h.range;u.set(d,G(k,r))}if(Pt(h)){let k=[];for(let R of h.items)R&&typeof R=="object"&&"range"in R&&Array.isArray(R.range)&&k.push(G(R.range,r));k.length>0&&m.set(d,k)}}l.size>0&&t.properties.set(s,l),u.size>0&&t.propertyValues.set(s,u),m.size>0&&t.valueListItems.set(s,m);let y=Mn(o.value,r);y.length>0&&t.importPackages.set(s,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(nr(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,a;if(o)for(let[c,p]of o)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);if(n)for(let[c,p]of n)nr(p,e,t)&&(!a||wr(p,a))&&(s=c,a=p);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function Mn(i,e){let t=[];if(!Ye(i))return t;let r=i.items.find(n=>O(n)&&M(n.key)&&String(n.key.value)==="imports");if(!r||!O(r)||!Pt(r.value))return t;for(let n of r.value.items){if(!Ye(n))continue;let o=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="publisher");if(!o||!O(o)||!M(o.value))continue;let s=String(o.value.value),a=n.items.find(c=>O(c)&&M(c.key)&&String(c.key.value)==="packages");if(!(!a||!O(a)||!Pt(a.value)))for(let c of a.value.items){if(!Ye(c))continue;let p=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="package");if(!p||!O(p)||!M(p.value)||!p.value.range)continue;let l=String(p.value.value),u=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="version"),m=u&&O(u)&&M(u.value)?String(u.value.value):"",y=c.items.find(g=>O(g)&&M(g.key)&&String(g.key.value)==="alias"),f=y&&O(y)&&M(y.value)?String(y.value.value):void 0,d=f!==void 0?{publisher:s,package_:l,version:m,alias:f,position:G(p.value.range,e)}:{publisher:s,package_:l,version:m,position:G(p.value.range,e)};t.push(d)}}return t}function nr(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function wr(i,e){let t=i.endLine-i.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function or(i,e,t,r){if(Ye(i)){for(let n of i.items){if(!O(n)||!M(n.key))continue;let o=String(n.key.value),s=[...e,o],a=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(a,G(n.key.range,t));let c=n.value,p=Ir(c);p&&r.setNestedValuePosition(a,G(p,t)),or(c,s,t,r)}return}if(Pt(i)){for(let n=0;n<i.items.length;n++){let o=i.items[n],s=[...e,n],a=JSON.stringify(s),c=Ir(o);c&&r.setNestedValuePosition(a,G(c,t)),or(o,s,t,r)}return}}function Ir(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function G(i,e){let t=e.linePos(i[0]),r=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function Sr(i,e){let r=(e??new $).parse(i),n=Je.fromContent(i);return{document:r,positions:n}}le();le();var wt=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,r){if(e.includes(".")){let o=e.split("."),s=o[0],a=o[1],c=this.findPackageNameForAlias(r,s);if(c){for(let p of t.values())if(p.entityName===a&&p.uri.package_===c)return p.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new T(e,t,r,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===t||!o.alias&&o.packageName===t)return o.packageName;return null}};le();function Ar(i){if(!i||i.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=i.trim(),t=e.split("/");if(t.length===1){let r=t[0];if(!r)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(r.includes("@"))throw new Error(`Invalid Kanonak address: "${i}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:r}}if(t.length===2){let[r,n]=t;if(!r||!n)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let o=n.indexOf("@");if(o===-1)return{kind:"package",publisher:r,package_:n};let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)throw new Error(`Invalid Kanonak address: "${i}". Expected publisher/package[@version].`);let c=Fn(a);return{kind:"package",publisher:r,package_:s,version:c}}return{kind:"resource",uri:T.parse(e)}}function Dr(i){switch(i.kind){case"publisher":return i.publisher;case"package":return i.version?`${i.publisher}/${i.package_}@${i.version.major}.${i.version.minor}.${i.version.patch}`:`${i.publisher}/${i.package_}`;case"resource":return i.uri.toString()}}function Fn(i){let e=i.split(".").map(Number);return Bn(e[0]||0,e[1]||0,e[2]||0)}function Bn(i,e,t){return{major:i,minor:e,patch:t,toString:()=>`${i}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===i&&r.minor===e&&r.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:r=>i!==r.major?i-r.major:e!==r.minor?e-r.minor:t-r.patch}}async function Cr(i,e){let t=[],r=await i.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,c=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[p,l]of Object.entries(n.body)){if(!l||typeof l!="object")continue;let u=l.type;!u||typeof u!="string"||u!=="Package"&&Wn(u,e)&&t.push({entityName:p,entity:l,documentNamespace:`${s}/${a}@${c}`,publisher:s,package_:a,version:c})}}return t}function Wn(i,e){let t=Kr(i),r=Kr(e);return t===r}function Kr(i){let e=i.lastIndexOf(".");if(e!==-1)return i.substring(e+1);let t=i.lastIndexOf("/");return t!==-1?i.substring(t+1):i}var ue=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var 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 It=class i{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new i;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var me=class i{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&i.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),c=e.split(".")[0],p=new b;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue=n,p.expectedValue=a,p.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(p)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var ye=class i{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){let s=i.VALID_AUGMENTATION_PATTERN.test(n);if(!s&&!r&&i.RESERVED_WORDS.has(n.toLowerCase())){let a=new b;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Entity name '${n}' is a reserved word and cannot be used.`,a.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(a);continue}if(!s&&!i.VALID_NAME_PATTERN.test(n)){let a;/^\d/.test(n)?a="Entity names must start with a letter, not a number.":n.includes(" ")?a="Entity names cannot contain spaces. Use camelCase or underscores instead.":a="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new b;c.ruleType=this.ruleName,c.severity="Error",c.entityName=n,c.message=`Invalid entity name '${n}'. ${a}`,c.suggestion=a,t.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!i.VALID_PROPERTIES.has(n)&&!i.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new 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 fe=class i{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let c=[];if(Array.isArray(a))for(let p of a){let l=p?.toString();l&&l==="Property"&&!r&&c.push(l)}else{let p=a?.toString();p&&p==="Property"&&!r&&c.push(p)}for(let p of c){let l=this.getPropertyValue(s,"range"),u=this.determinePropertyType(l),m=new b;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=p,m.expectedValue=u,m.message=`Invalid property type '${p}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":i.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var de=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||r.includes("."))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let c=new b;c.ruleType=this.ruleName,c.severity="Error",c.entityName=r,c.propertyName="type",c.message=`Subject Kanonak '${r}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
|
|
4
4
|
type: Scene
|
|
5
5
|
|
|
6
|
-
Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,c.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(c)}}return t}};var ge=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,t){let r=[],n=new
|
|
6
|
+
Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,c.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(c)}}return t}};var ge=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,t){let r=[],n=new x(t),o=await this.buildPropertyRangeMap(e,n);for(let[s,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.checkEmbeddedTypes(s,a,void 0,o,n,e,r,0);return r}pickRange(e,t,r){if(e.length===0)return;if(e.length===1)return e[0].range;let n=t.indexOf(".");if(n>0){let o=t.substring(0,n),s=e.find(a=>a.declaringAlias===o);if(s)return s.range}if(r){let o=this.localName(r),s=e.find(a=>this.localName(a.domain)===o);if(s)return s.range}return e[0].range}async checkEmbeddedTypes(e,t,r,n,o,s,a,c){if(c>0){let l=t.type;if(l!=null){let u=await this.validateEmbeddedType(e,String(l),r,o,s);u&&a.push(u)}}let p=t.type!==void 0&&t.type!==null?String(t.type):void 0;for(let[l,u]of Object.entries(t)){let m=this.localName(l),y=n.get(m),d=(y!==void 0?this.pickRange(y,l,p):void 0)??r;if(typeof u=="object"&&u!==null)if(Array.isArray(u))for(let g=0;g<u.length;g++){let h=u[g];typeof h=="object"&&h!==null&&!Array.isArray(h)&&await this.checkEmbeddedTypes(`${e}.${l}[${g}]`,h,d,n,o,s,a,c+1)}else await this.checkEmbeddedTypes(`${e}.${l}`,u,d,n,o,s,a,c+1)}}async validateEmbeddedType(e,t,r,n,o){if(t.length===0||!r)return null;let s=this.localName(t),a=this.localName(r);if(a==="Resource"||a==="Class")return null;let c=e.split(".")[0];if(s===a){let l=new b;return l.ruleType=this.ruleName,l.severity="Warning",l.entityName=c,l.propertyName=e,l.actualValue=t,l.expectedValue=r,l.message=`Embedded object at '${e}' declares 'type: ${t}', which equals the parent property's range '${r}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,l.suggestion=`Remove the 'type: ${t}' line, or keep it if explicitness is preferred over concision.`,l}if(await n.isSubclassOfAsync(t,r,o)||(s!==t||a!==r)&&await n.isSubclassOfAsync(s,a,o))return null;let p=new b;return p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue=t,p.expectedValue=r,p.message=`Embedded object at '${e}' has 'type: ${t}', which is not a subclass of the parent property's range '${r}'.`,p.suggestion=`Either remove the 'type: ${t}' line (so the type is inferred from the property's range '${r}'), or add 'subClassOf: ${r}' to the '${t}' class definition so the relationship holds.`,p}localName(e){let t=e.lastIndexOf(".");return t<0||t===e.length-1?e:e.substring(t+1)}async buildPropertyRangeMap(e,t){let r=new Map,n=await t.buildEntityIndexAsync(e),o=new Map;for(let[s,a]of n){let c=a.entity.type;if(c==null)continue;let p=String(c),l=this.localName(p);if(!(l==="Property"||l==="DatatypeProperty"||l==="ObjectProperty"||l==="AnnotationProperty"))continue;let m=a.entity.range;if(m==null)continue;let y=String(m);if(y.length===0)continue;let f=a.entity.domain,d=f!=null?String(f):"",g=a.uri.toString(),h=o.get(g),k=s.includes(".");(!h||k&&!h.entityName.includes("."))&&o.set(g,{entityName:s,domain:d,range:y})}for(let s of o.values()){let a=this.localName(s.entityName),c=s.entityName.indexOf("."),p=c>0?s.entityName.substring(0,c):void 0,l=r.get(a)??[];l.push({domain:s.domain,range:s.range,declaringAlias:p}),r.set(a,l)}return r}};var he=class{ruleName="ImportExistence";async validateAsync(e,t){let r=[];if(!e.metadata?.imports)return r;let n=await t.getAllDocumentsAsync();for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!await t.getHighestCompatibleVersionAsync(o,a)){let p=await this.determineImportErrorAsync(t,o,a,n),l=new b;l.ruleType=this.ruleName,l.severity="Error",l.message=p.message,l.suggestion=p.suggestion,l.entityName=`Import: ${o}/${a.packageName}`,l.actualValue=a.toString(),l.expectedValue=p.expectedValue,r.push(l)}return r}async determineImportErrorAsync(e,t,r,n){let o=await e.getDocumentsByNamespaceAsync(t,r.packageName);if(o.length===0){let p=n.filter(y=>y.metadata.namespace_?.publisher===t).map(y=>y.metadata.namespace_.package_).filter((y,f,d)=>d.indexOf(y)===f),l=this.findSimilarPackages(r.packageName,p),u=`Import '${t}/${r.package_}' not found - package does not exist`,m=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:p.length>0?`Available packages in ${t}: ${p.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:u,suggestion:m,expectedValue:"Existing package"}}let a=o.filter(p=>p.metadata.namespace_?.version).map(p=>p.metadata.namespace_.version.toString()).sort().join(", "),c=this.getAcceptableVersionRange(r);return{message:`Import '${t}/${r.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${c}`,expectedValue:c}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let r=t.filter(s=>s.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(s.toLowerCase()));if(r.length>0)return r.sort((s,a)=>s.length-a.length);let n=t.map(s=>({package:s,distance:this.levenshteinDistance(e.toLowerCase(),s.toLowerCase())})).sort((s,a)=>s.distance-a.distance),o=Math.max(3,Math.floor(e.length*.4));return n.filter(s=>s.distance<=o).map(s=>s.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let r=e.length,n=t.length,o=Array(r+1).fill(null).map(()=>Array(n+1).fill(0));for(let s=0;s<=r;s++)o[s][0]=s;for(let s=0;s<=n;s++)o[0][s]=s;for(let s=1;s<=r;s++)for(let a=1;a<=n;a++){let c=e[s-1]===t[a-1]?0:1;o[s][a]=Math.min(Math.min(o[s-1][a]+1,o[s][a-1]+1),o[s-1][a-1]+c)}return o[r][n]}};var ke=class{ruleName="UnresolvedReference";async validateAsync(e,t){let r=[],n=new x(t),o=await n.buildEntityIndexAsync(e),s=new Set;for(let[a,c]of o.entries()){let p=c.entity.type;if(p){let l=p.toString();(l==="ObjectProperty"||l.endsWith(".ObjectProperty"))&&s.add(a)}}for(let[a,c]of Object.entries(e.body)){if(!c||typeof c!="object"||Array.isArray(c))continue;let p=c,l=this.getPropertyValue(p,"type");if(!(!l||l==="Class"||l.endsWith("Property")||l==="AnnotationProperty"))for(let[u,m]of Object.entries(p))u==="type"||u==="label"||u==="comment"||!(s.has(u)||Array.from(s).some(f=>f.endsWith(`.${u}`)))||await this.validateReferenceValue(a,u,m,e,n,r)}return r}async validateReferenceValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string")await o.resolveEntityAsync(r,n)||s.push(this.createUnresolvedReferenceError(e,t,r));else if(Array.isArray(r))for(let a=0;a<r.length;a++){let c=r[a];typeof c=="string"&&(await o.resolveEntityAsync(c,n)||s.push(this.createUnresolvedReferenceError(e,`${t}[${a}]`,c)))}}}createUnresolvedReferenceError(e,t,r){let n=`The entity '${r}' cannot be found in the current document or any imported namespaces.
|
|
7
7
|
|
|
8
8
|
Possible solutions:
|
|
9
9
|
\u2022 Add import if the entity is defined in another namespace:
|
|
10
10
|
kanonak namespace add-import <publisher>/<package>@<version>
|
|
11
11
|
\u2022 Check for typos in the reference name '${r}'
|
|
12
12
|
\u2022 Define '${r}' in the current namespace or an appropriate namespace
|
|
13
|
-
\u2022 Use 'kanonak search type ${r} --include-imports' to locate the entity`,o=new k;return o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=t,o.actualValue=r,o.message=`Reference to '${r}' could not be resolved`,o.suggestion=n,o.expectedValue="A valid entity reference that exists in the current document or imported namespaces",o}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}};var be=class{ruleName="TypeAmbiguity";async validateAsync(e,t){let r=[],n=new Map,o=[];if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){o.push({doc:p,import:c,publisher:s});let l=await this.getTransitiveImportsAsync(t,p,new Set);o.push(...l.map(u=>({doc:u,import:null,publisher:s})))}}for(let{doc:s,import:a}of o){let c=s.metadata?.namespace_?.toString()??"unknown";for(let p of Object.keys(s.body))n.has(p)||n.set(p,[]),n.get(p).push({namespace:c,import:a})}for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a;this.checkAmbiguousReference(c,"type",n,s,r),this.checkAmbiguousReference(c,"subClassOf",n,s,r),this.checkAmbiguousReference(c,"subPropertyOf",n,s,r),this.checkAmbiguousReference(c,"domain",n,s,r),this.checkAmbiguousReference(c,"range",n,s,r)}return r}checkAmbiguousReference(e,t,r,n,o){let s=e[t];if(!s)return;let a=E(s);for(let c of a){if(c.includes("."))continue;let p=r.get(c);if(p&&p.length>1){let l=p.map(f=>f.namespace).join(", "),u=[];for(let{namespace:f,import:d}of p)if(d?.alias)u.push(`${d.alias}.${c}`);else{let g=f.split("/"),b=g[g.length-1]?.split("@")[0]??"alias";u.push(`${b}.${c}`)}let m=u.length>0?`Use one of: ${u.join(", ")}`:"Consider adding namespace aliases to your imports",y=new k;y.ruleType=this.ruleName,y.severity="Warning",y.entityName=n,y.propertyName=t,y.actualValue=c,y.message=`Type '${c}' is ambiguous. It's defined in: ${l}`,y.suggestion=m,o.push(y)}}}async getTransitiveImportsAsync(e,t,r){let n=[],o=t.metadata?.namespace_?.toString()??"";if(r.has(o))return n;if(r.add(o),t.metadata?.imports)for(let[s,a]of Object.entries(t.metadata.imports))for(let c of a){let p=await e.getHighestCompatibleVersionAsync(s,c);if(p){n.push(p);let l=await this.getTransitiveImportsAsync(e,p,r);n.push(...l)}}return n}};var Re=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildClassHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a,p=c.type,l=c.subClassOf;if(p?.toString()==="Class"&&l){let u=s,m=this.detectCycle(u,n);if(m){let y=m.join(" \u2192 "),f=new k;f.ruleType=this.ruleName,f.severity="Error",f.message=`Circular class hierarchy detected: ${y}`,f.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",f.entityName=u,f.propertyName="subClassOf",f.actualValue=y,r.push(f);break}}}return r}async buildClassHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a,p=c.type,l=c.subClassOf;if(p?.toString()==="Class"&&l){let u=E(l);u.length>0&&r.set(s,u)}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);p&&await this.buildClassHierarchy(p,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var ve=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildPropertyHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&a.subPropertyOf){let l=s,u=this.detectCycle(l,n);if(u){let m=u.join(" \u2192 "),y=new k;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=l,y.propertyName="subPropertyOf",y.actualValue=m,r.push(y);break}}return r}async buildPropertyHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a,p=c.type;if(p){let l=p.toString();if(l==="DatatypeProperty"||l==="ObjectProperty"||l==="AnnotationProperty"){let u=c.subPropertyOf;if(u){let m=E(u);m.length>0&&r.set(s,m)}}}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);p&&await this.buildPropertyHierarchy(p,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var Pe=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,t){let r=[];for(let[n,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o))continue;let s=o,a=s.type?.toString();if(a==="DatatypeProperty"||a==="ObjectProperty"||a?.endsWith(".DatatypeProperty")||a?.endsWith(".ObjectProperty")){let c="range"in s,p=s.range?.toString().trim();if(!c||!p){let l=new k;l.ruleType=this.ruleName,l.severity="Error",l.entityName=n,l.propertyName="range",l.message=`Property '${n}' must have a 'range' defined.`,l.suggestion=a==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",l.expectedValue=a==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",r.push(l)}}}return r}};var we=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();(c==="Class"||c&&c.endsWith(".Class"))&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=E(s.subClassOf);for(let p=0;p<c.length;p++){let l=c[p];if(this.builtInClasses.has(l)||n.has(l))continue;if(!await this.isClassAvailableInImports(e,t,l)){let m=c.length>1?`[${p}]`:"",y=new k;y.ruleType=this.ruleName,y.severity="Error",y.message=`Class '${l}' referenced in subClassOf${m} is not defined or imported`,y.suggestion=`Define '${l}' as a Class, or import a namespace that contains it`,y.entityName=o,y.propertyName="subClassOf",y.actualValue=l,y.expectedValue="Defined or imported class",r.push(y)}}}return r}async isClassAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){if(n!==null&&c.alias!==n)continue;let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=n!==null?o:r,u=p.body[l];if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u.type?.toString();if(f==="Class"||f&&f.endsWith(".Class"))return!0}let m=new Set;if(await this.isClassAvailableInImportsRecursive(p,t,l,m))return!0}}return!1}async isClassAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="Class"||m&&m.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var Ie=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty")&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=E(s.subPropertyOf);for(let p=0;p<c.length;p++){let l=c[p];if(this.builtInProperties.has(l)||n.has(l))continue;if(!await this.isPropertyAvailableInImports(e,t,l)){let m=c.length>1?`[${p}]`:"",y=new k;y.ruleType=this.ruleName,y.severity="Error",y.message=`Property '${l}' referenced in subPropertyOf${m} is not defined or imported`,y.suggestion=`Define '${l}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,y.entityName=o,y.propertyName="subPropertyOf",y.actualValue=l,y.expectedValue="Defined or imported property",r.push(y)}}}return r}async isPropertyAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){if(n!==null&&c.alias!==n)continue;let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=n!==null?o:r,u=p.body[l];if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u.type?.toString();if(f==="DatatypeProperty"||f==="ObjectProperty"||f==="AnnotationProperty")return!0}let m=new Set;if(await this.isPropertyAvailableInImportsRecursive(p,t,l,m))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var Se=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let r=[],n=e.metadata.namespace_?.toString();if(!n)return r;let o=new Map,s=new Set;await this.buildImportGraph(e,t,o,s);let a=this.detectCycle(n,o);if(a){let c=a.join(" \u2192 "),p=new k;p.ruleType=this.ruleName,p.severity="Error",p.message=`Circular namespace import detected: ${c}`,p.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",p.entityName="imports",p.propertyName="imports",p.actualValue=c,r.push(p)}return r}async buildImportGraph(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!(!o||n.has(o))&&(n.add(o),e.metadata.imports)){let s=[];for(let[a,c]of Object.entries(e.metadata.imports))for(let p of c){let l=`${a}/${p.packageName}@${p.version}`;s.push(l);let u=await t.getHighestCompatibleVersionAsync(a,p);u&&await this.buildImportGraph(u,t,r,n)}s.length>0&&r.set(o,s)}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){let o=r.indexOf(e);if(o>=0){let a=r.slice(o);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let s=t.get(e);if(s)for(let a of s){let c=this.detectCycleRecursive(a,t,r,n);if(c)return c}return r.pop(),null}};var Ae=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();this.isPropertyType(c)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=a.type?.toString();if(this.isPropertyType(c)||this.isClassType(c))continue;for(let[p,l]of Object.entries(a)){if(!p||this.metadataKeys.has(p))continue;let u=p,m=null;if(p.includes(".")){let f=p.lastIndexOf(".");m=p.substring(0,f),u=p.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,m)){let f=new k;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${p}' is not defined or imported`,f.suggestion=m?`The property '${u}' is not found in the imported namespace with alias '${m}'.
|
|
13
|
+
\u2022 Use 'kanonak search type ${r} --include-imports' to locate the entity`,o=new b;return o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=t,o.actualValue=r,o.message=`Reference to '${r}' could not be resolved`,o.suggestion=n,o.expectedValue="A valid entity reference that exists in the current document or imported namespaces",o}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}};var be=class{ruleName="TypeAmbiguity";async validateAsync(e,t){let r=[],n=new Map,o=[];if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){o.push({doc:p,import:c,publisher:s});let l=await this.getTransitiveImportsAsync(t,p,new Set);o.push(...l.map(u=>({doc:u,import:null,publisher:s})))}}for(let{doc:s,import:a}of o){let c=s.metadata?.namespace_?.toString()??"unknown";for(let p of Object.keys(s.body))n.has(p)||n.set(p,[]),n.get(p).push({namespace:c,import:a})}for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a;this.checkAmbiguousReference(c,"type",n,s,r),this.checkAmbiguousReference(c,"subClassOf",n,s,r),this.checkAmbiguousReference(c,"subPropertyOf",n,s,r),this.checkAmbiguousReference(c,"domain",n,s,r),this.checkAmbiguousReference(c,"range",n,s,r)}return r}checkAmbiguousReference(e,t,r,n,o){let s=e[t];if(!s)return;let a=E(s);for(let c of a){if(c.includes("."))continue;let p=r.get(c);if(p&&p.length>1){let l=p.map(f=>f.namespace).join(", "),u=[];for(let{namespace:f,import:d}of p)if(d?.alias)u.push(`${d.alias}.${c}`);else{let g=f.split("/"),k=g[g.length-1]?.split("@")[0]??"alias";u.push(`${k}.${c}`)}let m=u.length>0?`Use one of: ${u.join(", ")}`:"Consider adding namespace aliases to your imports",y=new b;y.ruleType=this.ruleName,y.severity="Warning",y.entityName=n,y.propertyName=t,y.actualValue=c,y.message=`Type '${c}' is ambiguous. It's defined in: ${l}`,y.suggestion=m,o.push(y)}}}async getTransitiveImportsAsync(e,t,r){let n=[],o=t.metadata?.namespace_?.toString()??"";if(r.has(o))return n;if(r.add(o),t.metadata?.imports)for(let[s,a]of Object.entries(t.metadata.imports))for(let c of a){let p=await e.getHighestCompatibleVersionAsync(s,c);if(p){n.push(p);let l=await this.getTransitiveImportsAsync(e,p,r);n.push(...l)}}return n}};var Re=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildClassHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a,p=c.type,l=c.subClassOf;if(p?.toString()==="Class"&&l){let u=s,m=this.detectCycle(u,n);if(m){let y=m.join(" \u2192 "),f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Circular class hierarchy detected: ${y}`,f.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",f.entityName=u,f.propertyName="subClassOf",f.actualValue=y,r.push(f);break}}}return r}async buildClassHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a,p=c.type,l=c.subClassOf;if(p?.toString()==="Class"&&l){let u=E(l);u.length>0&&r.set(s,u)}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);p&&await this.buildClassHierarchy(p,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var ve=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildPropertyHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&a.subPropertyOf){let l=s,u=this.detectCycle(l,n);if(u){let m=u.join(" \u2192 "),y=new b;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=l,y.propertyName="subPropertyOf",y.actualValue=m,r.push(y);break}}return r}async buildPropertyHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a,p=c.type;if(p){let l=p.toString();if(l==="DatatypeProperty"||l==="ObjectProperty"||l==="AnnotationProperty"){let u=c.subPropertyOf;if(u){let m=E(u);m.length>0&&r.set(s,m)}}}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);p&&await this.buildPropertyHierarchy(p,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var Pe=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,t){let r=[];for(let[n,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o))continue;let s=o,a=s.type?.toString();if(a==="DatatypeProperty"||a==="ObjectProperty"||a?.endsWith(".DatatypeProperty")||a?.endsWith(".ObjectProperty")){let c="range"in s,p=s.range?.toString().trim();if(!c||!p){let l=new b;l.ruleType=this.ruleName,l.severity="Error",l.entityName=n,l.propertyName="range",l.message=`Property '${n}' must have a 'range' defined.`,l.suggestion=a==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",l.expectedValue=a==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",r.push(l)}}}return r}};var we=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();(c==="Class"||c&&c.endsWith(".Class"))&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=E(s.subClassOf);for(let p=0;p<c.length;p++){let l=c[p];if(this.builtInClasses.has(l)||n.has(l))continue;if(!await this.isClassAvailableInImports(e,t,l)){let m=c.length>1?`[${p}]`:"",y=new b;y.ruleType=this.ruleName,y.severity="Error",y.message=`Class '${l}' referenced in subClassOf${m} is not defined or imported`,y.suggestion=`Define '${l}' as a Class, or import a namespace that contains it`,y.entityName=o,y.propertyName="subClassOf",y.actualValue=l,y.expectedValue="Defined or imported class",r.push(y)}}}return r}async isClassAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){if(n!==null&&c.alias!==n)continue;let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=n!==null?o:r,u=p.body[l];if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u.type?.toString();if(f==="Class"||f&&f.endsWith(".Class"))return!0}let m=new Set;if(await this.isClassAvailableInImportsRecursive(p,t,l,m))return!0}}return!1}async isClassAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="Class"||m&&m.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var Ie=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty")&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=E(s.subPropertyOf);for(let p=0;p<c.length;p++){let l=c[p];if(this.builtInProperties.has(l)||n.has(l))continue;if(!await this.isPropertyAvailableInImports(e,t,l)){let m=c.length>1?`[${p}]`:"",y=new b;y.ruleType=this.ruleName,y.severity="Error",y.message=`Property '${l}' referenced in subPropertyOf${m} is not defined or imported`,y.suggestion=`Define '${l}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,y.entityName=o,y.propertyName="subPropertyOf",y.actualValue=l,y.expectedValue="Defined or imported property",r.push(y)}}}return r}async isPropertyAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){if(n!==null&&c.alias!==n)continue;let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=n!==null?o:r,u=p.body[l];if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u.type?.toString();if(f==="DatatypeProperty"||f==="ObjectProperty"||f==="AnnotationProperty")return!0}let m=new Set;if(await this.isPropertyAvailableInImportsRecursive(p,t,l,m))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var Se=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let r=[],n=e.metadata.namespace_?.toString();if(!n)return r;let o=new Map,s=new Set;await this.buildImportGraph(e,t,o,s);let a=this.detectCycle(n,o);if(a){let c=a.join(" \u2192 "),p=new b;p.ruleType=this.ruleName,p.severity="Error",p.message=`Circular namespace import detected: ${c}`,p.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",p.entityName="imports",p.propertyName="imports",p.actualValue=c,r.push(p)}return r}async buildImportGraph(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!(!o||n.has(o))&&(n.add(o),e.metadata.imports)){let s=[];for(let[a,c]of Object.entries(e.metadata.imports))for(let p of c){let l=`${a}/${p.packageName}@${p.version}`;s.push(l);let u=await t.getHighestCompatibleVersionAsync(a,p);u&&await this.buildImportGraph(u,t,r,n)}s.length>0&&r.set(o,s)}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){let o=r.indexOf(e);if(o>=0){let a=r.slice(o);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let s=t.get(e);if(s)for(let a of s){let c=this.detectCycleRecursive(a,t,r,n);if(c)return c}return r.pop(),null}};var Ae=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();this.isPropertyType(c)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=a.type?.toString();if(this.isPropertyType(c)||this.isClassType(c))continue;for(let[p,l]of Object.entries(a)){if(!p||this.metadataKeys.has(p))continue;let u=p,m=null;if(p.includes(".")){let f=p.lastIndexOf(".");m=p.substring(0,f),u=p.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,m)){let f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${p}' is not defined or imported`,f.suggestion=m?`The property '${u}' is not found in the imported namespace with alias '${m}'.
|
|
14
14
|
1. Verify the namespace is imported with the correct alias
|
|
15
15
|
2. Check if the property name is spelled correctly
|
|
16
16
|
3. Ensure the imported namespace version contains this property`:`The property '${p}' is not defined in this namespace or any imported namespace.
|
|
17
17
|
1. Define '${p}' as an ObjectProperty or DatatypeProperty in this namespace, OR
|
|
18
18
|
2. Import the namespace that contains '${p}', OR
|
|
19
|
-
3. Use a qualified reference like 'alias.${p}' if already imported with an alias`,f.entityName=o,f.propertyName=p,f.actualValue=l?.toString(),f.expectedValue="A defined or imported property",r.push(f)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let c=await t.getHighestCompatibleVersionAsync(o,a);if(c){let p=c.body[r];if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p.type?.toString();if(this.isPropertyType(m))return!0}let l=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,t,r,l))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isPropertyType(m))return!0}if(await this.isPropertyAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var De=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();this.isPropertyType(c)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=a.type?.toString();if(!this.isPropertyType(c)&&!this.isClassType(c))continue;for(let[p,l]of Object.entries(a)){if(!p||this.metadataKeys.has(p))continue;let u=p,m=null;if(p.includes(".")){let f=p.lastIndexOf(".");m=p.substring(0,f),u=p.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,m)){let f=this.isClassType(c)?"class":"property",d=new
|
|
19
|
+
3. Use a qualified reference like 'alias.${p}' if already imported with an alias`,f.entityName=o,f.propertyName=p,f.actualValue=l?.toString(),f.expectedValue="A defined or imported property",r.push(f)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let c=await t.getHighestCompatibleVersionAsync(o,a);if(c){let p=c.body[r];if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p.type?.toString();if(this.isPropertyType(m))return!0}let l=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,t,r,l))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isPropertyType(m))return!0}if(await this.isPropertyAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var De=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();this.isPropertyType(c)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=a.type?.toString();if(!this.isPropertyType(c)&&!this.isClassType(c))continue;for(let[p,l]of Object.entries(a)){if(!p||this.metadataKeys.has(p))continue;let u=p,m=null;if(p.includes(".")){let f=p.lastIndexOf(".");m=p.substring(0,f),u=p.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,m)){let f=this.isClassType(c)?"class":"property",d=new b;d.ruleType=this.ruleName,d.severity="Error",d.message=`Property '${p}' used on ${f} '${o}' is not defined or imported`,d.suggestion=m?`The property '${u}' is not found in the imported namespace with alias '${m}'.
|
|
20
20
|
1. Verify the namespace is imported with the correct alias
|
|
21
21
|
2. Check if the property name is spelled correctly
|
|
22
22
|
3. Ensure the imported namespace version contains this property`:`The property '${p}' is not defined in this namespace or any imported namespace.
|
|
23
23
|
1. Define '${p}' as an ObjectProperty or DatatypeProperty in this namespace, OR
|
|
24
24
|
2. Import the namespace that contains '${p}', OR
|
|
25
|
-
3. Use a qualified reference like 'alias.${p}' if already imported with an alias`,d.entityName=o,d.propertyName=p,d.actualValue=l?.toString(),d.expectedValue="A defined or imported property",r.push(d)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let c=await t.getHighestCompatibleVersionAsync(o,a);if(c){let p=c.body[r];if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p.type?.toString();if(this.isPropertyType(m))return!0}let l=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,t,r,l))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isPropertyType(m))return!0}if(await this.isPropertyAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var Ke=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,t){let r=[],n=new Set,o=[];for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a,p=!1,l=c.type;if(Array.isArray(l)){for(let u of l)if(u?.toString()==="DatatypeProperty"){p=!0;break}}else l?.toString()==="DatatypeProperty"&&(p=!0);if(p){o.push(s);let u=this.getPropertyValue(c,"range");u&&this.xsdTypes.has(u)&&n.add(u)}}if(n.size>0&&!await this.checkXsdImportAsync(e.metadata,t)){let a=Array.from(n).sort().join(", "),c=o.sort().join(", "),p=new
|
|
26
|
-
`),u=e.split(".")[0],m=e.includes(".")?e:t,y=new
|
|
25
|
+
3. Use a qualified reference like 'alias.${p}' if already imported with an alias`,d.entityName=o,d.propertyName=p,d.actualValue=l?.toString(),d.expectedValue="A defined or imported property",r.push(d)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let c=await t.getHighestCompatibleVersionAsync(o,a);if(c){let p=c.body[r];if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p.type?.toString();if(this.isPropertyType(m))return!0}let l=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,t,r,l))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isPropertyType(m))return!0}if(await this.isPropertyAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}};var Ke=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,t){let r=[],n=new Set,o=[];for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a,p=!1,l=c.type;if(Array.isArray(l)){for(let u of l)if(u?.toString()==="DatatypeProperty"){p=!0;break}}else l?.toString()==="DatatypeProperty"&&(p=!0);if(p){o.push(s);let u=this.getPropertyValue(c,"range");u&&this.xsdTypes.has(u)&&n.add(u)}}if(n.size>0&&!await this.checkXsdImportAsync(e.metadata,t)){let a=Array.from(n).sort().join(", "),c=o.sort().join(", "),p=new b;p.ruleType=this.ruleName,p.severity="Error",p.message=`XSD namespace not imported but XSD types are used: ${a}`,p.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${c}`,p.entityName="imports",r.push(p)}return r}async checkXsdImportAsync(e,t,r=new Set){if(!e?.imports)return!1;let n=e.namespace_?.toString()??"";if(n&&r.has(n))return!1;n&&r.add(n);for(let[,o]of Object.entries(e.imports))for(let s of o)if(s.packageName==="xsd"||s.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[o,s]of Object.entries(e.imports))for(let a of s){let c=await t.getHighestCompatibleVersionAsync(o,a);if(c?.metadata&&await this.checkXsdImportAsync(c.metadata,t,r))return!0}return!1}getPropertyValue(e,t){return e[t]?.toString()}};var Ce=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,t){let r=[],n=await this.buildEntitySourceMapAsync(e,t),o=await this.buildDatatypePropertyNamesAsync(e,t);for(let[s,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&this.validateEntityReferences(s,a,n,o,e,r);return r}async buildEntitySourceMapAsync(e,t){let r=new Map,n=new Set;for(let o of Object.keys(e.body)){let s=e.metadata.namespace_?.toString()??"";r.has(o)||r.set(o,[]),r.get(o).push(`(local:${s})`)}if(e.metadata.imports)for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){let c=await t.getHighestCompatibleVersionAsync(o,a);c&&await this.collectEntitiesRecursivelyAsync(c,r,n,t)}return r}async collectEntitiesRecursivelyAsync(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!r.has(o)){r.add(o);for(let s of Object.keys(e.body)){t.has(s)||t.set(s,[]);let a=t.get(s);a.includes(o)||a.push(o)}if(e.metadata.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await n.getHighestCompatibleVersionAsync(s,c);p&&await this.collectEntitiesRecursivelyAsync(p,t,r,n)}}}async buildDatatypePropertyNamesAsync(e,t){let r=new Set,n=new Set;if(await this.collectDatatypePropertiesAsync(e,r,n,t),e.metadata.imports)for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){let c=await t.getHighestCompatibleVersionAsync(o,a);c&&await this.collectDatatypePropertiesAsync(c,r,n,t)}return r}async collectDatatypePropertiesAsync(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!r.has(o)){r.add(o);for(let[s,a]of Object.entries(e.body)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let c=a.type;if(typeof c!="string")continue;(c.includes(".")?c.substring(c.lastIndexOf(".")+1):c)==="DatatypeProperty"&&t.add(s)}if(e.metadata.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await n.getHighestCompatibleVersionAsync(s,c);p&&await this.collectDatatypePropertiesAsync(p,t,r,n)}}}validateEntityReferences(e,t,r,n,o,s){for(let[a,c]of Object.entries(t)){let p=a;if(p&&!p.includes(".")){let l=r.get(p);if(l&&l.length>1&&!l.some(m=>m.startsWith("(local:"))){let m=l.filter(y=>!y.startsWith("(local:"));m.length>1&&s.push(this.createAmbiguityError(e,p,`Property '${p}'`,m,o,!0,p))}}this.validatePropertyValue(e,p,c,r,n,o,s)}}validatePropertyValue(e,t,r,n,o,s,a){if(r==null)return;let c=t&&t.includes(".")?t.substring(t.lastIndexOf(".")+1):t,p=!!c&&o.has(c);if(typeof r=="string"&&!r.includes(".")&&!p){let l=n.get(r);if(l&&l.length>1&&!l.some(m=>m.startsWith("(local:"))){let m=l.filter(y=>!y.startsWith("(local:"));m.length>1&&a.push(this.createAmbiguityError(e,t,`Reference '${r}'`,m,s,!1,r))}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){let u=`${e}.${t}[${l}]`;this.validatePropertyValue(u,t,r[l],n,o,s,a)}else if(typeof r=="object"&&!Array.isArray(r)){let l=t?`${e}.${t}`:e;this.validateEntityReferences(l,r,n,o,s,a)}}createAmbiguityError(e,t,r,n,o,s,a){let c=[];for(let d of n){let g=this.findAliasForNamespace(o,d);if(g){let h=t?.split(".").pop()??t;c.push(`${g}.${h}`)}}let p=c.length>0?`Use one of: ${c.map(d=>`'${d}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${t}')`,l=n.map(d=>` \u2022 ${d}`).join(`
|
|
26
|
+
`),u=e.split(".")[0],m=e.includes(".")?e:t,y=new b;y.ruleType=this.ruleName,y.severity="Error",y.entityName=u,m&&(y.propertyName=m);let f=a??t;return f&&(y.actualValue=f),y.message=`${r} is ambiguous - defined in multiple imported namespaces`,y.suggestion=`${p}
|
|
27
27
|
|
|
28
28
|
Defined in:
|
|
29
|
-
${l}`,y.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",y}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(`${r}/${o.packageName}@${o.version}`===t&&o.alias)return o.alias;return null}};var $e=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();this.isValidRangeTargetType(c)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=a.type?.toString();if(c!=="DatatypeProperty"&&c!=="ObjectProperty"&&!c?.endsWith(".DatatypeProperty")&&!c?.endsWith(".ObjectProperty"))continue;let p=a.range;if(!p)continue;let l=[];if(Array.isArray(p))for(let u of p){let m=u?.toString();m&&l.push(m)}else{let u=p?.toString();u&&l.push(u)}if(l.length===0)continue;for(let u of l){if(this.primitiveTypes.has(u)||this.builtInClasses.has(u)||n.has(u))continue;if(!await this.isTypeAvailableInImports(e,t,u)){let y=c?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",f=new
|
|
29
|
+
${l}`,y.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",y}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(`${r}/${o.packageName}@${o.version}`===t&&o.alias)return o.alias;return null}};var $e=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let c=s.type?.toString();this.isValidRangeTargetType(c)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=a.type?.toString();if(c!=="DatatypeProperty"&&c!=="ObjectProperty"&&!c?.endsWith(".DatatypeProperty")&&!c?.endsWith(".ObjectProperty"))continue;let p=a.range;if(!p)continue;let l=[];if(Array.isArray(p))for(let u of p){let m=u?.toString();m&&l.push(m)}else{let u=p?.toString();u&&l.push(u)}if(l.length===0)continue;for(let u of l){if(this.primitiveTypes.has(u)||this.builtInClasses.has(u)||n.has(u))continue;if(!await this.isTypeAvailableInImports(e,t,u)){let y=c?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${o}' has range '${u}' which is not defined or imported`,f.suggestion=y==="ObjectProperty"?`For ObjectProperty:
|
|
30
30
|
1. Define '${u}' as a Class in this namespace, OR
|
|
31
31
|
2. Import the namespace that contains '${u}', OR
|
|
32
32
|
3. Use a qualified reference like 'alias.${u}' if already imported with an alias`:`For DatatypeProperty:
|
|
33
33
|
1. Use a primitive type (string, integer, boolean, dateTime, etc.), OR
|
|
34
|
-
2. If '${u}' should be a class, change property type to ObjectProperty`,f.entityName=o,f.propertyName="range",f.actualValue=u,f.expectedValue=y==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",r.push(f)}}}return r}async isTypeAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){if(n!==null&&c.alias!==n)continue;let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=n!==null?o:r,u=p.body[l];if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u.type?.toString();if(this.isValidRangeTargetType(f))return!0}let m=new Set;if(await this.isTypeAvailableInImportsRecursive(p,t,l,m))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isValidRangeTargetType(m))return!0}if(await this.isTypeAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var
|
|
34
|
+
2. If '${u}' should be a class, change property type to ObjectProperty`,f.entityName=o,f.propertyName="range",f.actualValue=u,f.expectedValue=y==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",r.push(f)}}}return r}async isTypeAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){if(n!==null&&c.alias!==n)continue;let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=n!==null?o:r,u=p.body[l];if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u.type?.toString();if(this.isValidRangeTargetType(f))return!0}let m=new Set;if(await this.isTypeAvailableInImportsRecursive(p,t,l,m))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let c of a){let p=await t.getHighestCompatibleVersionAsync(s,c);if(p){let l=p.body[r];if(l&&typeof l=="object"&&!Array.isArray(l)){let m=l.type?.toString();if(this.isValidRangeTargetType(m))return!0}if(await this.isTypeAvailableInImportsRecursive(p,t,r,n))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var xe=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,t){let r=[],n=new Map,o=new x(t);await o.buildEntityIndexAsync(e);for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a,p=!1,l=c.type;if(Array.isArray(l)){for(let u of l)if(u?.toString()==="ObjectProperty"){p=!0;break}}else l?.toString()==="ObjectProperty"&&(p=!0);if(p){let u=c.range,m=[];if(Array.isArray(u))for(let y of u){let f=y?.toString();f&&m.push(f)}else{let y=u?.toString();y&&m.push(y)}for(let y of m)this.xsdTypes.has(y)||(n.has(y)||n.set(y,[]),n.get(y).push(s))}}for(let[s,a]of n)if(!await o.resolveEntityAsync(s,e))for(let p of a){let l=new b;l.ruleType=this.ruleName,l.severity="Warning",l.message=`ObjectProperty references class '${s}' which may not be imported`,l.suggestion=`Ensure the namespace containing '${s}' is imported, or define '${s}' in this document`,l.entityName=p,l.propertyName="range",l.actualValue=s,r.push(l)}return r}};var je=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"ObjectPropertyValue"}async validateAsync(e,t){let r=[],n=new x(t),o=new ne(n),s=await n.buildEntityIndexAsync(e),a=await this.buildPropertyMetadataAsync(e,t,n,s);for(let[c,p]of Object.entries(e.body))typeof p=="object"&&p!==null&&!Array.isArray(p)&&await this.scanEntityForObjectProperties(p,c,"",a,n,o,e,r);return r}async scanEntityForObjectProperties(e,t,r,n,o,s,a,c){for(let[p,l]of Object.entries(e)){if(this.standardProperties.has(p))continue;let u=p,m=p.lastIndexOf(".");m>0&&m<p.length-1&&(u=p.substring(m+1));let y=n.get(u);if(y&&s.isEffectiveObjectProperty(y.propertyType,y.rangeUri)){let d=r?`${r}.${p}`:p;if(typeof l=="string"&&l.trim().length>0){let g=l.trim();if(g.includes(",")){let k=g.split(",").map(R=>R.trim()).filter(R=>R.length>0);c.push({ruleType:this.ruleName,severity:"Error",message:`Property '${p}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
|
|
35
35
|
${p}:
|
|
36
|
-
- ${
|
|
37
|
-
${
|
|
38
|
-
`)}`,entityName:t,propertyName:p,propertyPath:d,actualValue:g,expectedValue:`A single reference to ${y.range??"an entity"} OR a YAML list`});continue}let h=await o.resolveEntityAsync(g,a);if(h)y.range&&(await this.validateRangeType(h,y.range,o,a)||c.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${p}' expects a ${y.range}, but '${g}' may not be a ${y.range}`,suggestion:`Ensure '${g}' is defined with appropriate type`,entityName:t,propertyName:p,propertyPath:d,actualValue:g,expectedValue:y.range}));else{let
|
|
36
|
+
- ${k[0]}
|
|
37
|
+
${k.slice(1).map(R=>` - ${R}`).join(`
|
|
38
|
+
`)}`,entityName:t,propertyName:p,propertyPath:d,actualValue:g,expectedValue:`A single reference to ${y.range??"an entity"} OR a YAML list`});continue}let h=await o.resolveEntityAsync(g,a);if(h)y.range&&(await this.validateRangeType(h,y.range,o,a)||c.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${p}' expects a ${y.range}, but '${g}' may not be a ${y.range}`,suggestion:`Ensure '${g}' is defined with appropriate type`,entityName:t,propertyName:p,propertyPath:d,actualValue:g,expectedValue:y.range}));else{let k=y.range??"entity";c.push({ruleType:this.ruleName,severity:"Error",message:`Property '${p}' references '${g}' which is not defined or imported`,suggestion:`Define '${g}' or import a namespace that contains it. Expected range: ${k}`,entityName:t,propertyName:p,propertyPath:d,actualValue:g,expectedValue:"Defined or imported entity"})}}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let g=r?`${r}.${p}`:p;await this.scanEntityForObjectProperties(l,t,g,n,o,s,a,c)}else if(Array.isArray(l))for(let g=0;g<l.length;g++){let h=l[g];if(typeof h=="string"&&h.trim().length>0){let k=h.trim(),R=await o.resolveEntityAsync(k,a);if(R){if(y.range&&!await this.validateRangeType(R,y.range,o,a)){let j=r?`${r}.${p}[${g}]`:`${p}[${g}]`;c.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${p}' expects a ${y.range}, but '${k}' may not be a ${y.range}`,suggestion:`Ensure '${k}' is defined with appropriate type`,entityName:t,propertyName:`${p}[${g}]`,propertyPath:j,actualValue:k,expectedValue:y.range})}}else{let v=y.range??"entity",j=r?`${r}.${p}[${g}]`:`${p}[${g}]`;c.push({ruleType:this.ruleName,severity:"Error",message:`Property '${p}' references '${k}' which is not defined or imported`,suggestion:`Define '${k}' or import a namespace that contains it. Expected range: ${v}`,entityName:t,propertyName:`${p}[${g}]`,propertyPath:j,actualValue:k,expectedValue:"Defined or imported entity"})}}else if(typeof h=="object"&&h!==null&&!Array.isArray(h)){let k=r?`${r}.${p}[${g}]`:`${p}[${g}]`;await this.scanEntityForObjectProperties(h,t,k,n,o,s,a,c)}}}if(typeof l=="object"&&l!==null&&!Array.isArray(l)&&!n.has(p)){let f=r?`${r}.${p}`:p;await this.scanEntityForObjectProperties(l,t,f,n,o,s,a,c)}else if(Array.isArray(l))for(let f=0;f<l.length;f++){let d=l[f];if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let g=r?`${r}.${p}[${f}]`:`${p}[${f}]`;await this.scanEntityForObjectProperties(d,t,g,n,o,s,a,c)}}}}async validateRangeType(e,t,r,n){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(t))return!0;let s=e.entity.type;if(s){let a=[];if(Array.isArray(s))for(let c of s){let p=c?.toString();p&&p.trim().length>0&&a.push(p)}else{let c=s?.toString();c&&c.trim().length>0&&a.push(c)}for(let c of a){let p=c.includes(".")?c.split(".")[1]:c;if(p===t||t==="Property"&&(p==="DatatypeProperty"||p==="ObjectProperty"||p==="AnnotationProperty")||t==="Class"&&p==="Class"||await r.isSubclassOfAsync(c,t,n))return!0}}return!1}async buildPropertyMetadataAsync(e,t,r,n){let o=new Map;for(let[s,a]of n){let c=a.entity.type;if(c){let p=[];if(Array.isArray(c))for(let m of c){let y=m?.toString();y&&y.trim().length>0&&p.push(y)}else{let m=c?.toString();m&&m.trim().length>0&&p.push(m)}let l=!1,u="Property";for(let m of p){let y=m.includes(".")?m.split(".")[1]:m;if(y==="Property"||y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty"){l=!0,u=m;break}}if(l){let m={propertyType:u},y=a.entity.range;if(y){let f=y?.toString();if(f&&f.trim().length>0){m.range=f;let d=await r.resolveEntityAsync(f,e);d&&(m.rangeUri=d.uri)}}o.set(s,m)}}}return o}};var Ee=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"PropertyDomain"}async validateAsync(e,t){let r=[],n=new Map;for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a,p=this.getPropertyValue(c,"type");(p==="DatatypeProperty"||p?.endsWith(".DatatypeProperty")||p==="ObjectProperty"||p?.endsWith(".ObjectProperty")||p==="AnnotationProperty"||p?.endsWith(".AnnotationProperty"))&&n.set(s,c)}let o=await this.buildCompleteClassHierarchyAsync(e,t);for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a,p=this.getPropertyValue(c,"type");if(!p||p==="Class"||p.endsWith(".Class")||p.endsWith("Property")||p==="AnnotationProperty")continue;this.validateEntityProperties(c,s,p,n,o,r)}return r}async buildCompleteClassHierarchyAsync(e,t){let r=new Map,n=new Set,o=async(a,c)=>{if(!n.has(c)){n.add(c);for(let[p,l]of Object.entries(a.body))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=l,m=this.getPropertyValue(u,"type");if(m==="Class"||m?.endsWith(".Class")){let y=u.subClassOf;if(y===void 0){for(let d of Object.keys(u))if(d.endsWith(".subClassOf")){y=u[d];break}}let f=E(y);f.length>0&&r.set(p,f)}}if(a.metadata.imports)for(let[p,l]of Object.entries(a.metadata.imports))for(let u of l)try{let m=await t.getHighestCompatibleVersionAsync(p,u);if(m){let y=`${p}/${u.packageName}@${u.version}`;await o(m,y)}}catch{}}},s=e.metadata.namespace_?.toString()??"unknown";return await o(e,s),r}validateEntityProperties(e,t,r,n,o,s){for(let[a,c]of Object.entries(e)){if(this.standardProperties.has(a))continue;let p=a,l=a.lastIndexOf(".");l>0&&l<a.length-1&&(p=a.substring(l+1));let u=n.get(p);if(!u)continue;let m=this.getPropertyValue(u,"domain");if(m){if(!this.isTypeCompatibleWithDomain(r,m,o)){let y=t.split(".")[0];s.push({ruleType:this.ruleName,severity:"Error",entityName:y,propertyName:t,actualValue:a,message:`Property '${a}' has domain '${m}' but is used on '${r}' at '${t}'`,suggestion:`Either:
|
|
39
39
|
1. Use this property only on '${m}' instances
|
|
40
40
|
2. Change the property domain to include '${r}'
|
|
41
|
-
3. Create a different property for '${r}'`,expectedValue:`Property used on ${m} or its subclasses`})}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let y=c,f=this.getPropertyValue(y,"type");if(f){let d=`${t}.${a}`;this.validateEntityProperties(y,d,f,n,o,s)}else{let d=this.getPropertyValue(u,"range");if(d){let g=`${t}.${a}`;this.validateEntityProperties(y,g,d,n,o,s)}}}else if(Array.isArray(c))for(let y=0;y<c.length;y++){let f=c[y];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let d=f,g=this.getPropertyValue(d,"type");if(g){let h=`${t}.${a}[${y}]`;this.validateEntityProperties(d,h,g,n,o,s)}else{let h=this.getPropertyValue(u,"range");if(h){let
|
|
41
|
+
3. Create a different property for '${r}'`,expectedValue:`Property used on ${m} or its subclasses`})}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let y=c,f=this.getPropertyValue(y,"type");if(f){let d=`${t}.${a}`;this.validateEntityProperties(y,d,f,n,o,s)}else{let d=this.getPropertyValue(u,"range");if(d){let g=`${t}.${a}`;this.validateEntityProperties(y,g,d,n,o,s)}}}else if(Array.isArray(c))for(let y=0;y<c.length;y++){let f=c[y];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let d=f,g=this.getPropertyValue(d,"type");if(g){let h=`${t}.${a}[${y}]`;this.validateEntityProperties(d,h,g,n,o,s)}else{let h=this.getPropertyValue(u,"range");if(h){let k=`${t}.${a}[${y}]`;this.validateEntityProperties(d,k,h,n,o,s)}}}}}}}isTypeCompatibleWithDomain(e,t,r){if(e===t)return!0;let n=new Set,o=[e];for(;o.length>0;){let s=o.shift();if(n.has(s))continue;n.add(s);let a=r.get(s);if(a)for(let c of a){if(c===t)return!0;o.push(c)}}return!1}getPropertyValue(e,t){if(t in e){let r=e[t];return this.extractFirstValue(r)}for(let r of Object.keys(e))if(r.endsWith(`.${t}`)){let n=e[r];return this.extractFirstValue(n)}}extractFirstValue(e){if(Array.isArray(e)){let t=[];for(let r of e)t.push(r?.toString()??"");return t.length>0?t[0]:void 0}return e?.toString()}};var Oe=class{get ruleName(){return"PropertyValueType"}async validateAsync(e,t){let r=[],n=new Map;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,c=this.getPropertyValue(a,"type");(c==="DatatypeProperty"||c==="ObjectProperty")&&n.set(o,a)}for(let[o,s]of Object.entries(e.body)){if(typeof s!="object"||s===null||Array.isArray(s))continue;let a=s,c=this.getPropertyValue(a,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[p,l]of Object.entries(a)){if(p==="type"||p==="label"||p==="comment")continue;let u=p,m=p.lastIndexOf(".");m>0&&m<p.length-1&&(u=p.substring(m+1));let y=n.get(u);if(!y)continue;let f=this.getPropertyValue(y,"type"),d=this.getPropertyValue(y,"range");if(f==="DatatypeProperty"){if(typeof l=="object"&&l!==null&&!Array.isArray(l)||Array.isArray(l))r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:p,message:`Property '${p}' is a DatatypeProperty with range '${d}' but instance '${o}' has a complex object value`,suggestion:`Either:
|
|
42
42
|
1. Create a class for this data and change '${p}' to an ObjectProperty
|
|
43
43
|
2. Store as a JSON string to keep it as DatatypeProperty
|
|
44
|
-
3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${d}'`});else if(!this.validateDatatypeValue(d,l)){let g={ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:p,message:`Property '${p}' expects type '${d}' but instance '${o}' has value of type '${this.getValueTypeName(l)}'`,suggestion:`Provide a value of type '${d}'`,toString:()=>""};d&&(g.expectedValue=d),r.push(g)}}else if(f==="ObjectProperty")if(Array.isArray(l))for(let g=0;g<l.length;g++){let h=l[g];typeof h!="string"&&(typeof h!="object"||h===null||Array.isArray(h))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:`${p}[${g}]`,message:`ObjectProperty '${p}' array item ${g} in instance '${o}' has invalid type '${this.getValueTypeName(h)}'`,suggestion:"Array items must be references (strings) or embedded objects (dictionaries)",expectedValue:"string or object"})}else typeof l!="string"&&(typeof l!="object"||l===null||Array.isArray(l))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:p,message:`ObjectProperty '${p}' in instance '${o}' has invalid value type '${this.getValueTypeName(l)}'`,suggestion:"Value must be a reference (string), embedded object (dictionary), or array of these",expectedValue:`Reference to ${d} or embedded ${d} object`})}}return r}validateDatatypeValue(e,t){switch(e?.toLowerCase()){case"string":return typeof t=="string";case"integer":case"int":return typeof t=="number"&&Number.isInteger(t);case"decimal":return typeof t=="number";case"boolean":return typeof t=="boolean";case"float":case"double":return typeof t=="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,t){if(t in e){let r=e[t];if(Array.isArray(r)){let n=[];for(let o of r)n.push(o?.toString()??"");return n.length>0?n[0]:void 0}return r?.toString()}}};var Ve=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"ClassDefinition"}async validateAsync(e,t){let r=[],n=new Map,o=new Set;for(let[a,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=c.type;if(l)if(Array.isArray(l))for(let u of l){let m=u?.toString();if(m==="Class"||m&&m.endsWith(".Class")){o.add(a);break}}else{let u=l?.toString();(u==="Class"||u&&u.endsWith(".Class"))&&o.add(a)}}for(let[a,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let p=c,l=p.type;if(l)if(Array.isArray(l)){let u=!1;for(let m of l){let y=m?.toString();if(y&&this.isDefinitionType(y)){u=!0;break}}if(!u)for(let m of l){let y=m?.toString();y&&y.trim().length>0&&(n.has(y)||n.set(y,[]),n.get(y).push(a))}}else{let u=l?.toString();u&&u.trim().length>0&&(this.isDefinitionType(u)||(n.has(u)||n.set(u,[]),n.get(u).push(a)))}this.checkNestedTypes(p,a,n,a)}let s=new
|
|
44
|
+
3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${d}'`});else if(!this.validateDatatypeValue(d,l)){let g={ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:p,message:`Property '${p}' expects type '${d}' but instance '${o}' has value of type '${this.getValueTypeName(l)}'`,suggestion:`Provide a value of type '${d}'`,toString:()=>""};d&&(g.expectedValue=d),r.push(g)}}else if(f==="ObjectProperty")if(Array.isArray(l))for(let g=0;g<l.length;g++){let h=l[g];typeof h!="string"&&(typeof h!="object"||h===null||Array.isArray(h))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:`${p}[${g}]`,message:`ObjectProperty '${p}' array item ${g} in instance '${o}' has invalid type '${this.getValueTypeName(h)}'`,suggestion:"Array items must be references (strings) or embedded objects (dictionaries)",expectedValue:"string or object"})}else typeof l!="string"&&(typeof l!="object"||l===null||Array.isArray(l))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:p,message:`ObjectProperty '${p}' in instance '${o}' has invalid value type '${this.getValueTypeName(l)}'`,suggestion:"Value must be a reference (string), embedded object (dictionary), or array of these",expectedValue:`Reference to ${d} or embedded ${d} object`})}}return r}validateDatatypeValue(e,t){switch(e?.toLowerCase()){case"string":return typeof t=="string";case"integer":case"int":return typeof t=="number"&&Number.isInteger(t);case"decimal":return typeof t=="number";case"boolean":return typeof t=="boolean";case"float":case"double":return typeof t=="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,t){if(t in e){let r=e[t];if(Array.isArray(r)){let n=[];for(let o of r)n.push(o?.toString()??"");return n.length>0?n[0]:void 0}return r?.toString()}}};var Ve=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"ClassDefinition"}async validateAsync(e,t){let r=[],n=new Map,o=new Set;for(let[a,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=c.type;if(l)if(Array.isArray(l))for(let u of l){let m=u?.toString();if(m==="Class"||m&&m.endsWith(".Class")){o.add(a);break}}else{let u=l?.toString();(u==="Class"||u&&u.endsWith(".Class"))&&o.add(a)}}for(let[a,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let p=c,l=p.type;if(l)if(Array.isArray(l)){let u=!1;for(let m of l){let y=m?.toString();if(y&&this.isDefinitionType(y)){u=!0;break}}if(!u)for(let m of l){let y=m?.toString();y&&y.trim().length>0&&(n.has(y)||n.set(y,[]),n.get(y).push(a))}}else{let u=l?.toString();u&&u.trim().length>0&&(this.isDefinitionType(u)||(n.has(u)||n.set(u,[]),n.get(u).push(a)))}this.checkNestedTypes(p,a,n,a)}let s=new x(t);for(let[a,c]of n){if(this.builtInClasses.has(a)||o.has(a))continue;let p=await s.resolveEntityAsync(a,e);if(!(p&&this.isClassEntity(p.entity))){let u=Array.from(new Set(c)).sort();for(let m of u)r.push({ruleType:this.ruleName,severity:"Error",message:`Class '${a}' is not defined or imported`,suggestion:`Define '${a}' as a Class in this document, or import a namespace that contains it`,entityName:m,propertyName:"type",actualValue:a,expectedValue:"Defined or imported class"})}}return r}checkNestedTypes(e,t,r,n){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let o=e,s=o.type;if(s){let a=new Set(["Class","DatatypeProperty","ObjectProperty","AnnotationProperty"]);if(Array.isArray(s))for(let c of s){let p=c?.toString();p&&p.trim().length>0&&!a.has(p)&&(r.has(p)||r.set(p,[]),r.get(p).push(n))}else{let c=s?.toString();c&&c.trim().length>0&&!a.has(c)&&(r.has(c)||r.set(c,[]),r.get(c).push(n))}}for(let[a,c]of Object.entries(o))if(a!=="type"){let p=`${n}.${a}`;this.checkNestedTypes(c,t,r,p)}}else if(Array.isArray(e))for(let o=0;o<e.length;o++){let s=`${n}[${o}]`;this.checkNestedTypes(e[o],t,r,s)}}isClassEntity(e){if(!e)return!1;let t=e.type;if(!t)return!1;if(Array.isArray(t))for(let r of t){let n=r?.toString();if(n==="Class"||n&&n.endsWith(".Class"))return!0}else{let r=t?.toString();if(r==="Class"||r&&r.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 St=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new $,this.documentRules=[new me,new ye,new fe,new de],this.repositoryRules=[new ge,new he,new ke,new be,new Re,new ve,new Pe,new we,new Ie,new Se,new Ae,new De,new Ke,new Ce,new $e,new xe,new je,new Ee,new Oe,new Ve]}async validateAsync(e,t){let r=new ue;for(let n of this.documentRules)try{let o=n.validate(e);this.addErrorsToResult(r,o)}catch(o){let s=new b;s.ruleType=n.ruleName,s.severity="Error",s.message=`Validation rule '${n.ruleName}' failed: ${o instanceof Error?o.message:String(o)}`,r.errors.push(s)}if(t){let n=[];for(let o of this.repositoryRules)try{let s=await o.validateAsync(e,t);this.addErrorsToResult(r,s)}catch(s){let a=s instanceof Error?s.message:String(s);n.push({ruleName:o.ruleName,cause:a})}if(n.length>0){let o=new Map;for(let{ruleName:s,cause:a}of n){let c=o.get(a);c?c.push(s):o.set(a,[s])}for(let[s,a]of o){let c=new b;c.ruleType=a[0],c.severity="Error",a.length===1?c.message=`Validation rule '${a[0]}' failed: ${s}`:c.message=`${s} (affects ${a.length} rules: ${a.join(", ")})`,r.errors.push(c)}}}return r.isValid=r.errors.length===0,r}async validateYamlAsync(e,t){let r=this.parser.parseWithErrors(e);if(!r.isValid){let n=new ue;n.isValid=!1;for(let o of r.errors){let s=new b;s.ruleType="ParseError",s.severity="Error",s.lineNumber=o.line,s.column=o.column,s.message=o.message,o.keyName&&(s.entityName=o.keyName),o.errorType==="DuplicateKey"&&(s.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),n.errors.push(s)}return n}return await this.validateAsync(r.document,t)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(r=>r instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(r=>r instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let r of t)r.severity==="Error"?e.errors.push(r):this.includeWarnings&&e.warnings.push(r)}};import{VersionOperator as zm}from"@kanonak-protocol/types/document/models/enums";function nt(i){if(!i.expiresAt)return!1;let e=new Date(i.expiresAt),t=300*1e3;return e.getTime()<=Date.now()+t}function At(i){return!!i.accessToken&&!nt(i)}function S(i){let e=i.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}import{existsSync as co,readFileSync as po}from"fs";import{homedir as lo}from"os";import{join as uo}from"path";import{execFile as Hn}from"child_process";import{promisify as qn}from"util";var Dt=qn(Hn),Kt="kanonak",Ct="/usr/bin/security",ot=class{async get(e){let t=S(e);try{let{stdout:r}=await Dt(Ct,["find-generic-password","-s",Kt,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
|
|
45
45
|
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if($r(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${$t(r)}
|
|
46
46
|
The Keychain may be locked or inaccessible.
|
|
47
47
|
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=S(e),n=JSON.stringify(t);try{await Dt(Ct,["add-generic-password","-s",Kt,"-a",r,"-U","-w",n],{timeout:1e4})}catch(o){throw new Error(`macOS Keychain write failed for '${r}': ${$t(o)}
|
|
48
48
|
Ensure the Keychain is unlocked and the CLI has write permission.
|
|
49
49
|
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=S(e);try{await Dt(Ct,["delete-generic-password","-s",Kt,"-a",t],{timeout:1e4})}catch(r){if($r(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${$t(r)}
|
|
50
50
|
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await Dt(Ct,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let n of e.split(`
|
|
51
|
-
`))if(n.includes(`"svce"<blob>="${Kt}"`)&&(r=!0),r&&n.includes('"acct"<blob>=')){let o=n.match(/"acct"<blob>="([^"]+)"/);o&&t.push(o[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${$t(e)}`),[]}}};function $r(i,e){return typeof i=="object"&&i!==null&&"code"in i&&i.code===e}function $t(i){return i instanceof Error?i.message:String(i)}import{execFile as Gn}from"child_process";import{promisify as zn}from"util";var Xn=zn(Gn),
|
|
51
|
+
`))if(n.includes(`"svce"<blob>="${Kt}"`)&&(r=!0),r&&n.includes('"acct"<blob>=')){let o=n.match(/"acct"<blob>="([^"]+)"/);o&&t.push(o[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${$t(e)}`),[]}}};function $r(i,e){return typeof i=="object"&&i!==null&&"code"in i&&i.code===e}function $t(i){return i instanceof Error?i.message:String(i)}import{execFile as Gn}from"child_process";import{promisify as zn}from"util";var Xn=zn(Gn),xt="kanonak:",st=class{async get(e){let t=xt+S(e),r=`
|
|
52
52
|
${Et}
|
|
53
53
|
$target = [Console]::In.ReadLine()
|
|
54
54
|
$ptr = [IntPtr]::Zero
|
|
@@ -61,7 +61,7 @@ try {
|
|
|
61
61
|
[System.Text.Encoding]::Unicode.GetString($bytes)
|
|
62
62
|
} finally {
|
|
63
63
|
[CredMan]::CredFree($ptr)
|
|
64
|
-
}`;try{let{stdout:n}=await
|
|
64
|
+
}`;try{let{stdout:n}=await jt(r,t),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=xt+S(e),n=JSON.stringify(t),o=`
|
|
65
65
|
${Et}
|
|
66
66
|
$target = [Console]::In.ReadLine()
|
|
67
67
|
$json = [Console]::In.ReadLine()
|
|
@@ -78,11 +78,11 @@ try {
|
|
|
78
78
|
if (-not $result) { throw "CredWrite failed" }
|
|
79
79
|
} finally {
|
|
80
80
|
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
|
|
81
|
-
}`;try{await
|
|
82
|
-
${n}`)}catch(s){throw new Error(`Windows Credential Manager write failed: ${String(s)}`)}}async remove(e){let t=
|
|
81
|
+
}`;try{await jt(o,`${r}
|
|
82
|
+
${n}`)}catch(s){throw new Error(`Windows Credential Manager write failed: ${String(s)}`)}}async remove(e){let t=xt+S(e),r=`
|
|
83
83
|
${Et}
|
|
84
84
|
$target = [Console]::In.ReadLine()
|
|
85
|
-
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await
|
|
85
|
+
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await jt(r,t)}catch{}}async list(){let e=`
|
|
86
86
|
${Et}
|
|
87
87
|
${Yn}
|
|
88
88
|
$prefix = [Console]::In.ReadLine()
|
|
@@ -98,8 +98,8 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
|
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
100
|
[CredMan]::CredFree($pCreds)
|
|
101
|
-
}`;try{let{stdout:t}=await
|
|
102
|
-
`).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function
|
|
101
|
+
}`;try{let{stdout:t}=await jt(e,xt);return t.trim().split(`
|
|
102
|
+
`).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function jt(i,e){for(let t of["pwsh","powershell"])try{return await Xn(t,["-NoProfile","-NonInteractive","-Command",i],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var Et=`
|
|
103
103
|
Add-Type -TypeDefinition @"
|
|
104
104
|
using System;
|
|
105
105
|
using System.Runtime.InteropServices;
|
|
@@ -131,7 +131,7 @@ public class CredMan {
|
|
|
131
131
|
public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
|
|
132
132
|
}
|
|
133
133
|
"@`,Yn="";import{execFile as Jn,spawn as Zn}from"child_process";import{promisify as Qn}from"util";var Vt=Qn(Jn),Ot="kanonak",at=class{async get(e){let t=S(e);try{let{stdout:r}=await Vt("secret-tool",["lookup","service",Ot,"publisher",t],{timeout:1e4}),n=r.trim();return n?JSON.parse(n):null}catch{return null}}async store(e,t){let r=S(e),n=JSON.stringify(t);await new Promise((o,s)=>{let a=Zn("secret-tool",["store","--label",`Kanonak: ${r}`,"service",Ot,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(n),a.stdin.end(),a.on("close",c=>{c===0?o():s(new Error(`secret-tool store exited with code ${c}`))}),a.on("error",s)})}async remove(e){let t=S(e);try{await Vt("secret-tool",["clear","service",Ot,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await Vt("secret-tool",["search","service",Ot],{timeout:1e4}),t=[];for(let r of e.split(`
|
|
134
|
-
`)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function sr(){try{return await Vt("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as
|
|
134
|
+
`)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function sr(){try{return await Vt("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as xr,mkdirSync as jr,readFileSync as Er,writeFileSync as Or}from"fs";import{createCipheriv as eo,createDecipheriv as to,randomBytes as Vr}from"crypto";import{homedir as ro}from"os";import{join as cr,dirname as Tr}from"path";var _r=cr(ro(),".config","kanonak"),it=cr(_r,"keyring.key"),Tt=cr(_r,"credentials.enc"),Nr="aes-256-gcm",ar=32,Ze=12,ir=16,ct=class{async get(e){let t=this.loadStore(),r=S(e);return t[r]??null}async store(e,t){let r=this.loadStore(),n=S(e);r[n]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=S(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!xr(Tt))return{};try{let e=this.getOrCreateKey(),t=Er(Tt);if(t.length<Ze+ir)return{};let r=t.subarray(0,Ze),n=t.subarray(Ze,Ze+ir),o=t.subarray(Ze+ir),s=to(Nr,e,r);s.setAuthTag(n);let a=Buffer.concat([s.update(o),s.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Vr(Ze),n=eo(Nr,t,r),o=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([n.update(o),n.final()]),a=n.getAuthTag(),c=Buffer.concat([r,a,s]);jr(Tr(Tt),{recursive:!0}),Or(Tt,c,{mode:384})}getOrCreateKey(){if(xr(it)){let t=Er(it);if(t.length!==ar)throw new Error(`Credential keyring key is corrupted (expected ${ar} bytes, got ${t.length}). Delete ${it} and re-authenticate.`);return t}let e=Vr(ar);return jr(Tr(it),{recursive:!0}),Or(it,e,{mode:384}),e}};import{execFile as no}from"child_process";import{promisify as oo}from"util";var so=oo(no),Ur=3e4,pt=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=S(e);try{let n=(await this.runHelper("get",{publisher:t})).trim();return n?JSON.parse(n):null}catch(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${Nt(r)}
|
|
135
135
|
Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
|
|
136
136
|
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=S(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${Nt(n)}
|
|
137
137
|
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=S(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${Nt(r)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${Nt(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await so(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Ur});return r}catch(r){throw ao(r)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
@@ -139,7 +139,7 @@ public class CredMan {
|
|
|
139
139
|
The helper may be waiting for authentication to an external vault.`):r}}};function Nt(i){return i instanceof Error?i.message:String(i)}function ao(i){return i instanceof Error&&"code"in i&&i.code==="ENOENT"}function io(i){return i instanceof Error&&"killed"in i&&i.killed}var pr=uo(lo(),".kanonak","config.json"),_t=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=mo(e);if(t)return t;let n=await(await this.getBackend()).get(e);return!n||!At(n)?null:n.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=yo();return e.credentialHelper?new pt(e.credentialHelper):process.platform==="darwin"?new ot:process.platform==="win32"?new st:await sr()?new at:new ct}};function mo(i){let t="KANONAK_TOKEN_"+S(i).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function yo(){if(!co(pr))return{};try{return JSON.parse(po(pr,"utf-8"))}catch(i){let e=i instanceof Error?i.message:String(i);return console.warn(` Warning: Failed to parse ${pr}: ${e}
|
|
140
140
|
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as fo,createPrivateKey as go,generateKeyPairSync as ho,randomUUID as ko,sign as bo}from"crypto";function Mr(){let{publicKey:i,privateKey:e}=ho("ec",{namedCurve:"P-256"});return{publicKey:i.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function lt(i,e,t,r,n,o){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:ko(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return n&&(a.ath=fo("sha256").update(n).digest("base64url")),o&&(a.nonce=o),Ro(s,a,i)}function Fr(i){return!i||i.length===0?!1:i.some(e=>e.toUpperCase()==="ES256")}function Ro(i,e,t){let r=Lr(JSON.stringify(i)),n=Lr(JSON.stringify(e)),o=`${r}.${n}`,s=go({key:t,format:"jwk"}),c=bo("SHA256",Buffer.from(o),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${o}.${c}`}function Lr(i){return Buffer.from(i,"utf-8").toString("base64url")}function Br(i){let e=new Map;return async(t,r,n="GET")=>{if(!i)return fetch(t,{method:n});let o=await i.getCredential(r);if(!o?.accessToken)return fetch(t,{method:n});nt(o)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let s={};if(o.dpopKeyPair){let c=e.get(r);try{let p=lt(o.dpopKeyPair.privateKey,o.dpopKeyPair.publicKey,n,t,o.accessToken,c);s.Authorization=`DPoP ${o.accessToken}`,s.DPoP=p}catch(p){let l=p instanceof Error?p.message:String(p);console.error(` Error: Failed to create DPoP proof for '${r}': ${l}
|
|
141
141
|
The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),s.Authorization=`Bearer ${o.accessToken}`}}else s.Authorization=`Bearer ${o.accessToken}`;let a=await fetch(t,{method:n,headers:s});if(a.status===401&&o.dpopKeyPair){let c=a.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let p=lt(o.dpopKeyPair.privateKey,o.dpopKeyPair.publicKey,n,t,o.accessToken,c);s.DPoP=p,a=await fetch(t,{method:n,headers:s})}catch{}}}return a}}import{readFileSync as vo,writeFileSync as Po,existsSync as wo}from"fs";import{createHash as Io}from"crypto";import Wr from"js-yaml";var Hr="kanonak.lock",So=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
142
|
-
`;function qr(i=Hr){if(!wo(i))return null;let e=vo(i,"utf-8"),t=Wr.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Gr(i,e=Hr){i.lastUpdated=new Date().toISOString();let t={};for(let n of Object.keys(i.packages).sort())t[n]=i.packages[n];i.packages=t;let r=Wr.dump(i,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Po(e,So+r,"utf-8")}function zr(i){return`sha256:${Io("sha256").update(i).digest("hex")}`}function Jr(i,e,t,r){let n=Xr(i);if(n.length>0){let a=n.find(c=>Ut(c.format,e)&&Ut(c.variant,t));return a?{transformation:a.transformation,source:"instance"}:void 0}let o=new Set,s=Ko(i);for(;s.length>0;){let a=s.shift(),c=jo(a.subject);if(o.has(c))continue;o.add(c);let p=$o(r,a.subject);if(!p)continue;let u=Xr(p).find(m=>Ut(m.format,e)&&Ut(m.variant,t));if(u)return{transformation:u.transformation,source:{publisher:a.subject.publisher,package_:a.subject.package_,name:a.subject.name}};for(let m of Co(p))s.push(m)}}function Xr(i){let e=[];for(let t of i.statement)if(t instanceof L&&Lt(t,"kanonak.org","derivation","derivations"))for(let r of t.object??[]){if(!(r instanceof _))continue;let n=Ao(r);n&&e.push(n)}return e}function Ao(i){let e,t,r;for(let n of i.statement)n instanceof U?Lt(n,"kanonak.org","derivation","format")?e=Yr(n):Lt(n,"kanonak.org","derivation","variant")&&(t=Yr(n)):n instanceof H&&Lt(n,"kanonak.org","derivation","transformation")&&(r=Do(n.object));if(!(!e||!r))return t||(t={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:e,variant:t,transformation:r}}function Do(i){let e,t,r,n;for(let o of i.statement){if(!(o instanceof W))continue;let s=o.predicate?.subject?.name;s==="publisher"?e=o.object:s==="package"?t=o.object:s==="version"?r=o.object:s==="name"&&(n=o.object)}if(!(!e||!t||!r||!n))return{publisher:e,package_:t,version:r,name:n}}function Ko(i){let e=[];for(let t of i.statement)t instanceof U&&t.predicate?.subject?.name==="type"&&t.object instanceof w&&e.push(t.object);return e}function Co(i){let e=[];for(let t of i.statement)if(t instanceof U){if(t.predicate?.subject?.name!=="subClassOf")continue;t.object instanceof w&&e.push(t.object)}else if(t instanceof L){if(t.predicate?.subject?.name!=="subClassOf")continue;for(let r of t.object??[])r instanceof w&&e.push(r)}return e}function $o(i,e){for(let t of i){if(!(t instanceof N)||t.name!==e.name)continue;if((t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))return t}}function Lt(i,e,t,r){let n=i.predicate?.subject;return n?n.publisher===e&&n.package_===t&&n.name===r:!1}function Yr(i){let e=i.object.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}function Ut(i,e){return i.publisher===e.publisher&&i.package_===e.package_&&i.name===e.name}function jo(i){return`${i.publisher}/${i.package_}/${i.name}`}import{CtlKanonakUriType as ut,PathSegmentType as lr}from"@kanonak-protocol/types/ctl/parsing/enums";var xo=/\.?([a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\])/g;function Eo(i){let e=i.split(".").map(Number),t=e[0]||0,r=e[1]||0,n=e[2]||0;return{major:t,minor:r,patch:n,toString:()=>`${t}.${r}.${n}`,equals:o=>o&&typeof o=="object"&&o.major===t&&o.minor===r&&o.patch===n,getHashCode:()=>t<<20|r<<10|n,compareTo:o=>t!==o.major?t-o.major:r!==o.minor?r-o.minor:n-o.patch}}var Te=class i{scheme="kanonak";publisher;package_;version;resourceName;path;rawUri;constructor(e){this.publisher=e.publisher,this.package_=e.package_,this.version=e.version,this.resourceName=e.resourceName,this.path=e.path??[],this.rawUri=e.rawUri}get uriType(){return this.path.length>0?ut.DeepLink:this.resourceName!=null?ut.Resource:this.version!=null?ut.VersionedPackage:this.package_!=null?ut.Package:ut.Publisher}get namespace_(){return this.package_==null?null:this.version==null?`${this.publisher}/${this.package_}`:`${this.publisher}/${this.package_}@${this.version}`}static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");if(!e.toLowerCase().startsWith("kanonak://"))throw new Error(`Invalid Kanonak URI: '${e}'. Must start with 'kanonak://'`);let t=e.substring(8);if(!t||t.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Publisher is required after 'kanonak://'`);let r=t.indexOf("#"),n=null,o;if(r>=0){if(o=t.substring(0,r),n=t.substring(r+1),!n||n.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Deep link path required after '#'`)}else o=t;let s,a=null,c=null,p=null,l=o.indexOf("@");if(l>=0){let m=o.substring(0,l),y=o.substring(l+1),f=m.indexOf("/");if(f<0)throw new Error(`Invalid Kanonak URI: '${e}'. Expected format: publisher/package@version/resource`);if(s=m.substring(0,f),a=m.substring(f+1),!s||s.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Publisher cannot be empty`);if(!a||a.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Package cannot be empty`);let d=y.indexOf("/");if(d<0)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package@version/resource)`);let g=y.substring(0,d);if(p=y.substring(d+1),!g||g.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Version required after '@'`);if(c=Eo(g),!p||p.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}else{let m=o.split("/");if(m.length<3)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package/resource)`);if(m.length>3)throw new Error(`Invalid Kanonak URI: '${e}'. Too many path segments. Expected: publisher/package/resource`);if(s=m[0],a=m[1],p=m[2],!s||s.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Publisher cannot be empty`);if(!a||a.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Package cannot be empty`);if(!p||p.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}let u=[];return n!=null&&(u=Oo(n,e)),new i({publisher:s,package_:a,version:c,resourceName:p,path:u,rawUri:e})}static tryParse(e){try{return i.parse(e)}catch{return null}}static isKanonakUri(e){return!!e&&e.trim().length>0&&e.toLowerCase().startsWith("kanonak://")}toString(){let e=`kanonak://${this.publisher}`;if(this.package_!=null&&(e+=`/${this.package_}`,this.version!=null&&(e+=`@${this.version}`),this.resourceName!=null&&(e+=`/${this.resourceName}`,this.path.length>0))){e+="#";let t=!0;for(let r of this.path)r.type_===lr.Index?e+=`[${r.index}]`:(t||(e+="."),e+=r.name),t=!1}return e}equals(e){return e instanceof i?this.rawUri.toLowerCase()===e.rawUri.toLowerCase():!1}getHashCode(){let e=0,t=this.rawUri.toLowerCase();for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return e}};function Oo(i,e){let t=[],r=new RegExp(xo.source,"g"),n=0,o;for(;(o=r.exec(i))!==null;){let s=o[1];if(s.startsWith("[")&&s.endsWith("]")){let a=s.substring(1,s.length-1),c=parseInt(a,10);if(isNaN(c))throw new Error(`Invalid Kanonak URI: '${e}'. Invalid array index: ${s}`);t.push({type_:lr.Index,index:c,toString:()=>`[${c}]`})}else t.push({type_:lr.Property,name:s,toString:()=>s});n+=o[0].length}if(n!==i.length)throw new Error(`Invalid Kanonak URI: '${e}'. Invalid path syntax in: ${i}`);return t}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";import*as en from"js-yaml";var Vo=/\[([^\]]+)\]\((kanonak:\/\/[^)]+)\)/gi,To=/\[([^\]]+)\]\(kan:\/\/([^)]+)\)/gi,No=/```[\s\S]*?```|`[^`]+`/g,_o=/^---\s*\n([\s\S]*?)\n---\s*\n/;function Uo(i,e,t){let r=`${i}.${e}.${t}`;return{major:i,minor:e,patch:t,toString:()=>r,equals:n=>n?.major===i&&n?.minor===e&&n?.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:n=>i!==n.major?i-n.major:e!==n.minor?e-n.minor:t-n.patch}}function Lo(i,e,t,r,n){let o=r===ae.Compatible?"~":r===ae.Major?"^":r===ae.Exact?"=":"*",s=`${e} ${o} ${t}`;return{package_:s,publisher:i,packageName:e,versionOperator:r,version:t,alias:n,get minVersion(){return t},get maxVersion(){return t},toEmbeddedObject(){let a={package:e,version:t.toString()};return n&&(a.alias=n),r!==ae.Exact&&(a.match=o),a},toString(){return s}}}var Mt=class{parse(e,t){if(e==null)throw new Error("Content cannot be null");e.charCodeAt(0)===65279&&(e=e.substring(1));let r=_o.exec(e);return r?this.parseWithFrontmatter(e,r,t??null):this.parseInline(e,t??null)}async parseFileAsync(e){if(!e||e.trim().length===0)throw new Error("File path cannot be null or empty");let r=(await import("fs")).readFileSync(e,"utf-8");return this.parse(r,e)}parseWithFrontmatter(e,t,r){let n=t[1],o=e.substring(t[0].length),s=null,a=new Map;try{let p=en.load(n);if(!p)throw new Error("Frontmatter YAML is empty");if(!p.imports||!Array.isArray(p.imports))throw new Error("Frontmatter must contain an 'imports' sequence");let l={};for(let m of p.imports){if(!m||typeof m!="object")throw new Error("Each import entry must be a mapping with 'publisher' and 'packages'");let y=m.publisher?.toString();if(!y)throw new Error("Each import entry requires a 'publisher' property");if(!m.packages||!Array.isArray(m.packages))throw new Error(`Import entry for publisher '${y}' requires a 'packages' sequence`);l[y]||(l[y]=[]);for(let f of m.packages){if(!f||typeof f!="object")throw new Error(`Each package in publisher '${y}' must be a mapping`);let g=(f.version?.toString()??"1.0.0").split(".").map(Number),h=Uo(g[0]||0,g[1]||0,g[2]||0),b=f.match?.toString(),R=b==="^"?ae.Major:b==="~"?ae.Compatible:b==="*"?ae.Any:ae.Exact,v=Lo(y,f.package?.toString()??"",h,R,f.alias?.toString()??null);l[y].push(v)}}let u=[];for(let m of Object.values(l))u.push(...m);s={namespace_:void 0,imports:l,get allImports(){return u}},a=this.buildAliasMap(l)}catch(p){let l={displayText:"(frontmatter)",rawUri:"",startOffset:0,endOffset:t[0].length,line:1,column:1,isResolved:!1,error:`Failed to parse frontmatter: ${p.message}`,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};return ur({metadata:null,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:[l]})}let c=this.parseMarkdownBody(o,a,t[0].length);return ur({metadata:s,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:c})}parseInline(e,t){let r=this.parseMarkdownBody(e,new Map,0);return ur({metadata:null,rawMarkdown:e,frontmatterLength:0,filePath:t,references:r})}parseMarkdownBody(e,t,r){let n=[],o=Mo(e),s=new RegExp(Vo.source,"gi"),a;for(;(a=s.exec(e))!==null;){if(Zr(a.index,o))continue;let p=a[1],l=a[2],{line:u,column:m}=Qr(e,a.index),y={displayText:p,rawUri:l,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:m,isResolved:!1,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};try{y.parsedUri=Te.parse(l)}catch(f){y.error=f.message}n.push(y)}let c=new RegExp(To.source,"gi");for(;(a=c.exec(e))!==null;){if(Zr(a.index,o))continue;let p=a[1],l=a[2],{line:u,column:m}=Qr(e,a.index),y=null,f=null;try{y=Fo(l,t)}catch(g){f=g.message}let d={displayText:p,rawUri:y??`kan://${l}`,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:m,isResolved:!1,error:f,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};if(y!=null&&f==null)try{d.parsedUri=Te.parse(y)}catch(g){d.error=g.message}n.push(d)}return n.sort((p,l)=>p.startOffset-l.startOffset),n}buildAliasMap(e){let t=new Map;for(let[r,n]of Object.entries(e))for(let o of n){let s=o.alias??o.packageName;t.set(s.toLowerCase(),{publisher:r,package_:o.packageName,version:o.version})}return t}};function ur(i){return{metadata:i.metadata,get hasFrontmatter(){return i.metadata!=null},rawMarkdown:i.rawMarkdown,frontmatterLength:i.frontmatterLength,filePath:i.filePath,references:i.references,get referenceCount(){return i.references.length},get allReferencesResolved(){return i.references.every(e=>e.isResolved)},get unresolvedReferences(){return i.references.filter(e=>!e.isResolved)},get errorReferences(){return i.references.filter(e=>e.error!=null)}}}function Mo(i){let e=[],t=new RegExp(No.source,"g"),r;for(;(r=t.exec(i))!==null;)e.push([r.index,r.index+r[0].length]);return e}function Zr(i,e){for(let[t,r]of e)if(i>=t&&i<r)return!0;return!1}function Qr(i,e){let t=1,r=1;for(let n=0;n<e&&n<i.length;n++)i[n]===`
|
|
143
|
-
`?(t++,r=1):r++;return{line:t,column:r}}function Fo(i,e){if(!i||i.trim().length===0)throw new Error("kan:// link cannot be empty");if(e.size===0)throw new Error("kan:// links require frontmatter with imports");let t=null,r=i,n=i.indexOf(".");if(n>0&&(t=i.substring(0,n),r=i.substring(n+1),!r||r.trim().length===0))throw new Error(`Resource name required after alias '${t}.'`);if(t!=null){let o=e.get(t.toLowerCase());if(!o){let s=Array.from(e.keys()).join(", ");throw new Error(`Unknown alias: '${t}'. Available: ${s}`)}return`kanonak://${o.publisher}/${o.package_}@${o.version}/${r}`}else{let o=e.values().next().value;if(!o)throw new Error(`Cannot resolve '${r}': no imports defined`);return`kanonak://${o.publisher}/${o.package_}@${o.version}/${r}`}}import{CtlValidationErrorType as J,CtlValidationSeverity as ie}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as tn,PathSegmentType as rn}from"@kanonak-protocol/types/ctl/parsing/enums";var Ft=class{repository;constructor(e){if(!e)throw new Error("Repository is required for CTL validation");this.repository=e}async validateAsync(e){if(!e)throw new Error("Document cannot be null");let t=[],r=[];for(let o of e.references){if(!o.parsedUri){t.push({errorType:J.InvalidUri,severity:ie.Error,message:o.error??"Failed to parse Kanonak URI",reference:o,line:o.line,column:o.column,toString(){let s=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${s}`.trim()}});continue}try{await this.resolveReference(o,t,r)}catch(s){t.push({errorType:J.ParseError,severity:ie.Error,message:`Error resolving reference: ${s.message}`,reference:o,line:o.line,column:o.column,toString(){let a=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${a}`.trim()}})}}return{isValid:t.length===0,document:e,errors:t,warnings:r,get totalReferences(){return e.referenceCount},get resolvedReferences(){return e.references.filter(o=>o.isResolved).length},get summary(){if(t.length===0)return`All ${e.referenceCount} references validated`;let o=e.references.filter(s=>s.isResolved).length;return`${t.length} error(s), ${o}/${e.referenceCount} references resolved`}}}async resolveReference(e,t,r){let n=e.parsedUri;switch(n.uriType){case tn.Resource:await this.resolveResource(e,t);break;case tn.DeepLink:await this.resolveDeepLink(e,t);break;default:t.push({errorType:J.InvalidUri,severity:ie.Error,message:`Unsupported URI type: ${n.uriType}. CTL only supports resource references.`,reference:e,line:e.line,column:e.column,suggestion:"Use resource URIs: kanonak://publisher/package@version/resource",toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${o}`.trim()}});break}}async resolveResource(e,t){let r=e.parsedUri,n=r.namespace_,o=await this.repository.getDocumentAsync(n);if(!o){t.push(this.createError(J.PackageNotFound,`Package not found: ${n}`,e));return}if(o.body&&o.body[r.resourceName])e.isResolved=!0;else{let s=o.body?Object.keys(o.body).slice(0,5):[];t.push(this.createError(J.EntityNotFound,`Resource not found: ${r.resourceName} in ${n}`,e,s.length>0?`Available resources: ${s.join(", ")}`:void 0))}}async resolveDeepLink(e,t){let r=e.parsedUri,n=r.namespace_,o=await this.repository.getDocumentAsync(n);if(!o){t.push(this.createError(J.PackageNotFound,`Package not found: ${n}`,e));return}if(!o.body||!o.body[r.resourceName]){t.push(this.createError(J.EntityNotFound,`Resource not found: ${r.resourceName} in ${n}`,e));return}let s=o.body[r.resourceName],a=r.resourceName;for(let c of r.path){if(s==null){t.push(this.createError(J.PathNotFound,`Path not found: ${a}`,e));return}if(c.type_===rn.Property){let p=c.name;a+=`.${p}`;let l=Bo(s,p);if(l===void 0){let u=Ho(s);t.push(this.createError(J.PathNotFound,`Path not found: ${a}`,e,u));return}s=l}else if(c.type_===rn.Index){let p=c.index;a+=`[${p}]`;let l=Wo(s,p);if(l===void 0){let u=qo(s);t.push(this.createError(J.IndexOutOfBounds,`Index out of bounds: ${a}`,e,u));return}s=l}}e.isResolved=!0,e.resolvedValue=s}createError(e,t,r,n){return{errorType:e,severity:ie.Error,message:t,reference:r,line:r.line,column:r.column,suggestion:n,toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${o}`.trim()}}}};function Bo(i,e){if(i&&typeof i=="object"&&!Array.isArray(i)){if(e in i)return i[e];let t=Object.keys(i).find(r=>r.toLowerCase()===e.toLowerCase());if(t)return i[t]}}function Wo(i,e){if(Array.isArray(i)&&e>=0&&e<i.length)return i[e]}function Ho(i){if(i&&typeof i=="object"&&!Array.isArray(i)){let e=Object.keys(i).slice(0,5);if(e.length>0)return`Available properties: ${e.join(", ")}`}}function qo(i){if(Array.isArray(i))return i.length>0?`Collection has ${i.length} items (valid indices: 0-${i.length-1})`:"Collection is empty"}import{ResolvedResourceType as Ne}from"@kanonak-protocol/types/ctl/resolution/enums";var Go=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);var Bt=class{repository;constructor(e){if(!e)throw new Error("Repository is required for CTL graph resolution");this.repository=e}async resolveAsync(e,t=1e3){if(!e)throw new Error("Document cannot be null");let r=new Set,n=[],o=[],s=[],a=[],c=new Set;for(let d of e.references)d.parsedUri&&c.add(d.parsedUri.toString());let p=new Map,l=new Map,u=await this.repository.getAllDocumentsAsync();for(let d of u){let g=d.metadata?.namespace_?.toString();if(!g||!d.body)continue;let h=[];for(let[b,R]of Object.entries(d.body))if(R&&typeof R=="object"&&!Array.isArray(R)){let v=this.createMockSubjectKanonak(b,R,g),x=`kanonak://${g}/${b}`;p.has(x)||p.set(x,{entity:v,namespace:g}),h.push(v)}l.set(g,h)}let m=0,y=!1;for(let d of e.references){if(!d.parsedUri){a.push({reference:d.rawUri,reason:d.error??"Failed to parse URI"});continue}let g=d.parsedUri.toString();if(r.has(g))continue;let h=await this.resolveEntityRecursive(g,null,null,0,t,r,c,n,o,s,a,p,l);m=Math.max(m,h),h>=t&&(y=!0)}let f=Zo(e.rawMarkdown);return{sourceFile:e.filePath??null,originalContent:e.rawMarkdown,title:f,directReferences:n,inheritedReferences:o,foundationTypes:s,get totalResourceCount(){return n.length+o.length+s.length},get allResources(){return[...n,...o,...s]},maxDepthReached:m,wasTruncated:y,unresolvedResources:a}}async resolveEntityRecursive(e,t,r,n,o,s,a,c,p,l,u,m,y){if(s.has(e)||(s.add(e),n>=o))return n;if(!t){let R=m.get(e);if(!R)return u.push({reference:e,reason:"Resource not found in workspace"}),n;t=R.entity}let f=t,d=f.namespace??f.namespace_??"";!r&&d&&(r=await this.repository.getDocumentAsync(d));let g=this.createResolvedResource(t,e,n,y);switch(this.classifyTier(e,d,a)){case 0:c.push(g);break;case 2:l.push(g);break;default:p.push(g);break}let b=n;for(let R of g.parentClasses){let v=this.resolveReferenceToUri(R,d,r);if(v&&!s.has(v)){let x=m.get(v),V=await this.resolveEntityRecursive(v,x?.entity??null,null,n+1,o,s,a,c,p,l,u,m,y);b=Math.max(b,V)}}for(let R of g.properties.filter(v=>v.isObjectProperty)){let v=this.resolveReferenceToUri(R.rangeType,d,r);if(v&&!s.has(v)){let x=m.get(v),V=await this.resolveEntityRecursive(v,x?.entity??null,null,n+1,o,s,a,c,p,l,u,m,y);b=Math.max(b,V)}}if(g.instanceOf_){let R=this.resolveReferenceToUri(g.instanceOf_,d,r);if(R&&!s.has(R)){let v=m.get(R),x=await this.resolveEntityRecursive(R,v?.entity??null,null,n+1,o,s,a,c,p,l,u,m,y);b=Math.max(b,x)}}return b}createResolvedResource(e,t,r,n){let o=e,s=o.name??"",a=o.namespace??o.namespace_??"",c=this.classifyEntityType(e),p=nn(e),l=Xo(e),u=Yo(e),m=[];if(c===Ne.Class){let y=n.get(a);y&&(m=Jo(s,y))}return{name:s,kanonakUri:t,resource:e,resourceType:c,parentClass:l.length>0?l[0]:null,parentClasses:l,comment:p,properties:m,namespace_:a,resolutionDepth:r,instanceOf_:u}}classifyEntityType(e){if(I.isClassType(e))return Ne.Class;if(I.isAnnotationPropertyType(e))return Ne.AnnotationProperty;if(I.isDatatypePropertyType(e))return Ne.DatatypeProperty;if(I.isObjectPropertyType(e))return Ne.ObjectProperty;let t=I.getTypeUri(e);return t&&!I.isCoreOntologyType(t)?Ne.Instance:Ne.Other}classifyTier(e,t,r){return r.has(e)?0:zo(t)?2:1}resolveReferenceToUri(e,t,r){if(e.toLowerCase().startsWith("kanonak://"))return e;if(e.includes(".")&&r?.metadata){let n=e.indexOf("."),o=e.substring(0,n),s=e.substring(n+1);if(s){let a=r.metadata.allImports;if(a){for(let c of a)if((c.alias??c.packageName).toLowerCase()===o.toLowerCase())return`kanonak://${c.version?`${c.publisher}/${c.packageName}@${c.version}`:`${c.publisher}/${c.packageName}`}/${s}`}}}return!e.includes(".")&&t?`kanonak://${t}/${e}`:null}createMockSubjectKanonak(e,t,r){let n=[];for(let[o,s]of Object.entries(t))typeof s=="string"?o==="type"||o==="subClassOf"||o==="domain"||o==="range"||o==="subPropertyOf"?n.push({predicate:{subject:{name:o,publisher:"",package_:""}},object:{subject:{name:s,publisher:"",package_:""}}}):n.push({predicate:{subject:{name:o,publisher:"",package_:""}},object:s}):Array.isArray(s)&&n.push({predicate:{subject:{name:o,publisher:"",package_:""}},object:s.map(a=>typeof a=="string"?{subject:{name:a,publisher:"",package_:""}}:a)});return{name:e,namespace_:r,statement:n,entity:t}}};function zo(i){if(!i)return!1;let e=i.split("/");if(e.length<2)return!1;let t=e[0],r=e[1],n=r.includes("@")?r.split("@")[0]:r;return Go.has(`${t}/${n}`)}function nn(i){let e=i;if(e.entity&&typeof e.entity=="object")return e.entity.comment??null;if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="comment"&&typeof t.object=="string")return t.object}return null}function Xo(i){let e=[],t=i,r=t.name??"";if(t.entity&&typeof t.entity=="object"){let n=t.entity.subClassOf;if(typeof n=="string")n.toLowerCase()!==r.toLowerCase()&&e.push(n);else if(Array.isArray(n))for(let o of n){let s=typeof o=="string"?o:o?.subject?.name??o?.name;s&&s.toLowerCase()!==r.toLowerCase()&&e.push(s)}return e}if(t.statement&&Array.isArray(t.statement)){for(let n of t.statement)if(n.predicate?.subject?.name==="subClassOf"){if(n.object?.subject?.name){let o=n.object.subject.name;o.toLowerCase()!==r.toLowerCase()&&e.push(o)}else if(Array.isArray(n.object))for(let o of n.object){let s=o?.subject?.name??o?.name;s&&s.toLowerCase()!==r.toLowerCase()&&e.push(s)}}}return e}function Yo(i){let e=I.getTypeUri(i);return e?I.isCoreOntologyType(e)?null:e.name:null}function Jo(i,e){let t=[];for(let r of e){if(!I.isAnyPropertyType(r))continue;let n=r,o=[],s=[];if(n.entity&&typeof n.entity=="object"){let l=n.entity.domain;if(typeof l=="string")o.push(l);else if(Array.isArray(l))for(let m of l)o.push(typeof m=="string"?m:m?.name??String(m));let u=n.entity.range;if(typeof u=="string")s.push(u);else if(Array.isArray(u))for(let m of u)s.push(typeof m=="string"?m:m?.name??String(m))}if(!o.some(l=>l.toLowerCase()===i.toLowerCase()))continue;s.length===0&&s.push("unknown");let a=I.isObjectPropertyType(r),c=n.entity?.collection!=null,p=nn(r);t.push({name:n.name??"",rangeTypes:s,domains:o,get rangeType(){return s.length>0?s.join(", "):"unknown"},isObjectProperty:a,isCollection:c,comment:p})}return t}function Zo(i){let e=i.split(`
|
|
142
|
+
`;function qr(i=Hr){if(!wo(i))return null;let e=vo(i,"utf-8"),t=Wr.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Gr(i,e=Hr){i.lastUpdated=new Date().toISOString();let t={};for(let n of Object.keys(i.packages).sort())t[n]=i.packages[n];i.packages=t;let r=Wr.dump(i,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Po(e,So+r,"utf-8")}function zr(i){return`sha256:${Io("sha256").update(i).digest("hex")}`}function Jr(i,e,t,r){let n=Xr(i);if(n.length>0){let a=n.find(c=>Ut(c.format,e)&&Ut(c.variant,t));return a?{transformation:a.transformation,source:"instance"}:void 0}let o=new Set,s=Ko(i);for(;s.length>0;){let a=s.shift(),c=xo(a.subject);if(o.has(c))continue;o.add(c);let p=$o(r,a.subject);if(!p)continue;let u=Xr(p).find(m=>Ut(m.format,e)&&Ut(m.variant,t));if(u)return{transformation:u.transformation,source:{publisher:a.subject.publisher,package_:a.subject.package_,name:a.subject.name}};for(let m of Co(p))s.push(m)}}function Xr(i){let e=[];for(let t of i.statement)if(t instanceof L&&Lt(t,"kanonak.org","derivation","derivations"))for(let r of t.object??[]){if(!(r instanceof _))continue;let n=Ao(r);n&&e.push(n)}return e}function Ao(i){let e,t,r;for(let n of i.statement)n instanceof U?Lt(n,"kanonak.org","derivation","format")?e=Yr(n):Lt(n,"kanonak.org","derivation","variant")&&(t=Yr(n)):n instanceof H&&Lt(n,"kanonak.org","derivation","transformation")&&(r=Do(n.object));if(!(!e||!r))return t||(t={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:e,variant:t,transformation:r}}function Do(i){let e,t,r,n;for(let o of i.statement){if(!(o instanceof W))continue;let s=o.predicate?.subject?.name;s==="publisher"?e=o.object:s==="package"?t=o.object:s==="version"?r=o.object:s==="name"&&(n=o.object)}if(!(!e||!t||!r||!n))return{publisher:e,package_:t,version:r,name:n}}function Ko(i){let e=[];for(let t of i.statement)t instanceof U&&t.predicate?.subject?.name==="type"&&t.object instanceof w&&e.push(t.object);return e}function Co(i){let e=[];for(let t of i.statement)if(t instanceof U){if(t.predicate?.subject?.name!=="subClassOf")continue;t.object instanceof w&&e.push(t.object)}else if(t instanceof L){if(t.predicate?.subject?.name!=="subClassOf")continue;for(let r of t.object??[])r instanceof w&&e.push(r)}return e}function $o(i,e){for(let t of i){if(!(t instanceof N)||t.name!==e.name)continue;if((t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))return t}}function Lt(i,e,t,r){let n=i.predicate?.subject;return n?n.publisher===e&&n.package_===t&&n.name===r:!1}function Yr(i){let e=i.object.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}function Ut(i,e){return i.publisher===e.publisher&&i.package_===e.package_&&i.name===e.name}function xo(i){return`${i.publisher}/${i.package_}/${i.name}`}import{CtlKanonakUriType as ut,PathSegmentType as lr}from"@kanonak-protocol/types/ctl/parsing/enums";var jo=/\.?([a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\])/g;function Eo(i){let e=i.split(".").map(Number),t=e[0]||0,r=e[1]||0,n=e[2]||0;return{major:t,minor:r,patch:n,toString:()=>`${t}.${r}.${n}`,equals:o=>o&&typeof o=="object"&&o.major===t&&o.minor===r&&o.patch===n,getHashCode:()=>t<<20|r<<10|n,compareTo:o=>t!==o.major?t-o.major:r!==o.minor?r-o.minor:n-o.patch}}var Te=class i{scheme="kanonak";publisher;package_;version;resourceName;path;rawUri;constructor(e){this.publisher=e.publisher,this.package_=e.package_,this.version=e.version,this.resourceName=e.resourceName,this.path=e.path??[],this.rawUri=e.rawUri}get uriType(){return this.path.length>0?ut.DeepLink:this.resourceName!=null?ut.Resource:this.version!=null?ut.VersionedPackage:this.package_!=null?ut.Package:ut.Publisher}get namespace_(){return this.package_==null?null:this.version==null?`${this.publisher}/${this.package_}`:`${this.publisher}/${this.package_}@${this.version}`}static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");if(!e.toLowerCase().startsWith("kanonak://"))throw new Error(`Invalid Kanonak URI: '${e}'. Must start with 'kanonak://'`);let t=e.substring(8);if(!t||t.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Publisher is required after 'kanonak://'`);let r=t.indexOf("#"),n=null,o;if(r>=0){if(o=t.substring(0,r),n=t.substring(r+1),!n||n.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Deep link path required after '#'`)}else o=t;let s,a=null,c=null,p=null,l=o.indexOf("@");if(l>=0){let m=o.substring(0,l),y=o.substring(l+1),f=m.indexOf("/");if(f<0)throw new Error(`Invalid Kanonak URI: '${e}'. Expected format: publisher/package@version/resource`);if(s=m.substring(0,f),a=m.substring(f+1),!s||s.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Publisher cannot be empty`);if(!a||a.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Package cannot be empty`);let d=y.indexOf("/");if(d<0)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package@version/resource)`);let g=y.substring(0,d);if(p=y.substring(d+1),!g||g.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Version required after '@'`);if(c=Eo(g),!p||p.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}else{let m=o.split("/");if(m.length<3)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package/resource)`);if(m.length>3)throw new Error(`Invalid Kanonak URI: '${e}'. Too many path segments. Expected: publisher/package/resource`);if(s=m[0],a=m[1],p=m[2],!s||s.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Publisher cannot be empty`);if(!a||a.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Package cannot be empty`);if(!p||p.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}let u=[];return n!=null&&(u=Oo(n,e)),new i({publisher:s,package_:a,version:c,resourceName:p,path:u,rawUri:e})}static tryParse(e){try{return i.parse(e)}catch{return null}}static isKanonakUri(e){return!!e&&e.trim().length>0&&e.toLowerCase().startsWith("kanonak://")}toString(){let e=`kanonak://${this.publisher}`;if(this.package_!=null&&(e+=`/${this.package_}`,this.version!=null&&(e+=`@${this.version}`),this.resourceName!=null&&(e+=`/${this.resourceName}`,this.path.length>0))){e+="#";let t=!0;for(let r of this.path)r.type_===lr.Index?e+=`[${r.index}]`:(t||(e+="."),e+=r.name),t=!1}return e}equals(e){return e instanceof i?this.rawUri.toLowerCase()===e.rawUri.toLowerCase():!1}getHashCode(){let e=0,t=this.rawUri.toLowerCase();for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e|=0;return e}};function Oo(i,e){let t=[],r=new RegExp(jo.source,"g"),n=0,o;for(;(o=r.exec(i))!==null;){let s=o[1];if(s.startsWith("[")&&s.endsWith("]")){let a=s.substring(1,s.length-1),c=parseInt(a,10);if(isNaN(c))throw new Error(`Invalid Kanonak URI: '${e}'. Invalid array index: ${s}`);t.push({type_:lr.Index,index:c,toString:()=>`[${c}]`})}else t.push({type_:lr.Property,name:s,toString:()=>s});n+=o[0].length}if(n!==i.length)throw new Error(`Invalid Kanonak URI: '${e}'. Invalid path syntax in: ${i}`);return t}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";import*as en from"js-yaml";var Vo=/\[([^\]]+)\]\((kanonak:\/\/[^)]+)\)/gi,To=/\[([^\]]+)\]\(kan:\/\/([^)]+)\)/gi,No=/```[\s\S]*?```|`[^`]+`/g,_o=/^---\s*\n([\s\S]*?)\n---\s*\n/;function Uo(i,e,t){let r=`${i}.${e}.${t}`;return{major:i,minor:e,patch:t,toString:()=>r,equals:n=>n?.major===i&&n?.minor===e&&n?.patch===t,getHashCode:()=>i<<20|e<<10|t,compareTo:n=>i!==n.major?i-n.major:e!==n.minor?e-n.minor:t-n.patch}}function Lo(i,e,t,r,n){let o=r===ae.Compatible?"~":r===ae.Major?"^":r===ae.Exact?"=":"*",s=`${e} ${o} ${t}`;return{package_:s,publisher:i,packageName:e,versionOperator:r,version:t,alias:n,get minVersion(){return t},get maxVersion(){return t},toEmbeddedObject(){let a={package:e,version:t.toString()};return n&&(a.alias=n),r!==ae.Exact&&(a.match=o),a},toString(){return s}}}var Mt=class{parse(e,t){if(e==null)throw new Error("Content cannot be null");e.charCodeAt(0)===65279&&(e=e.substring(1));let r=_o.exec(e);return r?this.parseWithFrontmatter(e,r,t??null):this.parseInline(e,t??null)}async parseFileAsync(e){if(!e||e.trim().length===0)throw new Error("File path cannot be null or empty");let r=(await import("fs")).readFileSync(e,"utf-8");return this.parse(r,e)}parseWithFrontmatter(e,t,r){let n=t[1],o=e.substring(t[0].length),s=null,a=new Map;try{let p=en.load(n);if(!p)throw new Error("Frontmatter YAML is empty");if(!p.imports||!Array.isArray(p.imports))throw new Error("Frontmatter must contain an 'imports' sequence");let l={};for(let m of p.imports){if(!m||typeof m!="object")throw new Error("Each import entry must be a mapping with 'publisher' and 'packages'");let y=m.publisher?.toString();if(!y)throw new Error("Each import entry requires a 'publisher' property");if(!m.packages||!Array.isArray(m.packages))throw new Error(`Import entry for publisher '${y}' requires a 'packages' sequence`);l[y]||(l[y]=[]);for(let f of m.packages){if(!f||typeof f!="object")throw new Error(`Each package in publisher '${y}' must be a mapping`);let g=(f.version?.toString()??"1.0.0").split(".").map(Number),h=Uo(g[0]||0,g[1]||0,g[2]||0),k=f.match?.toString(),R=k==="^"?ae.Major:k==="~"?ae.Compatible:k==="*"?ae.Any:ae.Exact,v=Lo(y,f.package?.toString()??"",h,R,f.alias?.toString()??null);l[y].push(v)}}let u=[];for(let m of Object.values(l))u.push(...m);s={namespace_:void 0,imports:l,get allImports(){return u}},a=this.buildAliasMap(l)}catch(p){let l={displayText:"(frontmatter)",rawUri:"",startOffset:0,endOffset:t[0].length,line:1,column:1,isResolved:!1,error:`Failed to parse frontmatter: ${p.message}`,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};return ur({metadata:null,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:[l]})}let c=this.parseMarkdownBody(o,a,t[0].length);return ur({metadata:s,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:c})}parseInline(e,t){let r=this.parseMarkdownBody(e,new Map,0);return ur({metadata:null,rawMarkdown:e,frontmatterLength:0,filePath:t,references:r})}parseMarkdownBody(e,t,r){let n=[],o=Mo(e),s=new RegExp(Vo.source,"gi"),a;for(;(a=s.exec(e))!==null;){if(Zr(a.index,o))continue;let p=a[1],l=a[2],{line:u,column:m}=Qr(e,a.index),y={displayText:p,rawUri:l,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:m,isResolved:!1,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};try{y.parsedUri=Te.parse(l)}catch(f){y.error=f.message}n.push(y)}let c=new RegExp(To.source,"gi");for(;(a=c.exec(e))!==null;){if(Zr(a.index,o))continue;let p=a[1],l=a[2],{line:u,column:m}=Qr(e,a.index),y=null,f=null;try{y=Fo(l,t)}catch(g){f=g.message}let d={displayText:p,rawUri:y??`kan://${l}`,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:m,isResolved:!1,error:f,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};if(y!=null&&f==null)try{d.parsedUri=Te.parse(y)}catch(g){d.error=g.message}n.push(d)}return n.sort((p,l)=>p.startOffset-l.startOffset),n}buildAliasMap(e){let t=new Map;for(let[r,n]of Object.entries(e))for(let o of n){let s=o.alias??o.packageName;t.set(s.toLowerCase(),{publisher:r,package_:o.packageName,version:o.version})}return t}};function ur(i){return{metadata:i.metadata,get hasFrontmatter(){return i.metadata!=null},rawMarkdown:i.rawMarkdown,frontmatterLength:i.frontmatterLength,filePath:i.filePath,references:i.references,get referenceCount(){return i.references.length},get allReferencesResolved(){return i.references.every(e=>e.isResolved)},get unresolvedReferences(){return i.references.filter(e=>!e.isResolved)},get errorReferences(){return i.references.filter(e=>e.error!=null)}}}function Mo(i){let e=[],t=new RegExp(No.source,"g"),r;for(;(r=t.exec(i))!==null;)e.push([r.index,r.index+r[0].length]);return e}function Zr(i,e){for(let[t,r]of e)if(i>=t&&i<r)return!0;return!1}function Qr(i,e){let t=1,r=1;for(let n=0;n<e&&n<i.length;n++)i[n]===`
|
|
143
|
+
`?(t++,r=1):r++;return{line:t,column:r}}function Fo(i,e){if(!i||i.trim().length===0)throw new Error("kan:// link cannot be empty");if(e.size===0)throw new Error("kan:// links require frontmatter with imports");let t=null,r=i,n=i.indexOf(".");if(n>0&&(t=i.substring(0,n),r=i.substring(n+1),!r||r.trim().length===0))throw new Error(`Resource name required after alias '${t}.'`);if(t!=null){let o=e.get(t.toLowerCase());if(!o){let s=Array.from(e.keys()).join(", ");throw new Error(`Unknown alias: '${t}'. Available: ${s}`)}return`kanonak://${o.publisher}/${o.package_}@${o.version}/${r}`}else{let o=e.values().next().value;if(!o)throw new Error(`Cannot resolve '${r}': no imports defined`);return`kanonak://${o.publisher}/${o.package_}@${o.version}/${r}`}}import{CtlValidationErrorType as J,CtlValidationSeverity as ie}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as tn,PathSegmentType as rn}from"@kanonak-protocol/types/ctl/parsing/enums";var Ft=class{repository;constructor(e){if(!e)throw new Error("Repository is required for CTL validation");this.repository=e}async validateAsync(e){if(!e)throw new Error("Document cannot be null");let t=[],r=[];for(let o of e.references){if(!o.parsedUri){t.push({errorType:J.InvalidUri,severity:ie.Error,message:o.error??"Failed to parse Kanonak URI",reference:o,line:o.line,column:o.column,toString(){let s=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${s}`.trim()}});continue}try{await this.resolveReference(o,t,r)}catch(s){t.push({errorType:J.ParseError,severity:ie.Error,message:`Error resolving reference: ${s.message}`,reference:o,line:o.line,column:o.column,toString(){let a=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${a}`.trim()}})}}return{isValid:t.length===0,document:e,errors:t,warnings:r,get totalReferences(){return e.referenceCount},get resolvedReferences(){return e.references.filter(o=>o.isResolved).length},get summary(){if(t.length===0)return`All ${e.referenceCount} references validated`;let o=e.references.filter(s=>s.isResolved).length;return`${t.length} error(s), ${o}/${e.referenceCount} references resolved`}}}async resolveReference(e,t,r){let n=e.parsedUri;switch(n.uriType){case tn.Resource:await this.resolveResource(e,t);break;case tn.DeepLink:await this.resolveDeepLink(e,t);break;default:t.push({errorType:J.InvalidUri,severity:ie.Error,message:`Unsupported URI type: ${n.uriType}. CTL only supports resource references.`,reference:e,line:e.line,column:e.column,suggestion:"Use resource URIs: kanonak://publisher/package@version/resource",toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${o}`.trim()}});break}}async resolveResource(e,t){let r=e.parsedUri,n=r.namespace_,o=await this.repository.getDocumentAsync(n);if(!o){t.push(this.createError(J.PackageNotFound,`Package not found: ${n}`,e));return}if(o.body&&o.body[r.resourceName])e.isResolved=!0;else{let s=o.body?Object.keys(o.body).slice(0,5):[];t.push(this.createError(J.EntityNotFound,`Resource not found: ${r.resourceName} in ${n}`,e,s.length>0?`Available resources: ${s.join(", ")}`:void 0))}}async resolveDeepLink(e,t){let r=e.parsedUri,n=r.namespace_,o=await this.repository.getDocumentAsync(n);if(!o){t.push(this.createError(J.PackageNotFound,`Package not found: ${n}`,e));return}if(!o.body||!o.body[r.resourceName]){t.push(this.createError(J.EntityNotFound,`Resource not found: ${r.resourceName} in ${n}`,e));return}let s=o.body[r.resourceName],a=r.resourceName;for(let c of r.path){if(s==null){t.push(this.createError(J.PathNotFound,`Path not found: ${a}`,e));return}if(c.type_===rn.Property){let p=c.name;a+=`.${p}`;let l=Bo(s,p);if(l===void 0){let u=Ho(s);t.push(this.createError(J.PathNotFound,`Path not found: ${a}`,e,u));return}s=l}else if(c.type_===rn.Index){let p=c.index;a+=`[${p}]`;let l=Wo(s,p);if(l===void 0){let u=qo(s);t.push(this.createError(J.IndexOutOfBounds,`Index out of bounds: ${a}`,e,u));return}s=l}}e.isResolved=!0,e.resolvedValue=s}createError(e,t,r,n){return{errorType:e,severity:ie.Error,message:t,reference:r,line:r.line,column:r.column,suggestion:n,toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${ie[this.severity]}: ${this.message} ${o}`.trim()}}}};function Bo(i,e){if(i&&typeof i=="object"&&!Array.isArray(i)){if(e in i)return i[e];let t=Object.keys(i).find(r=>r.toLowerCase()===e.toLowerCase());if(t)return i[t]}}function Wo(i,e){if(Array.isArray(i)&&e>=0&&e<i.length)return i[e]}function Ho(i){if(i&&typeof i=="object"&&!Array.isArray(i)){let e=Object.keys(i).slice(0,5);if(e.length>0)return`Available properties: ${e.join(", ")}`}}function qo(i){if(Array.isArray(i))return i.length>0?`Collection has ${i.length} items (valid indices: 0-${i.length-1})`:"Collection is empty"}import{ResolvedResourceType as Ne}from"@kanonak-protocol/types/ctl/resolution/enums";var Go=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);var Bt=class{repository;constructor(e){if(!e)throw new Error("Repository is required for CTL graph resolution");this.repository=e}async resolveAsync(e,t=1e3){if(!e)throw new Error("Document cannot be null");let r=new Set,n=[],o=[],s=[],a=[],c=new Set;for(let d of e.references)d.parsedUri&&c.add(d.parsedUri.toString());let p=new Map,l=new Map,u=await this.repository.getAllDocumentsAsync();for(let d of u){let g=d.metadata?.namespace_?.toString();if(!g||!d.body)continue;let h=[];for(let[k,R]of Object.entries(d.body))if(R&&typeof R=="object"&&!Array.isArray(R)){let v=this.createMockSubjectKanonak(k,R,g),j=`kanonak://${g}/${k}`;p.has(j)||p.set(j,{entity:v,namespace:g}),h.push(v)}l.set(g,h)}let m=0,y=!1;for(let d of e.references){if(!d.parsedUri){a.push({reference:d.rawUri,reason:d.error??"Failed to parse URI"});continue}let g=d.parsedUri.toString();if(r.has(g))continue;let h=await this.resolveEntityRecursive(g,null,null,0,t,r,c,n,o,s,a,p,l);m=Math.max(m,h),h>=t&&(y=!0)}let f=Zo(e.rawMarkdown);return{sourceFile:e.filePath??null,originalContent:e.rawMarkdown,title:f,directReferences:n,inheritedReferences:o,foundationTypes:s,get totalResourceCount(){return n.length+o.length+s.length},get allResources(){return[...n,...o,...s]},maxDepthReached:m,wasTruncated:y,unresolvedResources:a}}async resolveEntityRecursive(e,t,r,n,o,s,a,c,p,l,u,m,y){if(s.has(e)||(s.add(e),n>=o))return n;if(!t){let R=m.get(e);if(!R)return u.push({reference:e,reason:"Resource not found in workspace"}),n;t=R.entity}let f=t,d=f.namespace??f.namespace_??"";!r&&d&&(r=await this.repository.getDocumentAsync(d));let g=this.createResolvedResource(t,e,n,y);switch(this.classifyTier(e,d,a)){case 0:c.push(g);break;case 2:l.push(g);break;default:p.push(g);break}let k=n;for(let R of g.parentClasses){let v=this.resolveReferenceToUri(R,d,r);if(v&&!s.has(v)){let j=m.get(v),V=await this.resolveEntityRecursive(v,j?.entity??null,null,n+1,o,s,a,c,p,l,u,m,y);k=Math.max(k,V)}}for(let R of g.properties.filter(v=>v.isObjectProperty)){let v=this.resolveReferenceToUri(R.rangeType,d,r);if(v&&!s.has(v)){let j=m.get(v),V=await this.resolveEntityRecursive(v,j?.entity??null,null,n+1,o,s,a,c,p,l,u,m,y);k=Math.max(k,V)}}if(g.instanceOf_){let R=this.resolveReferenceToUri(g.instanceOf_,d,r);if(R&&!s.has(R)){let v=m.get(R),j=await this.resolveEntityRecursive(R,v?.entity??null,null,n+1,o,s,a,c,p,l,u,m,y);k=Math.max(k,j)}}return k}createResolvedResource(e,t,r,n){let o=e,s=o.name??"",a=o.namespace??o.namespace_??"",c=this.classifyEntityType(e),p=nn(e),l=Xo(e),u=Yo(e),m=[];if(c===Ne.Class){let y=n.get(a);y&&(m=Jo(s,y))}return{name:s,kanonakUri:t,resource:e,resourceType:c,parentClass:l.length>0?l[0]:null,parentClasses:l,comment:p,properties:m,namespace_:a,resolutionDepth:r,instanceOf_:u}}classifyEntityType(e){if(I.isClassType(e))return Ne.Class;if(I.isAnnotationPropertyType(e))return Ne.AnnotationProperty;if(I.isDatatypePropertyType(e))return Ne.DatatypeProperty;if(I.isObjectPropertyType(e))return Ne.ObjectProperty;let t=I.getTypeUri(e);return t&&!I.isCoreOntologyType(t)?Ne.Instance:Ne.Other}classifyTier(e,t,r){return r.has(e)?0:zo(t)?2:1}resolveReferenceToUri(e,t,r){if(e.toLowerCase().startsWith("kanonak://"))return e;if(e.includes(".")&&r?.metadata){let n=e.indexOf("."),o=e.substring(0,n),s=e.substring(n+1);if(s){let a=r.metadata.allImports;if(a){for(let c of a)if((c.alias??c.packageName).toLowerCase()===o.toLowerCase())return`kanonak://${c.version?`${c.publisher}/${c.packageName}@${c.version}`:`${c.publisher}/${c.packageName}`}/${s}`}}}return!e.includes(".")&&t?`kanonak://${t}/${e}`:null}createMockSubjectKanonak(e,t,r){let n=[];for(let[o,s]of Object.entries(t))typeof s=="string"?o==="type"||o==="subClassOf"||o==="domain"||o==="range"||o==="subPropertyOf"?n.push({predicate:{subject:{name:o,publisher:"",package_:""}},object:{subject:{name:s,publisher:"",package_:""}}}):n.push({predicate:{subject:{name:o,publisher:"",package_:""}},object:s}):Array.isArray(s)&&n.push({predicate:{subject:{name:o,publisher:"",package_:""}},object:s.map(a=>typeof a=="string"?{subject:{name:a,publisher:"",package_:""}}:a)});return{name:e,namespace_:r,statement:n,entity:t}}};function zo(i){if(!i)return!1;let e=i.split("/");if(e.length<2)return!1;let t=e[0],r=e[1],n=r.includes("@")?r.split("@")[0]:r;return Go.has(`${t}/${n}`)}function nn(i){let e=i;if(e.entity&&typeof e.entity=="object")return e.entity.comment??null;if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="comment"&&typeof t.object=="string")return t.object}return null}function Xo(i){let e=[],t=i,r=t.name??"";if(t.entity&&typeof t.entity=="object"){let n=t.entity.subClassOf;if(typeof n=="string")n.toLowerCase()!==r.toLowerCase()&&e.push(n);else if(Array.isArray(n))for(let o of n){let s=typeof o=="string"?o:o?.subject?.name??o?.name;s&&s.toLowerCase()!==r.toLowerCase()&&e.push(s)}return e}if(t.statement&&Array.isArray(t.statement)){for(let n of t.statement)if(n.predicate?.subject?.name==="subClassOf"){if(n.object?.subject?.name){let o=n.object.subject.name;o.toLowerCase()!==r.toLowerCase()&&e.push(o)}else if(Array.isArray(n.object))for(let o of n.object){let s=o?.subject?.name??o?.name;s&&s.toLowerCase()!==r.toLowerCase()&&e.push(s)}}}return e}function Yo(i){let e=I.getTypeUri(i);return e?I.isCoreOntologyType(e)?null:e.name:null}function Jo(i,e){let t=[];for(let r of e){if(!I.isAnyPropertyType(r))continue;let n=r,o=[],s=[];if(n.entity&&typeof n.entity=="object"){let l=n.entity.domain;if(typeof l=="string")o.push(l);else if(Array.isArray(l))for(let m of l)o.push(typeof m=="string"?m:m?.name??String(m));let u=n.entity.range;if(typeof u=="string")s.push(u);else if(Array.isArray(u))for(let m of u)s.push(typeof m=="string"?m:m?.name??String(m))}if(!o.some(l=>l.toLowerCase()===i.toLowerCase()))continue;s.length===0&&s.push("unknown");let a=I.isObjectPropertyType(r),c=n.entity?.collection!=null,p=nn(r);t.push({name:n.name??"",rangeTypes:s,domains:o,get rangeType(){return s.length>0?s.join(", "):"unknown"},isObjectProperty:a,isCollection:c,comment:p})}return t}function Zo(i){let e=i.split(`
|
|
144
144
|
`);for(let t of e){let r=t.trim();if(r.startsWith("# ")&&!r.startsWith("## "))return r.substring(2).trim()}return null}import{ResolvedResourceType as q}from"@kanonak-protocol/types/ctl/resolution/enums";var Ht=class{resolvedResourceNames=new Set;render(e){if(!e)throw new Error("Graph cannot be null");this.resolvedResourceNames=new Set(e.allResources.map(r=>r.name.toLowerCase()));let t=[];return t.push(this.transformTemplateLinks(e.originalContent)),t.push(""),t.push("---"),t.push(""),t.push("# Kanonak Resource Reference"),t.push(""),this.renderSummary(t,e),this.renderHierarchyDiagram(t,e),this.renderQuickReference(t,e),this.renderTier(t,"Direct References",e.directReferences,"Resources explicitly referenced in this template."),this.renderTier(t,"Inherited References",e.inheritedReferences,"Parent classes, property types, and other dependencies of directly referenced entities."),this.renderTier(t,"Foundation Types",e.foundationTypes,"Core ontology types that form the base of the type hierarchy."),e.unresolvedResources.length>0&&this.renderUnresolved(t,e.unresolvedResources),t.join(`
|
|
145
|
-
`)}generateAnchor(e){return e.toLowerCase()}renderInternalLink(e){return this.resolvedResourceNames.has(e.toLowerCase())?`[${e}](#${this.generateAnchor(e)})`:e}renderInternalLinks(e){return e.map(t=>this.renderInternalLink(t)).join(", ")}transformTemplateLinks(e){let t=/\[([^\]]+)\]\(can:\/\/([^)]+)\)/g;return e.replace(t,(r,n,o)=>{let s;if(o.includes("#"))s=o.substring(o.indexOf("#")+1);else{let a=o.lastIndexOf(".");s=a>=0?o.substring(a+1):o}return this.resolvedResourceNames.has(s.toLowerCase())?`[${n}](#${this.generateAnchor(s)})`:r})}renderSummary(e,t){e.push(`**Total Resources**: ${t.totalResourceCount}`),e.push(`- Direct: ${t.directReferences.length}`),e.push(`- Inherited: ${t.inheritedReferences.length}`),e.push(`- Foundation: ${t.foundationTypes.length}`),t.wasTruncated&&(e.push(""),e.push(`**Resolution was truncated at depth ${t.maxDepthReached}** - some resources may be missing.`),e.push("To include more resources, re-run with a higher depth limit: `kanonak ctl resolve <file> --depth 2000`")),e.push("")}renderQuickReference(e,t){let r=t.allResources;if(r.length===0)return;e.push("## Quick Reference"),e.push("");let n=r.filter(l=>l.resourceType===q.Class),o=r.filter(l=>l.resourceType===q.AnnotationProperty),s=r.filter(l=>l.resourceType===q.DatatypeProperty),a=r.filter(l=>l.resourceType===q.ObjectProperty),c=r.filter(l=>l.resourceType===q.Instance);if(n.length>0){e.push(`### Classes (${n.length})`),e.push(""),e.push("| Class | Extends | Properties |"),e.push("|-------|---------|------------|");for(let l of[...n].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(l.name),m=l.parentClasses.length>0?this.renderInternalLinks(l.parentClasses):"-";e.push(`| ${u} | ${m} | ${l.properties.length} |`)}e.push("")}let p=[...o,...s,...a];if(p.length>0){e.push(`### Properties (${p.length})`),e.push(""),e.push("| Property | Type | Description |"),e.push("|----------|------|-------------|");for(let l of[...p].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(l.name),m=on(l.resourceType),y=Qo(l.comment??"");e.push(`| ${u} | ${m} | ${y} |`)}e.push("")}if(c.length>0){let l=new Map;for(let u of c){let m=u.instanceOf_??"Unknown";l.has(m)||l.set(m,[]),l.get(m).push(u)}e.push("### Resources by Type"),e.push(""),e.push("| Type | Resources |"),e.push("|------|-----------|");for(let[u,m]of[...l.entries()].sort((y,f)=>y[0].localeCompare(f[0]))){let y=this.renderInternalLink(u),f=this.renderInternalLinks(m.map(d=>d.name));e.push(`| ${y} | ${f} |`)}e.push("")}}renderHierarchyDiagram(e,t){let r=t.allResources.filter(a=>a.resourceType===q.Class);if(r.length===0)return;let n=r.filter(a=>a.parentClasses.length>0);if(n.length===0)return;let o=new Set;for(let a of n)for(let c of a.parentClasses)o.add(c.toLowerCase());let s=new Set(r.map(a=>a.name.toLowerCase()));e.push("## Type Hierarchy"),e.push(""),e.push("```mermaid"),e.push("flowchart TB");for(let a of[...r].sort((c,p)=>c.name.localeCompare(p.name))){let c=Wt(a.name);e.push(` ${c}["${a.name}"]`)}for(let a of[...o])if(!s.has(a)){let c=a;for(let l of n)for(let u of l.parentClasses)u.toLowerCase()===a&&(c=u);let p=Wt(c);e.push(` ${p}["${c}"]:::external`)}e.push("");for(let a of n){let c=Wt(a.name);for(let p of a.parentClasses){let l=Wt(p);e.push(` ${l} --> ${c}`)}}e.push(""),e.push(" classDef external fill:#f9f9f9,stroke:#999,stroke-dasharray: 5 5"),e.push("```"),e.push("")}renderTier(e,t,r,n){if(r.length!==0){e.push(`## ${t} (${r.length})`),e.push(""),e.push(`*${n}*`),e.push("");for(let o of[...r].sort((s,a)=>s.name.localeCompare(a.name)))this.renderEntity(e,o)}}renderEntity(e,t){let r=this.generateAnchor(t.name);if(e.push(`### ${t.name}`),e.push(`<a id="${r}"></a>`),e.push(""),e.push("| Attribute | Value |"),e.push("|-----------|-------|"),e.push(`| **URI** | \`${t.kanonakUri}\` |`),e.push(`| **Type** | ${on(t.resourceType)} |`),t.parentClasses.length>0){let n=this.renderInternalLinks(t.parentClasses);e.push(`| **Extends** | ${n} |`)}if(t.instanceOf_){let n=this.renderInternalLink(t.instanceOf_);e.push(`| **Instance of** | ${n} |`)}e.push(""),t.comment&&(e.push(t.comment),e.push("")),t.resourceType===q.Class&&t.properties.length>0&&this.renderPropertiesTable(e,t.properties),e.push("---"),e.push("")}renderPropertiesTable(e,t){e.push("| Property | Type | Description |"),e.push("|----------|------|-------------|");for(let r of[...t].sort((n,o)=>n.name.localeCompare(o.name))){let o=r.rangeTypes.map(a=>{let c=this.renderInternalLink(a);return r.isObjectProperty?`-> ${c}`:c}).join(", ");r.isCollection&&(o=`${o}[]`);let s=(r.comment??"").replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,"");e.push(`| ${r.name} | ${o} | ${s} |`)}e.push("")}renderUnresolved(e,t){e.push(`## Unresolved References (${t.length})`),e.push(""),e.push("*The following references could not be resolved:*"),e.push("");for(let r of t)e.push(`- \`${r.reference}\`: ${r.reason}`);e.push("")}};function on(i){switch(i){case q.Class:return"Class";case q.AnnotationProperty:return"Annotation Property";case q.DatatypeProperty:return"Datatype Property";case q.ObjectProperty:return"Object Property";case q.Instance:return"Instance";default:return"Other"}}function Qo(i){return i?(i=i.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,""),i.length<=50?i:i.substring(0,47)+"..."):""}function Wt(i){return i.replace(/[^a-zA-Z0-9]/g,"_")}import{CtlValidationErrorType as es,CtlValidationSeverity as ts}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as rs,PathSegmentType as ns}from"@kanonak-protocol/types/ctl/parsing/enums";import{ResolvedResourceType as os}from"@kanonak-protocol/types/ctl/resolution/enums";export{Ce as AmbiguousReferenceRule,ee as BooleanStatement,Ve as ClassDefinitionRule,Re as ClassHierarchyCycleRule,Fe as CompositeKanonakDocumentRepository,_t as CredentialStore,Bt as CtlGraphResolver,Te as CtlKanonakUri,rs as CtlKanonakUriType,Ht as CtlMarkdownRenderer,Mt as CtlParser,es as CtlValidationErrorType,ts as CtlValidationSeverity,Ft as CtlValidator,re as DefinedKanonak,De as DefinitionPropertyReferenceRule,Xt as DocumentLocation,Zt as EdgeType,_ as EmbeddedKanonak,ge as EmbeddedKanonakTypeRule,H as EmbeddedStatement,ce as FileSystemKanonakDocumentRepository,bt as GitIgnoreFilter,ht as GraphBuilder,gt as HttpKanonakDocumentRepository,he as ImportExistenceRule,mt as InMemoryKanonakDocumentRepository,Ae as InstancePropertyReferenceRule,z as Kanonak,Je as KanonakDocumentPositions,oe as KanonakObjectParser,St as KanonakObjectValidator,$ as KanonakParser,T as KanonakUri,wt as KanonakUriBuilder,qe as KanonakVocabulary,L as ListStatement,Z as LiteralKanonak,Se as NamespaceImportCycleRule,me as NamespacePrefixRule,Jt as NodeType,Q as NumberStatement,rt as OWL_RL_CLASSIFICATION_RULES,
|
|
145
|
+
`)}generateAnchor(e){return e.toLowerCase()}renderInternalLink(e){return this.resolvedResourceNames.has(e.toLowerCase())?`[${e}](#${this.generateAnchor(e)})`:e}renderInternalLinks(e){return e.map(t=>this.renderInternalLink(t)).join(", ")}transformTemplateLinks(e){let t=/\[([^\]]+)\]\(can:\/\/([^)]+)\)/g;return e.replace(t,(r,n,o)=>{let s;if(o.includes("#"))s=o.substring(o.indexOf("#")+1);else{let a=o.lastIndexOf(".");s=a>=0?o.substring(a+1):o}return this.resolvedResourceNames.has(s.toLowerCase())?`[${n}](#${this.generateAnchor(s)})`:r})}renderSummary(e,t){e.push(`**Total Resources**: ${t.totalResourceCount}`),e.push(`- Direct: ${t.directReferences.length}`),e.push(`- Inherited: ${t.inheritedReferences.length}`),e.push(`- Foundation: ${t.foundationTypes.length}`),t.wasTruncated&&(e.push(""),e.push(`**Resolution was truncated at depth ${t.maxDepthReached}** - some resources may be missing.`),e.push("To include more resources, re-run with a higher depth limit: `kanonak ctl resolve <file> --depth 2000`")),e.push("")}renderQuickReference(e,t){let r=t.allResources;if(r.length===0)return;e.push("## Quick Reference"),e.push("");let n=r.filter(l=>l.resourceType===q.Class),o=r.filter(l=>l.resourceType===q.AnnotationProperty),s=r.filter(l=>l.resourceType===q.DatatypeProperty),a=r.filter(l=>l.resourceType===q.ObjectProperty),c=r.filter(l=>l.resourceType===q.Instance);if(n.length>0){e.push(`### Classes (${n.length})`),e.push(""),e.push("| Class | Extends | Properties |"),e.push("|-------|---------|------------|");for(let l of[...n].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(l.name),m=l.parentClasses.length>0?this.renderInternalLinks(l.parentClasses):"-";e.push(`| ${u} | ${m} | ${l.properties.length} |`)}e.push("")}let p=[...o,...s,...a];if(p.length>0){e.push(`### Properties (${p.length})`),e.push(""),e.push("| Property | Type | Description |"),e.push("|----------|------|-------------|");for(let l of[...p].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(l.name),m=on(l.resourceType),y=Qo(l.comment??"");e.push(`| ${u} | ${m} | ${y} |`)}e.push("")}if(c.length>0){let l=new Map;for(let u of c){let m=u.instanceOf_??"Unknown";l.has(m)||l.set(m,[]),l.get(m).push(u)}e.push("### Resources by Type"),e.push(""),e.push("| Type | Resources |"),e.push("|------|-----------|");for(let[u,m]of[...l.entries()].sort((y,f)=>y[0].localeCompare(f[0]))){let y=this.renderInternalLink(u),f=this.renderInternalLinks(m.map(d=>d.name));e.push(`| ${y} | ${f} |`)}e.push("")}}renderHierarchyDiagram(e,t){let r=t.allResources.filter(a=>a.resourceType===q.Class);if(r.length===0)return;let n=r.filter(a=>a.parentClasses.length>0);if(n.length===0)return;let o=new Set;for(let a of n)for(let c of a.parentClasses)o.add(c.toLowerCase());let s=new Set(r.map(a=>a.name.toLowerCase()));e.push("## Type Hierarchy"),e.push(""),e.push("```mermaid"),e.push("flowchart TB");for(let a of[...r].sort((c,p)=>c.name.localeCompare(p.name))){let c=Wt(a.name);e.push(` ${c}["${a.name}"]`)}for(let a of[...o])if(!s.has(a)){let c=a;for(let l of n)for(let u of l.parentClasses)u.toLowerCase()===a&&(c=u);let p=Wt(c);e.push(` ${p}["${c}"]:::external`)}e.push("");for(let a of n){let c=Wt(a.name);for(let p of a.parentClasses){let l=Wt(p);e.push(` ${l} --> ${c}`)}}e.push(""),e.push(" classDef external fill:#f9f9f9,stroke:#999,stroke-dasharray: 5 5"),e.push("```"),e.push("")}renderTier(e,t,r,n){if(r.length!==0){e.push(`## ${t} (${r.length})`),e.push(""),e.push(`*${n}*`),e.push("");for(let o of[...r].sort((s,a)=>s.name.localeCompare(a.name)))this.renderEntity(e,o)}}renderEntity(e,t){let r=this.generateAnchor(t.name);if(e.push(`### ${t.name}`),e.push(`<a id="${r}"></a>`),e.push(""),e.push("| Attribute | Value |"),e.push("|-----------|-------|"),e.push(`| **URI** | \`${t.kanonakUri}\` |`),e.push(`| **Type** | ${on(t.resourceType)} |`),t.parentClasses.length>0){let n=this.renderInternalLinks(t.parentClasses);e.push(`| **Extends** | ${n} |`)}if(t.instanceOf_){let n=this.renderInternalLink(t.instanceOf_);e.push(`| **Instance of** | ${n} |`)}e.push(""),t.comment&&(e.push(t.comment),e.push("")),t.resourceType===q.Class&&t.properties.length>0&&this.renderPropertiesTable(e,t.properties),e.push("---"),e.push("")}renderPropertiesTable(e,t){e.push("| Property | Type | Description |"),e.push("|----------|------|-------------|");for(let r of[...t].sort((n,o)=>n.name.localeCompare(o.name))){let o=r.rangeTypes.map(a=>{let c=this.renderInternalLink(a);return r.isObjectProperty?`-> ${c}`:c}).join(", ");r.isCollection&&(o=`${o}[]`);let s=(r.comment??"").replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,"");e.push(`| ${r.name} | ${o} | ${s} |`)}e.push("")}renderUnresolved(e,t){e.push(`## Unresolved References (${t.length})`),e.push(""),e.push("*The following references could not be resolved:*"),e.push("");for(let r of t)e.push(`- \`${r.reference}\`: ${r.reason}`);e.push("")}};function on(i){switch(i){case q.Class:return"Class";case q.AnnotationProperty:return"Annotation Property";case q.DatatypeProperty:return"Datatype Property";case q.ObjectProperty:return"Object Property";case q.Instance:return"Instance";default:return"Other"}}function Qo(i){return i?(i=i.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,""),i.length<=50?i:i.substring(0,47)+"..."):""}function Wt(i){return i.replace(/[^a-zA-Z0-9]/g,"_")}import{CtlValidationErrorType as es,CtlValidationSeverity as ts}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as rs,PathSegmentType as ns}from"@kanonak-protocol/types/ctl/parsing/enums";import{ResolvedResourceType as os}from"@kanonak-protocol/types/ctl/resolution/enums";export{Ce as AmbiguousReferenceRule,ee as BooleanStatement,Ve as ClassDefinitionRule,Re as ClassHierarchyCycleRule,Fe as CompositeKanonakDocumentRepository,_t as CredentialStore,Bt as CtlGraphResolver,Te as CtlKanonakUri,rs as CtlKanonakUriType,Ht as CtlMarkdownRenderer,Mt as CtlParser,es as CtlValidationErrorType,ts as CtlValidationSeverity,Ft as CtlValidator,re as DefinedKanonak,De as DefinitionPropertyReferenceRule,Xt as DocumentLocation,Zt as EdgeType,_ as EmbeddedKanonak,ge as EmbeddedKanonakTypeRule,H as EmbeddedStatement,ce as FileSystemKanonakDocumentRepository,bt as GitIgnoreFilter,ht as GraphBuilder,gt as HttpKanonakDocumentRepository,he as ImportExistenceRule,mt as InMemoryKanonakDocumentRepository,Ae as InstancePropertyReferenceRule,z as Kanonak,Je as KanonakDocumentPositions,oe as KanonakObjectParser,St as KanonakObjectValidator,$ as KanonakParser,T as KanonakUri,wt as KanonakUriBuilder,qe as KanonakVocabulary,L as ListStatement,Z as LiteralKanonak,Se as NamespaceImportCycleRule,me as NamespacePrefixRule,Jt as NodeType,Q as NumberStatement,rt as OWL_RL_CLASSIFICATION_RULES,xe as ObjectPropertyImportRule,je as ObjectPropertyValueValidationRule,b as OntologyValidationError,ue as OntologyValidationResult,ns as PathSegmentType,Ee as PropertyDomainRule,ve as PropertyHierarchyCycleRule,vt as PropertyMetadata,$e as PropertyRangeReferenceRule,Pe as PropertyRangeRequiredRule,fe as PropertyTypeSpecificityRule,Oe as PropertyValueTypeRule,Be as PublisherConfigResolver,pe as PublisherIndex,tt as RDFS_RULES,kt as Reasoner,ze as ReasoningResult,w as ReferenceKanonak,U as ReferenceStatement,ft as RepositoryFactory,os as ResolvedResourceType,ye as ResourceNamingRule,x as ResourceResolver,I as ResourceTypeClassifier,X as ScalarStatement,B as Statement,W as StringStatement,we as SubClassOfReferenceRule,Ie as SubPropertyOfReferenceRule,N as SubjectKanonak,de as SubjectKanonakTypeRequiredRule,He as TripleStore,be as TypeAmbiguityRule,ne as TypeResolver,ke as UnresolvedReferenceRule,It as ValidationContext,P as ValidationSeverity,zm as VersionOperator,Ke as XsdImportRule,F as compareVersions,zr as computeIntegrity,Br as createAuthenticatedFetch,lt as createDPoPProof,zt as createVersion,Jr as findDerivation,Cr as findInstancesByType,Dr as formatKanonakAddress,Gt as formatVersion,Mr as generateDPoPKeyPair,Qe as getGlobalCachePath,At as hasValidToken,Ue as isCompatibleVersion,nt as isExpired,Le as isMajorCompatible,qr as loadLockFile,C as makeUriKey,S as normalizeHost,Ar as parseKanonakAddress,mr as parseVersionString,Sr as parseWithPositions,yr as pickHighestDocument,Gr as saveLockFile,Fr as serverSupportsDPoP,et as tripleKey,We as uriKey,A as uriTriple,_e as versionsEqual};
|