@kanonak-protocol/sdk 1.3.0 → 1.5.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,6 +1,6 @@
1
- var mr=Object.defineProperty;var yr=(l,e)=>()=>(l&&(e=l(l=0)),e);var fr=(l,e)=>{for(var t in e)mr(l,t,{get:e[t],enumerable:!0})};var Nt={};fr(Nt,{KanonakUri:()=>K});var K,Ve=yr(()=>{"use strict";K=class l{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});var Ge=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let r=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===e&&n.metadata?.namespace_?.package_===t&&r.push(n);return r}async getHighestCompatibleVersionAsync(e,t){let r=[];for(let o of this.documents.values())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t.packageName&&o.metadata?.namespace_?.version!==void 0&&r.push(o);if(r.length===0)return null;let n=r.filter(o=>{let s=o.metadata.namespace_.version;if(!s)return!1;switch(t.versionOperator){case 0:return this.versionsEqual(s,t.version);case 1:return this.isCompatibleVersion(s,t.version);case 2:return this.isMajorCompatible(s,t.version);case 3:return this.compareVersions(s,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((o,s)=>{let a=o.metadata.namespace_.version,i=s.metadata.namespace_.version;return!a&&!i?0:a?i?this.compareVersions(i,a):-1:1}),n[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let r=this.parser.save(e);this.documentContents.set(t,r)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let r=[];for(let[n,o]of this.documents.entries())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t&&r.push(n);for(let n of r)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let r=this.documents.get(e);return r!==void 0?this.parser.save(r):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}};import*as D from"fs/promises";import*as C from"path";import*as ze from"js-yaml";var E=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=ze.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),ze.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===s&&i.package_===o&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let c=0;c<s.length;c++)i=(i<<5)-i+s.charCodeAt(c);for(let c=0;c<o.length;c++)i=(i<<5)-i+o.charCodeAt(c);return i|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let i=0;i<o[1].length;i++)a=(a<<5)-a+o[1].charCodeAt(i);for(let i=0;i<o[2].length;i++)a=(a<<5)-a+o[2].charCodeAt(i);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),i=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:c,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let p=i[1].trim(),u=i[2],m=this.parseVersion(i[3].trim()),y=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:m,alias:y,minVersion:m,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:m.toString()};return y&&(g.alias=y),g},toString:()=>`${p} ${u} ${m.toString()} as ${y}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),u=c[2],m=this.parseVersion(c[3].trim()),y=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:m.toString()}),toString:()=>`${p} ${u} ${m.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let i={package:o,match:s,version:n.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],i={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(i.alias=s.alias),i})};t.push(o)}return t}};var q=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=C.resolve(e),this.recursive=t,this.parser=r??new E,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let r=C.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=C.join(this.rootPath,o);if(t=this.documentCache.get(s),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values());return Array.from(r).filter(n=>n.metadata.namespace_?.publisher===e&&n.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values()),n=Array.from(r).filter(s=>s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0);if(n.length===0)return null;let o=n.filter(s=>{let a=s.metadata.namespace_.version;switch(t.versionOperator){case 0:return this.versionsEqual(a,t.version);case 1:return this.isCompatibleVersion(a,t.version);case 2:return this.isMajorCompatible(a,t.version);case 3:return this.compareVersions(a,t.minVersion)>=0;default:return!1}});return o.length===0?null:(o.sort((s,a)=>{let i=s.metadata.namespace_.version,c=a.metadata.namespace_.version;return this.compareVersions(c,i)}),o[0])}async saveDocumentAsync(e,t){let r,n=e.metadata.namespace_?.toString();if(n&&n.includes("@")&&n.includes("/")){let i=n.split("/"),c=i[0],u=i[1].replace("@","@")+".kan.yml";r=C.join(this.rootPath,c,u)}else r=C.join(this.rootPath,t),!r.endsWith(".yml")&&!r.endsWith(".yaml")&&!r.endsWith(".kan.yml")&&(r+=".kan.yml");let o=C.dirname(r);await D.mkdir(o,{recursive:!0});let s=this.parser.save(e);await D.writeFile(r,s,"utf8"),n&&this.documentCache.set(n,e),this.documentCache.set(r,e);let a=C.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 D.unlink(r)}catch{}let n=t.metadata.namespace_?.toString();n&&this.documentCache.delete(n),this.documentCache.delete(e),this.documentCache.delete(r);let o=C.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=C.join(this.rootPath,e);try{let o=await D.readdir(n);for(let s of o)s.includes(t)&&s.endsWith(".kan.yml")&&await D.unlink(C.join(n,s))}catch{}for(let[o]of r)this.documentCache.delete(o)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let r of e){let n=`file://${r}`,o;for(let[i,c]of this.documentCache.entries())if(this.filePathsByIdentifier.get(i)===r&&c.metadata.namespace_){o=c.metadata.namespace_.toString();break}let s=o??C.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 D.access(e),t=e}catch{let r=C.join(this.rootPath,e);try{await D.access(r),t=r}catch{return null}}try{return await D.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await D.access(e),t=e}catch{let r=C.join(this.rootPath,e);try{await D.access(r),t=r}catch{return null}}return`file://${t}`}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await D.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async n=>{try{let o=await D.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=C.relative(this.rootPath,n);if(o&&o.metadata.namespace_){let i=o.metadata.namespace_.toString();this.documentCache.set(i,o),this.documentCache.set(n,o),this.documentCache.set(a,o),this.filePathsByIdentifier.set(i,n),this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n)}else this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n);s&&this.parsingErrors.set(n,s)}}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}async findYamlFiles(e,t){let r=[];try{let n=await D.readdir(e,{withFileTypes:!0});for(let o of n){let s=C.join(e,o.name);if(o.isDirectory()&&t){let a=await this.findYamlFiles(s,t);r.push(...a)}else o.isFile()&&o.name.endsWith(".kan.yml")&&r.push(s)}}catch{}return r}};import*as Se from"fs";var wt=(r=>(r.NotFound="NotFound",r.Workspace="Workspace",r.Cache="Cache",r))(wt||{}),je=class{cache;workspace;constructor(e,t,r){let n=r??new E;Se.existsSync(e)||Se.mkdirSync(e,{recursive:!0}),Se.existsSync(t)||Se.mkdirSync(t,{recursive:!0}),this.cache=new q(e,!0,n),this.workspace=new q(t,!0,n)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),r=new Map;for(let n of t)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}for(let n of e)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}return Array.from(r.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let r=await this.workspace.getDocumentsByNamespaceAsync(e,t),n=await this.cache.getDocumentsByNamespaceAsync(e,t),o=new Map;for(let s of n)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}for(let s of r)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}return Array.from(o.values())}async getHighestCompatibleVersionAsync(e,t){let r=await this.workspace.getHighestCompatibleVersionAsync(e,t);return r||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),r=[];return r.push(...e),r.push(...t),r}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as dr}from"os";import{join as gr}from"path";function Te(){let l=process.env.KANONAK_PACKAGE_CACHE;return l||gr(dr(),".kanonak","packages")}var qe=class l{static createComposite(e,t,r){let n=e??Te(),o=t??".";return new je(n,o,r)}static createFromEnvironment(e){let t=Te(),r=process.env.KANONAK_WORKSPACE_PATH??".";return l.createComposite(t,r,e)}};import{VersionOperator as Xe}from"@kanonak-protocol/types/document/models/enums";var hr="https://{publisher}/index.txt",kr="https://{publisher}/{package}/{version}.kan.yml",Ot={version:1},Ee=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let r=await this.fetchConfig(e);return this.cache.set(e,r),r}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await fetch(t)}catch{return Ot}if(r.status===404)return Ot;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${t} (${r.status} ${r.statusText})`);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let o={version:n.version};return typeof n.index=="string"&&(o.index=n.index),typeof n.package=="string"&&(o.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(o.auth=n.auth),o}resolveIndexUrl(e,t){let r=t.index??hr;return Tt(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??kr;return Tt(o,{publisher:e,package:t,version:r})}};function Tt(l,e){let t=l;for(let[n,o]of Object.entries(e))t=t.replaceAll(`{${n}}`,o);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${l}`);return t}var X=class l{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Ee,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(o=>this.isVersionCompatible(o,t.version,t.versionOperator));return n.length===0?null:(n.sort((o,s)=>this.compareVersionStrings(s,o)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((o,s)=>this.compareVersionStrings(s,o))[0]}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let o=await n.text();return l.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
2
- `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("/");if(o===-1)continue;let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)continue;let i=t.get(s);i?i.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=l.parseVersion(e);if(!n)return!1;switch(r){case Xe.Any:return!0;case Xe.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case Xe.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case Xe.Major:return n.major!==t.major?!1:n.minor>t.minor?!0:n.minor===t.minor?n.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let r=parseInt(t[0],10),n=parseInt(t[1],10),o=t.length>=3?parseInt(t[2],10):0;return isNaN(r)||isNaN(n)||isNaN(o)?null:{major:r,minor:n,patch:o}}compareVersionStrings(e,t){let r=l.parseVersion(e),n=l.parseVersion(t);return!r&&!n?0:r?n?r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch:1:-1}};var Ye=class{parser=new E;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new X({fetchFn:e.fetchFn}):new X}async getHighestCompatibleVersionAsync(e,t){let r=await this.publisherIndex.resolveVersion(e,t);if(!r)return null;let n=`${e}/${t.packageName}@${r}`,o=this.documents.get(n);if(o)return o;if(this.getFromCache){let p=this.getFromCache(e,t.packageName,r);if(p){let u=this.parser.parse(p);return this.documents.set(n,u),this.contentCache.set(n,p),u}}let s=await this.publisherIndex.getPackageUrl(e,t.packageName,r),a=this.fetchFn?await this.fetchFn(s,e):await fetch(s);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${s} (${a.status} ${a.statusText})`);let i=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,i);let c=this.parser.parse(i);return this.documents.set(n,c),this.contentCache.set(n,i),c}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,o]=t;return this.publisherIndex.getPackageUrl(r,n,o)}};var F=class{};var U=class extends F{statement=[]};var L=class extends U{namespace;name;icon};var B=class extends U{};Ve();var A=class l extends F{subject;static parse(e){let t=new l;return t.subject=K.parse(e),t}};var x=class{predicate;object};var T=class extends x{};var Y=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var J=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var Z=class extends T{};var Q=class l extends x{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=A.parse(t),r}};var ee=class extends x{};var te=class extends x{};Ve();function S(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var V=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:i,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((i,c)=>i+c.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[i,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[i,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(i,{entityName:i,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(c,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,t,s),f=0;for(let[d,g]of y.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=S(s);for(let i of a)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=S(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var W=class l{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&l.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return l.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Ke=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new V(e),o=new W(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new L;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,i]of Object.entries(e))try{let c=await this.getPropertyMetadata(a,t,r,o);if(!c)continue;let p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}catch(c){console.error(`Error parsing property ${a}:`,c)}return s}async getPropertyMetadata(e,t,r,n){let o=await r.resolveEntityAsync(e,t);if(!o)return;let s=o.entity,i=(s.type?.toString()??"")==="ObjectProperty"?"ObjectProperty":"DatatypeProperty",c=s.range?.toString();return{propertyUri:o.uri.toString(),propertyType:i,range:c,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(typeof t=="string")return Y.parse(e,t);if(typeof t=="number")return J.parse(e,t);if(typeof t=="boolean"){let n=new Z;return n.predicate=A.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let i=new Q;return i.predicate=A.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new B;a.statement=await this.parseStatements(t,n,o,s,{});let i=new ee;return i.predicate=A.parse(e),i.object=a,i}}async parseListValue(e,t,r,n,o,s){let a=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,n,o);p&&a.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new B;p.statement=await this.parseStatements(c,n,o,s,{}),a.push(p)}let i=new te;return i.predicate=A.parse(e),i.object=a,i}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new A;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(Ve(),Nt)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[m,y]of Object.entries(t.metadata.imports))for(let f of y)if((f.alias??f.packageName)===p){let g=new A;return g.subject=new s(m,f.packageName,u,f.version),g}}}let i=new A;return i.subject=new s(o.publisher,o.package_,e,a),i}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof L&&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 L&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new E().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let i of s.statement){let[c,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof Y)return[e.predicate.subject.name,e.object];if(e instanceof J)return[e.predicate.subject.name,e.object];if(e instanceof Z)return[e.predicate.subject.name,e.object];if(e instanceof Q)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof te){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof ee){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof A?t.push(r.subject.name):r instanceof B&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var br=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),_t={Class:{publisher:"kanonak.org",package_:"core-owl"},ObjectProperty:{publisher:"kanonak.org",package_:"core-owl"},DatatypeProperty:{publisher:"kanonak.org",package_:"core-owl"},AnnotationProperty:{publisher:"kanonak.org",package_:"core-owl"},Property:{publisher:"kanonak.org",package_:"core-rdf"},Datatype:{publisher:"kanonak.org",package_:"core-rdfs"},Resource:{publisher:"kanonak.org",package_:"core-rdfs"},Literal:{publisher:"kanonak.org",package_:"core-rdfs"},Thing:{publisher:"kanonak.org",package_:"core-owl"},Nothing:{publisher:"kanonak.org",package_:"core-owl"}};function N(l){let e=l;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=_t[t];return r?{publisher:r.publisher,package_:r.package_,name:t}:{publisher:"",package_:"",name:t}}}if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t.object?.subject){let r=t.object.subject;if(!r.publisher&&!r.package_||r.publisher===""&&r.package_===""){let n=_t[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function M(l,e){return br.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return N(e)}static isCoreOntologyType(e){return M(e.publisher,e.package_)}static isClassType(e){let t=N(e);return t?M(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=N(e);return t?M(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=N(e);return t?M(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=N(e);return t?M(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=N(e);return t?M(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=N(e);return t?M(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=N(e);return!t||!M(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=N(e);return!t||!M(t.publisher,t.package_)?!1:t.name==="Class"||t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"||t.name==="Datatype"}static isInstanceOfKnownClass(e,t){if(l.isSchemaDefinitionType(e))return!1;let r=N(e);return r?t.has(r.name):!1}};var At=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(At||{}),Ct=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(Ct||{}),Je=class{static async buildFromRepository(e){let r=await new Ke().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,i=new Set,c=new Map;for(let u of r){let m=u;m.name&&(w.isClassType(m)&&a.add(m.name),(w.isObjectPropertyType(m)||w.isGenericPropertyType(m))&&i.add(m.name))}for(let u of n)for(let[m,y]of Object.entries(u.body))i.has(m)&&y?.range&&typeof y.range=="string"&&c.set(m,y.range);let p=new Map;for(let u of r){let m=u;m.name&&p.set(m.name,m)}for(let u of n){let m=u.metadata.namespace_,y=m?`${m.publisher}/${m.package_}`:"",f=m?.version?`${m.version.major}.${m.version.minor}.${m.version.patch}`:"",d=Mt(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=p.get(g),R="Unknown";if(b){let j=b;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,$={};for(let[j,Pt]of Object.entries(h))j!=="type"&&(typeof Pt!="object"||Pt===null)&&($[j]=Pt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:$}),Ft(v,h,R,a,i,s,y,f,d),It(v,h,i,c,o,s,y,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,i=new Set,c=new Map,p=Mt(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(vr(d,p)&&a.add(y),Pr(d,p)&&(i.add(y),f.range&&typeof f.range=="string"&&c.set(y,f.range)))}for(let[y,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=wr(d,y,a,p),h=s&&o?`${s}/${y}@${o}`:y,b={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(b[R]=v);t.push({id:h,label:f.label??y,type:g,namespace:s,properties:b}),Ft(h,f,g,a,i,r,s,o,p),It(h,f,i,c,t,r,s,o,p)}let u=new Set(t.map(y=>y.id)),m=r.filter(y=>u.has(y.source)&&u.has(y.target));return{nodes:t,edges:m}}};function Mt(l,e){let t=new Map;if(l.metadata?.imports)for(let[r,n]of Object.entries(l.metadata.imports))for(let o of n){let s=o.alias??o.packageName,a=o.version,i=`${a.major}.${a.minor}.${a.patch}`;t.set(s,{publisher:r,package_:o.packageName,version:i})}return t}var Ut={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},Rr=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Dt(l,e){if(l.includes(".")){let t=l.indexOf("."),r=l.substring(0,t),n=l.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function vr(l,e){let t=Dt(l,e);return t?Ut[t]==="Class":!1}function Pr(l,e){let t=Dt(l,e);return t?Rr.has(t):!1}function wr(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=Dt(l,r);if(n){let s=Ut[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=l.split(".").pop()??l;return t.has(o)?"Instance":"Unknown"}var Lt=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Ft(l,e,t,r,n,o,s,a,i){let c=e.type,p=e.subClassOf;if(p){let f=Array.isArray(p)?p:[p];for(let d of f)typeof d=="string"&&o.push({source:l,target:H(d,s,a,i),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let f=Array.isArray(u)?u:[u];for(let d of f)typeof d=="string"&&o.push({source:l,target:H(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:H(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Lt.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&Ir(h)&&o.push({source:l,target:H(h,s,a,i),type:"propertyValue",label:f,propertyId:H(f,s,a,i)})}let m=t==="ObjectProperty"||t==="DatatypeProperty",y=e.domain&&e.range;if((m||y)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:H(f,s,a,i),target:H(d,s,a,i),type:"objectRelationship",label:e.label??l.split("/").pop()??"",propertyId:l})}}function It(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(Lt.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,m=`${l}/${c}`,y=r.get(c),f=y?y.split(".").pop()??y:"Unknown",d={};for(let[h,b]of Object.entries(u))(typeof b!="object"||b===null)&&(d[h]=b);n.push({id:m,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:l,target:m,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),y&&o.push({source:m,target:H(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),It(m,u,t,r,n,o,s,a,i)}}function Ir(l){return!(!l||l.includes(" ")||l.includes(`
3
- `)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function H(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${l}@${t}`:l}import Ar from"ignore";import*as Qe from"fs";import*as xe from"path";var Ze=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=xe.join(e,".gitignore");if(Qe.existsSync(t))try{let r=Qe.readFileSync(t,"utf8");this.ignoreInstance=Ar(),this.ignoreInstance.add(r)}catch{this.ignoreInstance=null}else this.ignoreInstance=null}shouldIgnore(e){if(!this.ignoreInstance)return!1;let r=xe.relative(this.basePath,e).split(xe.sep).join("/");return this.ignoreInstance.ignores(r)}};var et=class{propertyUri;propertyType;range;isImported;definedInNamespace};Ve();Ve();var tt=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,r){if(e.includes(".")){let o=e.split("."),s=o[0],a=o[1],i=this.findPackageNameForAlias(r,s);if(i){for(let c of t.values())if(c.entityName===a&&c.uri.package_===i)return c.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new K(e,t,r,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===t||!o.alias&&o.packageName===t)return o.packageName;return null}};async function Wt(l,e){let t=[],r=await l.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[c,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let u=p.type;!u||typeof u!="string"||u!=="Package"&&Cr(u,e)&&t.push({entityName:c,entity:p,documentNamespace:`${s}/${a}@${i}`,publisher:s,package_:a,version:i})}}return t}function Cr(l,e){let t=Bt(l),r=Bt(e);return t===r}function Bt(l){let e=l.lastIndexOf(".");if(e!==-1)return l.substring(e+1);let t=l.lastIndexOf("/");return t!==-1?l.substring(t+1):l}var re=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var rt=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ne=class l{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&l.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=n,c.expectedValue=a,c.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var oe=class l{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(l.RESERVED_WORDS.has(r.toLowerCase())){let o=new k;o.ruleType=this.ruleName,o.severity="Error",o.entityName=r,o.message=`Entity name '${r}' is a reserved word and cannot be used.`,o.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(o);continue}if(!l.VALID_NAME_PATTERN.test(r)){let o;/^\d/.test(r)?o="Entity names must start with a letter, not a number.":r.includes(" ")?o="Entity names cannot contain spaces. Use camelCase or underscores instead.":o="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new k;s.ruleType=this.ruleName,s.severity="Error",s.entityName=r,s.message=`Invalid entity name '${r}'. ${o}`,s.suggestion=o,t.push(s)}n&&typeof n=="object"&&!Array.isArray(n)&&this.validatePropertyNames(r,n,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!l.VALID_PROPERTIES.has(n)&&!l.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var se=class l{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let i=[];if(Array.isArray(a))for(let c of a){let p=c?.toString();p&&p==="Property"&&!r&&i.push(p)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let p=this.getPropertyValue(s,"range"),u=this.determinePropertyType(p),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=c,m.expectedValue=u,m.message=`Invalid property type '${c}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":l.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var ae=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let i=new k;i.ruleType=this.ruleName,i.severity="Error",i.entityName=r,i.propertyName="type",i.message=`Subject Kanonak '${r}' must have a 'type' property.`,i.suggestion=`Add a type statement like:
1
+ var mr=Object.defineProperty;var yr=(l,e)=>()=>(l&&(e=l(l=0)),e);var fr=(l,e)=>{for(var t in e)mr(l,t,{get:e[t],enumerable:!0})};var Nt={};fr(Nt,{KanonakUri:()=>K});var K,Ve=yr(()=>{"use strict";K=class l{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});var Ge=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let r=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===e&&n.metadata?.namespace_?.package_===t&&r.push(n);return r}async getHighestCompatibleVersionAsync(e,t){let r=[];for(let o of this.documents.values())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t.packageName&&o.metadata?.namespace_?.version!==void 0&&r.push(o);if(r.length===0)return null;let n=r.filter(o=>{let s=o.metadata.namespace_.version;if(!s)return!1;switch(t.versionOperator){case 0:return this.versionsEqual(s,t.version);case 1:return this.isCompatibleVersion(s,t.version);case 2:return this.isMajorCompatible(s,t.version);case 3:return this.compareVersions(s,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((o,s)=>{let a=o.metadata.namespace_.version,i=s.metadata.namespace_.version;return!a&&!i?0:a?i?this.compareVersions(i,a):-1:1}),n[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let r=this.parser.save(e);this.documentContents.set(t,r)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let r=[];for(let[n,o]of this.documents.entries())o.metadata?.namespace_?.publisher===e&&o.metadata?.namespace_?.package_===t&&r.push(n);for(let n of r)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let r=this.documents.get(e);return r!==void 0?this.parser.save(r):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}};import*as C from"fs/promises";import*as D from"path";import*as ze from"js-yaml";var E=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=ze.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),ze.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===s&&i.package_===o&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let c=0;c<s.length;c++)i=(i<<5)-i+s.charCodeAt(c);for(let c=0;c<o.length;c++)i=(i<<5)-i+o.charCodeAt(c);return i|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let i=0;i<o[1].length;i++)a=(a<<5)-a+o[1].charCodeAt(i);for(let i=0;i<o[2].length;i++)a=(a<<5)-a+o[2].charCodeAt(i);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),i=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:c,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let p=i[1].trim(),u=i[2],m=this.parseVersion(i[3].trim()),y=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:m,alias:y,minVersion:m,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:m.toString()};return y&&(g.alias=y),g},toString:()=>`${p} ${u} ${m.toString()} as ${y}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),u=c[2],m=this.parseVersion(c[3].trim()),y=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,m);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:m,alias:void 0,minVersion:m,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:m.toString()}),toString:()=>`${p} ${u} ${m.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let i={package:o,match:s,version:n.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],i={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(i.alias=s.alias),i})};t.push(o)}return t}};var Y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,r){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=D.resolve(e),this.recursive=t,this.parser=r??new E,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let r=D.join(this.rootPath,e);if(t=this.documentCache.get(r),t)return t;for(let n of[".kan.yml",".yml",".yaml"])if(!e.endsWith(n)){let o=e+n;if(t=this.documentCache.get(o),t)return t;let s=D.join(this.rootPath,o);if(t=this.documentCache.get(s),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values());return Array.from(r).filter(n=>n.metadata.namespace_?.publisher===e&&n.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let r=new Set(this.documentCache.values()),n=Array.from(r).filter(s=>s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0);if(n.length===0)return null;let o=n.filter(s=>{let a=s.metadata.namespace_.version;switch(t.versionOperator){case 0:return this.versionsEqual(a,t.version);case 1:return this.isCompatibleVersion(a,t.version);case 2:return this.isMajorCompatible(a,t.version);case 3:return this.compareVersions(a,t.minVersion)>=0;default:return!1}});return o.length===0?null:(o.sort((s,a)=>{let i=s.metadata.namespace_.version,c=a.metadata.namespace_.version;return this.compareVersions(c,i)}),o[0])}async saveDocumentAsync(e,t){let r,n=e.metadata.namespace_?.toString();if(n&&n.includes("@")&&n.includes("/")){let i=n.split("/"),c=i[0],u=i[1].replace("@","@")+".kan.yml";r=D.join(this.rootPath,c,u)}else r=D.join(this.rootPath,t),!r.endsWith(".yml")&&!r.endsWith(".yaml")&&!r.endsWith(".kan.yml")&&(r+=".kan.yml");let o=D.dirname(r);await C.mkdir(o,{recursive:!0});let s=this.parser.save(e);await C.writeFile(r,s,"utf8"),n&&this.documentCache.set(n,e),this.documentCache.set(r,e);let a=D.relative(this.rootPath,r);this.documentCache.set(a,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let r=this.filePathsByIdentifier.get(e);if(!r)return;try{await C.unlink(r)}catch{}let n=t.metadata.namespace_?.toString();n&&this.documentCache.delete(n),this.documentCache.delete(e),this.documentCache.delete(r);let o=D.relative(this.rootPath,r);this.documentCache.delete(o)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let r=[];for(let[o,s]of this.documentCache.entries()){let a=s.metadata.namespace_?.toString()||"";a.includes(e)&&a.includes(t)&&r.push([o,s])}let n=D.join(this.rootPath,e);try{let o=await C.readdir(n);for(let s of o)s.includes(t)&&s.endsWith(".kan.yml")&&await C.unlink(D.join(n,s))}catch{}for(let[o]of r)this.documentCache.delete(o)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let r of e){let n=`file://${r}`,o;for(let[i,c]of this.documentCache.entries())if(this.filePathsByIdentifier.get(i)===r&&c.metadata.namespace_){o=c.metadata.namespace_.toString();break}let s=o??D.relative(this.rootPath,r),a=this.parsingErrors.has(r);t.push({identifier:s,uri:n,hasParseError:a})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await C.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await C.access(r),t=r}catch{return null}}try{return await C.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await C.access(e),t=e}catch{let r=D.join(this.rootPath,e);try{await C.access(r),t=r}catch{return null}}return`file://${t}`}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await C.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async n=>{try{let o=await C.readFile(n,"utf8"),s=this.parser.parse(o);return{filePath:n,document:s,error:null}}catch(o){return{filePath:n,document:null,error:o instanceof Error?o.message:String(o)}}}),r=await Promise.all(t);for(let{filePath:n,document:o,error:s}of r){let a=D.relative(this.rootPath,n);if(o&&o.metadata.namespace_){let i=o.metadata.namespace_.toString();this.documentCache.set(i,o),this.documentCache.set(n,o),this.documentCache.set(a,o),this.filePathsByIdentifier.set(i,n),this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n)}else this.filePathsByIdentifier.set(n,n),this.filePathsByIdentifier.set(a,n);s&&this.parsingErrors.set(n,s)}}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}async findYamlFiles(e,t){let r=[];try{let n=await C.readdir(e,{withFileTypes:!0});for(let o of n){let s=D.join(e,o.name);if(o.isDirectory()&&t){let a=await this.findYamlFiles(s,t);r.push(...a)}else o.isFile()&&o.name.endsWith(".kan.yml")&&r.push(s)}}catch{}return r}};import*as Se from"fs";var wt=(r=>(r.NotFound="NotFound",r.Workspace="Workspace",r.Cache="Cache",r))(wt||{}),je=class{cache;workspace;constructor(e,t,r){let n=r??new E;Se.existsSync(e)||Se.mkdirSync(e,{recursive:!0}),Se.existsSync(t)||Se.mkdirSync(t,{recursive:!0}),this.cache=new Y(e,!0,n),this.workspace=new Y(t,!0,n)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),r=new Map;for(let n of t)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}for(let n of e)if(n.metadata.namespace_){let o=n.metadata.namespace_.toString();r.set(o,n)}return Array.from(r.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let r=await this.workspace.getDocumentsByNamespaceAsync(e,t),n=await this.cache.getDocumentsByNamespaceAsync(e,t),o=new Map;for(let s of n)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}for(let s of r)if(s.metadata.namespace_?.version){let a=s.metadata.namespace_.version.toString();o.set(a,s)}return Array.from(o.values())}async getHighestCompatibleVersionAsync(e,t){let r=await this.workspace.getHighestCompatibleVersionAsync(e,t);return r||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),r=[];return r.push(...e),r.push(...t),r}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as dr}from"os";import{join as gr}from"path";function Te(){let l=process.env.KANONAK_PACKAGE_CACHE;return l||gr(dr(),".kanonak","packages")}var qe=class l{static createComposite(e,t,r){let n=e??Te(),o=t??".";return new je(n,o,r)}static createFromEnvironment(e){let t=Te(),r=process.env.KANONAK_WORKSPACE_PATH??".";return l.createComposite(t,r,e)}};import{VersionOperator as Xe}from"@kanonak-protocol/types/document/models/enums";var hr="https://{publisher}/index.txt",kr="https://{publisher}/{package}/{version}.kan.yml",Ot={version:1},Ee=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let r=await this.fetchConfig(e);return this.cache.set(e,r),r}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await fetch(t)}catch{return Ot}if(r.status===404)return Ot;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${t} (${r.status} ${r.statusText})`);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let o={version:n.version};return typeof n.index=="string"&&(o.index=n.index),typeof n.package=="string"&&(o.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(o.auth=n.auth),o}resolveIndexUrl(e,t){let r=t.index??hr;return Tt(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??kr;return Tt(o,{publisher:e,package:t,version:r})}};function Tt(l,e){let t=l;for(let[n,o]of Object.entries(e))t=t.replaceAll(`{${n}}`,o);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${l}`);return t}var J=class l{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Ee,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(o=>this.isVersionCompatible(o,t.version,t.versionOperator));return n.length===0?null:(n.sort((o,s)=>this.compareVersionStrings(s,o)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((o,s)=>this.compareVersionStrings(s,o))[0]}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let o=await n.text();return l.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
2
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("/");if(o===-1)continue;let s=n.substring(0,o),a=n.substring(o+1);if(!s||!a)continue;let i=t.get(s);i?i.push(a):t.set(s,[a])}return t}isVersionCompatible(e,t,r){let n=l.parseVersion(e);if(!n)return!1;switch(r){case Xe.Any:return!0;case Xe.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case Xe.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case Xe.Major:return n.major!==t.major?!1:n.minor>t.minor?!0:n.minor===t.minor?n.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let r=parseInt(t[0],10),n=parseInt(t[1],10),o=t.length>=3?parseInt(t[2],10):0;return isNaN(r)||isNaN(n)||isNaN(o)?null:{major:r,minor:n,patch:o}}compareVersionStrings(e,t){let r=l.parseVersion(e),n=l.parseVersion(t);return!r&&!n?0:r?n?r.major!==n.major?r.major-n.major:r.minor!==n.minor?r.minor-n.minor:r.patch-n.patch:1:-1}};var Ye=class{parser=new E;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new J({fetchFn:e.fetchFn}):new J}async getHighestCompatibleVersionAsync(e,t){let r=await this.publisherIndex.resolveVersion(e,t);if(!r)return null;let n=`${e}/${t.packageName}@${r}`,o=this.documents.get(n);if(o)return o;if(this.getFromCache){let p=this.getFromCache(e,t.packageName,r);if(p){let u=this.parser.parse(p);return this.documents.set(n,u),this.contentCache.set(n,p),u}}let s=await this.publisherIndex.getPackageUrl(e,t.packageName,r),a=this.fetchFn?await this.fetchFn(s,e):await fetch(s);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${s} (${a.status} ${a.statusText})`);let i=await a.text();this.onFetch&&this.onFetch(e,t.packageName,r,i);let c=this.parser.parse(i);return this.documents.set(n,c),this.contentCache.set(n,i),c}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,o]=t;return this.publisherIndex.getPackageUrl(r,n,o)}};var L=class{};var U=class extends L{statement=[]};var B=class extends U{namespace;name;icon};var M=class extends U{};Ve();var A=class l extends L{subject;static parse(e){let t=new l;return t.subject=K.parse(e),t}};var x=class{predicate;object};var T=class extends x{};var Z=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var Q=class l extends T{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=t,r}};var ee=class extends T{};var te=class l extends x{static parse(e,t){let r=new l;return r.predicate=A.parse(e),r.object=A.parse(t),r}};var W=class extends x{};var H=class extends x{};Ve();function S(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var V=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:i,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((i,c)=>i+c.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[i,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(u){let m=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[i,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(i,{entityName:i,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(c,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let y=await this.buildEntityIndexAsyncInternal(m,t,s),f=0;for(let[d,g]of y.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(m){let y=m;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=S(s);for(let i of a)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=S(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var G=class l{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&l.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return l.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Ke=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new V(e),o=new G(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new B;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,i]of Object.entries(e))try{let c=await this.getPropertyMetadata(a,t,r,o,n);if(!c)continue;let p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}catch(c){console.error(`Error parsing property ${a}:`,c)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,i=a.type?.toString()??"",c=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let u=o.getPropertyTypeClassification(i),m=a.range?.toString(),y;if(u==="ObjectProperty")y="ObjectProperty";else if(u==="DatatypeProperty")y="DatatypeProperty";else{let d=m&&m.includes(".")?m.substring(m.lastIndexOf(".")+1):m??"";(m?o.isKnownXsdDatatypeName(m):!1)||d==="Literal"?y="DatatypeProperty":y="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:y,range:m,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(typeof t=="string")return Z.parse(e,t);if(typeof t=="number")return Q.parse(e,t);if(typeof t=="boolean"){let n=new ee;return n.predicate=A.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let i=new te;return i.predicate=A.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new M;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new W;return p.predicate=A.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new M;u.statement=await this.parseStatements(p,n,o,s,{}),i.push(u)}else if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&i.push(u)}if(i.length>0){let p=new H;return p.predicate=A.parse(e),p.object=i,p}let c=new W;return c.predicate=A.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,n,o);p&&a.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new M;p.statement=await this.parseStatements(c,n,o,s,{}),a.push(p)}let i=new H;return i.predicate=A.parse(e),i.object=a,i}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new A;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(Ve(),Nt)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[m,y]of Object.entries(t.metadata.imports))for(let f of y)if((f.alias??f.packageName)===p){let g=new A;return g.subject=new s(m,f.packageName,u,f.version),g}}}let i=new A;return i.subject=new s(o.publisher,o.package_,e,a),i}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof B&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),a=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,a)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof B&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new E().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let i of s.statement){let[c,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof Z)return[e.predicate.subject.name,e.object];if(e instanceof Q)return[e.predicate.subject.name,e.object];if(e instanceof ee)return[e.predicate.subject.name,e.object];if(e instanceof te)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof H){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof W){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof A?t.push(r.subject.name):r instanceof M&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var br=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),_t={Class:{publisher:"kanonak.org",package_:"core-owl"},ObjectProperty:{publisher:"kanonak.org",package_:"core-owl"},DatatypeProperty:{publisher:"kanonak.org",package_:"core-owl"},AnnotationProperty:{publisher:"kanonak.org",package_:"core-owl"},Property:{publisher:"kanonak.org",package_:"core-rdf"},Datatype:{publisher:"kanonak.org",package_:"core-rdfs"},Resource:{publisher:"kanonak.org",package_:"core-rdfs"},Literal:{publisher:"kanonak.org",package_:"core-rdfs"},Thing:{publisher:"kanonak.org",package_:"core-owl"},Nothing:{publisher:"kanonak.org",package_:"core-owl"}};function N(l){let e=l;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=_t[t];return r?{publisher:r.publisher,package_:r.package_,name:t}:{publisher:"",package_:"",name:t}}}if(e.statement&&Array.isArray(e.statement)){for(let t of e.statement)if(t.predicate?.subject?.name==="type"&&t.object?.subject){let r=t.object.subject;if(!r.publisher&&!r.package_||r.publisher===""&&r.package_===""){let n=_t[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function F(l,e){return br.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return N(e)}static isCoreOntologyType(e){return F(e.publisher,e.package_)}static isClassType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=N(e);return t?F(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=N(e);return!t||!F(t.publisher,t.package_)?!1:t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"}static isSchemaDefinitionType(e){let t=N(e);return!t||!F(t.publisher,t.package_)?!1:t.name==="Class"||t.name==="Property"||t.name==="DatatypeProperty"||t.name==="ObjectProperty"||t.name==="AnnotationProperty"||t.name==="Datatype"}static isInstanceOfKnownClass(e,t){if(l.isSchemaDefinitionType(e))return!1;let r=N(e);return r?t.has(r.name):!1}};var At=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(At||{}),Dt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(Dt||{}),Je=class{static async buildFromRepository(e){let r=await new Ke().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,i=new Set,c=new Map;for(let u of r){let m=u;m.name&&(w.isClassType(m)&&a.add(m.name),(w.isObjectPropertyType(m)||w.isGenericPropertyType(m))&&i.add(m.name))}for(let u of n)for(let[m,y]of Object.entries(u.body))i.has(m)&&y?.range&&typeof y.range=="string"&&c.set(m,y.range);let p=new Map;for(let u of r){let m=u;m.name&&p.set(m.name,m)}for(let u of n){let m=u.metadata.namespace_,y=m?`${m.publisher}/${m.package_}`:"",f=m?.version?`${m.version.major}.${m.version.minor}.${m.version.patch}`:"",d=Mt(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let b=p.get(g),R="Unknown";if(b){let j=b;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=y&&f?`${y}/${g}@${f}`:g,$={};for(let[j,Pt]of Object.entries(h))j!=="type"&&(typeof Pt!="object"||Pt===null)&&($[j]=Pt);o.push({id:v,label:h.label??g,type:R,namespace:y,properties:$}),Ft(v,h,R,a,i,s,y,f,d),It(v,h,i,c,o,s,y,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,i=new Set,c=new Map,p=Mt(e);for(let[y,f]of Object.entries(e.body)){let d=f?.type;d&&(vr(d,p)&&a.add(y),Pr(d,p)&&(i.add(y),f.range&&typeof f.range=="string"&&c.set(y,f.range)))}for(let[y,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=wr(d,y,a,p),h=s&&o?`${s}/${y}@${o}`:y,b={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(b[R]=v);t.push({id:h,label:f.label??y,type:g,namespace:s,properties:b}),Ft(h,f,g,a,i,r,s,o,p),It(h,f,i,c,t,r,s,o,p)}let u=new Set(t.map(y=>y.id)),m=r.filter(y=>u.has(y.source)&&u.has(y.target));return{nodes:t,edges:m}}};function Mt(l,e){let t=new Map;if(l.metadata?.imports)for(let[r,n]of Object.entries(l.metadata.imports))for(let o of n){let s=o.alias??o.packageName,a=o.version,i=`${a.major}.${a.minor}.${a.patch}`;t.set(s,{publisher:r,package_:o.packageName,version:i})}return t}var Lt={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},Rr=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function Ct(l,e){if(l.includes(".")){let t=l.indexOf("."),r=l.substring(0,t),n=l.substring(t+1),o=e.get(r);if(o)return`${o.publisher}/${o.package_}/${n}`}return null}function vr(l,e){let t=Ct(l,e);return t?Lt[t]==="Class":!1}function Pr(l,e){let t=Ct(l,e);return t?Rr.has(t):!1}function wr(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=Ct(l,r);if(n){let s=Lt[n];if(s)return s;let a=n.split("/").pop()?.split("@")[0]??"";return t.has(a)?"Instance":"Unknown"}let o=l.split(".").pop()??l;return t.has(o)?"Instance":"Unknown"}var Ut=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Ft(l,e,t,r,n,o,s,a,i){let c=e.type,p=e.subClassOf;if(p){let f=Array.isArray(p)?p:[p];for(let d of f)typeof d=="string"&&o.push({source:l,target:z(d,s,a,i),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let f=Array.isArray(u)?u:[u];for(let d of f)typeof d=="string"&&o.push({source:l,target:z(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:z(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if(Ut.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&Ir(h)&&o.push({source:l,target:z(h,s,a,i),type:"propertyValue",label:f,propertyId:z(f,s,a,i)})}let m=t==="ObjectProperty"||t==="DatatypeProperty",y=e.domain&&e.range;if((m||y)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:z(f,s,a,i),target:z(d,s,a,i),type:"objectRelationship",label:e.label??l.split("/").pop()??"",propertyId:l})}}function It(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(Ut.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,m=`${l}/${c}`,y=r.get(c),f=y?y.split(".").pop()??y:"Unknown",d={};for(let[h,b]of Object.entries(u))(typeof b!="object"||b===null)&&(d[h]=b);n.push({id:m,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:l,target:m,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),y&&o.push({source:m,target:z(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),It(m,u,t,r,n,o,s,a,i)}}function Ir(l){return!(!l||l.includes(" ")||l.includes(`
3
+ `)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function z(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${l}@${t}`:l}import Ar from"ignore";import*as Qe from"fs";import*as xe from"path";var Ze=class{ignoreInstance;basePath;constructor(e){this.basePath=e;let t=xe.join(e,".gitignore");if(Qe.existsSync(t))try{let r=Qe.readFileSync(t,"utf8");this.ignoreInstance=Ar(),this.ignoreInstance.add(r)}catch{this.ignoreInstance=null}else this.ignoreInstance=null}shouldIgnore(e){if(!this.ignoreInstance)return!1;let r=xe.relative(this.basePath,e).split(xe.sep).join("/");return this.ignoreInstance.ignores(r)}};var et=class{propertyUri;propertyType;range;isImported;definedInNamespace};Ve();Ve();var tt=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,r){if(e.includes(".")){let o=e.split("."),s=o[0],a=o[1],i=this.findPackageNameForAlias(r,s);if(i){for(let c of t.values())if(c.entityName===a&&c.uri.package_===i)return c.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,r,n){return new K(e,t,r,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===t||!o.alias&&o.packageName===t)return o.packageName;return null}};async function Wt(l,e){let t=[],r=await l.getAllDocumentsAsync();for(let n of r){let o=n.metadata.namespace_;if(!o)continue;let s=o.publisher,a=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[c,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let u=p.type;!u||typeof u!="string"||u!=="Package"&&Dr(u,e)&&t.push({entityName:c,entity:p,documentNamespace:`${s}/${a}@${i}`,publisher:s,package_:a,version:i})}}return t}function Dr(l,e){let t=Bt(l),r=Bt(e);return t===r}function Bt(l){let e=l.lastIndexOf(".");if(e!==-1)return l.substring(e+1);let t=l.lastIndexOf("/");return t!==-1?l.substring(t+1):l}var re=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var k=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var rt=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ne=class l{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&l.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new k;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=n,c.expectedValue=a,c.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var oe=class l{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(l.RESERVED_WORDS.has(r.toLowerCase())){let o=new k;o.ruleType=this.ruleName,o.severity="Error",o.entityName=r,o.message=`Entity name '${r}' is a reserved word and cannot be used.`,o.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(o);continue}if(!l.VALID_NAME_PATTERN.test(r)){let o;/^\d/.test(r)?o="Entity names must start with a letter, not a number.":r.includes(" ")?o="Entity names cannot contain spaces. Use camelCase or underscores instead.":o="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new k;s.ruleType=this.ruleName,s.severity="Error",s.entityName=r,s.message=`Invalid entity name '${r}'. ${o}`,s.suggestion=o,t.push(s)}n&&typeof n=="object"&&!Array.isArray(n)&&this.validatePropertyNames(r,n,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!l.VALID_PROPERTIES.has(n)&&!l.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new k;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var se=class l{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let i=[];if(Array.isArray(a))for(let c of a){let p=c?.toString();p&&p==="Property"&&!r&&i.push(p)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let p=this.getPropertyValue(s,"range"),u=this.determinePropertyType(p),m=new k;m.ruleType=this.ruleName,m.severity="Error",m.entityName=n,m.propertyName="type",m.actualValue=c,m.expectedValue=u,m.message=`Invalid property type '${c}'. Use '${u}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(m)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":l.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var ae=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let i=new k;i.ruleType=this.ruleName,i.severity="Error",i.entityName=r,i.propertyName="type",i.message=`Subject Kanonak '${r}' must have a 'type' property.`,i.suggestion=`Add a type statement like:
4
4
  type: Scene
5
5
 
6
6
  Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,i.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(i)}}return t}};var ie=class{get ruleName(){return"EmbeddedKanonakNoExplicitType"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&this.checkForEmbeddedTypeViolations(r,n,t,0);return t}checkForEmbeddedTypeViolations(e,t,r,n){for(let[o,s]of Object.entries(t)){let a=o;if(n>0&&a.toLowerCase()==="type"){let i=s?.toString(),c=e.split(".")[0],p=new k;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue="type",p.message=`Embedded object at '${e}' cannot have explicit 'type' property.`,p.suggestion=`Remove the 'type: ${i}' line.
@@ -36,7 +36,7 @@ ${p}`,y.expectedValue="Unambiguous reference (use namespace alias to disambiguat
36
36
  2. Import the namespace that contains '${u}', OR
37
37
  3. Use a qualified reference like 'alias.${u}' if already imported with an alias`:`For DatatypeProperty:
38
38
  1. Use a primitive type (string, integer, boolean, dateTime, etc.), OR
39
- 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 i of a){if(n!==null&&i.alias!==n)continue;let c=await t.getHighestCompatibleVersionAsync(s,i);if(c){let p=n!==null?o:r,u=c.body[p];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(c,t,p,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 i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);if(c){let p=c.body[r];if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p.type?.toString();if(this.isValidRangeTargetType(m))return!0}if(await this.isTypeAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var Pe=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 V(t);await o.buildEntityIndexAsync(e);for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=!1,p=i.type;if(Array.isArray(p)){for(let u of p)if(u?.toString()==="ObjectProperty"){c=!0;break}}else p?.toString()==="ObjectProperty"&&(c=!0);if(c){let u=i.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 c of a){let p=new k;p.ruleType=this.ruleName,p.severity="Warning",p.message=`ObjectProperty references class '${s}' which may not be imported`,p.suggestion=`Ensure the namespace containing '${s}' is imported, or define '${s}' in this document`,p.entityName=c,p.propertyName="range",p.actualValue=s,r.push(p)}return r}};var we=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 V(t),o=new W(n),s=await n.buildEntityIndexAsync(e),a=await this.buildPropertyMetadataAsync(e,t,n,s);for(let[i,c]of Object.entries(e.body))typeof c=="object"&&c!==null&&!Array.isArray(c)&&await this.scanEntityForObjectProperties(c,i,"",a,n,o,e,r);return r}async scanEntityForObjectProperties(e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(this.standardProperties.has(c))continue;let u=c,m=c.lastIndexOf(".");m>0&&m<c.length-1&&(u=c.substring(m+1));let y=n.get(u);if(y&&s.isEffectiveObjectProperty(y.propertyType,y.rangeUri)){let d=r?`${r}.${c}`:c;if(typeof p=="string"&&p.trim().length>0){let g=p.trim();if(g.includes(",")){let b=g.split(",").map(R=>R.trim()).filter(R=>R.length>0);i.push({ruleType:this.ruleName,severity:"Error",message:`Property '${c}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
39
+ 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 i of a){if(n!==null&&i.alias!==n)continue;let c=await t.getHighestCompatibleVersionAsync(s,i);if(c){let p=n!==null?o:r,u=c.body[p];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(c,t,p,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 i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);if(c){let p=c.body[r];if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p.type?.toString();if(this.isValidRangeTargetType(m))return!0}if(await this.isTypeAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var Pe=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 V(t);await o.buildEntityIndexAsync(e);for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=!1,p=i.type;if(Array.isArray(p)){for(let u of p)if(u?.toString()==="ObjectProperty"){c=!0;break}}else p?.toString()==="ObjectProperty"&&(c=!0);if(c){let u=i.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 c of a){let p=new k;p.ruleType=this.ruleName,p.severity="Warning",p.message=`ObjectProperty references class '${s}' which may not be imported`,p.suggestion=`Ensure the namespace containing '${s}' is imported, or define '${s}' in this document`,p.entityName=c,p.propertyName="range",p.actualValue=s,r.push(p)}return r}};var we=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 V(t),o=new G(n),s=await n.buildEntityIndexAsync(e),a=await this.buildPropertyMetadataAsync(e,t,n,s);for(let[i,c]of Object.entries(e.body))typeof c=="object"&&c!==null&&!Array.isArray(c)&&await this.scanEntityForObjectProperties(c,i,"",a,n,o,e,r);return r}async scanEntityForObjectProperties(e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(this.standardProperties.has(c))continue;let u=c,m=c.lastIndexOf(".");m>0&&m<c.length-1&&(u=c.substring(m+1));let y=n.get(u);if(y&&s.isEffectiveObjectProperty(y.propertyType,y.rangeUri)){let d=r?`${r}.${c}`:c;if(typeof p=="string"&&p.trim().length>0){let g=p.trim();if(g.includes(",")){let b=g.split(",").map(R=>R.trim()).filter(R=>R.length>0);i.push({ruleType:this.ruleName,severity:"Error",message:`Property '${c}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
40
40
  ${c}:
41
41
  - ${b[0]}
42
42
  ${b.slice(1).map(R=>` - ${R}`).join(`
@@ -46,7 +46,7 @@ ${b.slice(1).map(R=>` - ${R}`).join(`
46
46
  3. Create a different property for '${r}'`,expectedValue:`Property used on ${m} or its subclasses`})}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let y=i,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(i))for(let y=0;y<i.length;y++){let f=i[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 b=`${t}.${a}[${y}]`;this.validateEntityProperties(d,b,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 i of a){if(i===t)return!0;o.push(i)}}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 Ae=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,i=this.getPropertyValue(a,"type");(i==="DatatypeProperty"||i==="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,i=this.getPropertyValue(a,"type");if(!(!i||i==="Class"||i.endsWith("Property")||i==="AnnotationProperty"))for(let[c,p]of Object.entries(a)){if(c==="type"||c==="label"||c==="comment")continue;let u=c,m=c.lastIndexOf(".");m>0&&m<c.length-1&&(u=c.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 p=="object"&&p!==null&&!Array.isArray(p)||Array.isArray(p))r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:c,message:`Property '${c}' is a DatatypeProperty with range '${d}' but instance '${o}' has a complex object value`,suggestion:`Either:
47
47
  1. Create a class for this data and change '${c}' to an ObjectProperty
48
48
  2. Store as a JSON string to keep it as DatatypeProperty
49
- 3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${d}'`});else if(!this.validateDatatypeValue(d,p)){let g={ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:c,message:`Property '${c}' expects type '${d}' but instance '${o}' has value of type '${this.getValueTypeName(p)}'`,suggestion:`Provide a value of type '${d}'`,toString:()=>""};d&&(g.expectedValue=d),r.push(g)}}else if(f==="ObjectProperty")if(Array.isArray(p))for(let g=0;g<p.length;g++){let h=p[g];typeof h!="string"&&(typeof h!="object"||h===null||Array.isArray(h))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:`${c}[${g}]`,message:`ObjectProperty '${c}' 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 p!="string"&&(typeof p!="object"||p===null||Array.isArray(p))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:c,message:`ObjectProperty '${c}' in instance '${o}' has invalid value type '${this.getValueTypeName(p)}'`,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 Ce=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,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type;if(p)if(Array.isArray(p))for(let u of p){let m=u?.toString();if(m==="Class"||m&&m.endsWith(".Class")){o.add(a);break}}else{let u=p?.toString();(u==="Class"||u&&u.endsWith(".Class"))&&o.add(a)}}for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=i,p=c.type;if(p)if(Array.isArray(p)){let u=!1;for(let m of p){let y=m?.toString();if(y&&this.isDefinitionType(y)){u=!0;break}}if(!u)for(let m of p){let y=m?.toString();y&&y.trim().length>0&&(n.has(y)||n.set(y,[]),n.get(y).push(a))}}else{let u=p?.toString();u&&u.trim().length>0&&(this.isDefinitionType(u)||(n.has(u)||n.set(u,[]),n.get(u).push(a)))}this.checkNestedTypes(c,a,n,a)}let s=new V(t);for(let[a,i]of n){if(this.builtInClasses.has(a)||o.has(a))continue;let c=await s.resolveEntityAsync(a,e);if(!(c&&this.isClassEntity(c.entity))){let u=Array.from(new Set(i)).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 i of s){let c=i?.toString();c&&c.trim().length>0&&!a.has(c)&&(r.has(c)||r.set(c,[]),r.get(c).push(n))}else{let i=s?.toString();i&&i.trim().length>0&&!a.has(i)&&(r.has(i)||r.set(i,[]),r.get(i).push(n))}}for(let[a,i]of Object.entries(o))if(a!=="type"){let c=`${n}.${a}`;this.checkNestedTypes(i,t,r,c)}}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 nt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new E,this.documentRules=[new ne,new oe,new se,new ae,new ie],this.repositoryRules=[new ce,new pe,new le,new ue,new me,new ye,new fe,new de,new ge,new he,new ke,new be,new Re,new ve,new Pe,new we,new Ie,new Ae,new Ce]}async validateAsync(e,t){let r=new re;for(let n of this.documentRules)try{let o=n.validate(e);this.addErrorsToResult(r,o)}catch(o){let s=new k;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 i=o.get(a);i?i.push(s):o.set(a,[s])}for(let[s,a]of o){let i=new k;i.ruleType=a[0],i.severity="Error",a.length===1?i.message=`Validation rule '${a[0]}' failed: ${s}`:i.message=`${s} (affects ${a.length} rules: ${a.join(", ")})`,r.errors.push(i)}}}return r.isValid=r.errors.length===0,r}async validateYamlAsync(e,t){let r=this.parser.parseWithErrors(e);if(!r.isValid){let n=new re;n.isValid=!1;for(let o of r.errors){let s=new k;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)}};function Ne(l){if(!l.expiresAt)return!1;let e=new Date(l.expiresAt),t=300*1e3;return e.getTime()<=Date.now()+t}function ot(l){return!!l.accessToken&&!Ne(l)}function I(l){let e=l.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}import{existsSync as Wr,readFileSync as Hr}from"fs";import{homedir as Gr}from"os";import{join as zr}from"path";import{execFile as Dr}from"child_process";import{promisify as $r}from"util";var st=$r(Dr),at="kanonak",it="/usr/bin/security",_e=class{async get(e){let t=I(e);try{let{stdout:r}=await st(it,["find-generic-password","-s",at,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
49
+ 3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${d}'`});else if(!this.validateDatatypeValue(d,p)){let g={ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:c,message:`Property '${c}' expects type '${d}' but instance '${o}' has value of type '${this.getValueTypeName(p)}'`,suggestion:`Provide a value of type '${d}'`,toString:()=>""};d&&(g.expectedValue=d),r.push(g)}}else if(f==="ObjectProperty")if(Array.isArray(p))for(let g=0;g<p.length;g++){let h=p[g];typeof h!="string"&&(typeof h!="object"||h===null||Array.isArray(h))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:`${c}[${g}]`,message:`ObjectProperty '${c}' 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 p!="string"&&(typeof p!="object"||p===null||Array.isArray(p))&&r.push({ruleType:this.ruleName,severity:"Error",entityName:o,propertyName:c,message:`ObjectProperty '${c}' in instance '${o}' has invalid value type '${this.getValueTypeName(p)}'`,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 De=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,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=i.type;if(p)if(Array.isArray(p))for(let u of p){let m=u?.toString();if(m==="Class"||m&&m.endsWith(".Class")){o.add(a);break}}else{let u=p?.toString();(u==="Class"||u&&u.endsWith(".Class"))&&o.add(a)}}for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=i,p=c.type;if(p)if(Array.isArray(p)){let u=!1;for(let m of p){let y=m?.toString();if(y&&this.isDefinitionType(y)){u=!0;break}}if(!u)for(let m of p){let y=m?.toString();y&&y.trim().length>0&&(n.has(y)||n.set(y,[]),n.get(y).push(a))}}else{let u=p?.toString();u&&u.trim().length>0&&(this.isDefinitionType(u)||(n.has(u)||n.set(u,[]),n.get(u).push(a)))}this.checkNestedTypes(c,a,n,a)}let s=new V(t);for(let[a,i]of n){if(this.builtInClasses.has(a)||o.has(a))continue;let c=await s.resolveEntityAsync(a,e);if(!(c&&this.isClassEntity(c.entity))){let u=Array.from(new Set(i)).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 i of s){let c=i?.toString();c&&c.trim().length>0&&!a.has(c)&&(r.has(c)||r.set(c,[]),r.get(c).push(n))}else{let i=s?.toString();i&&i.trim().length>0&&!a.has(i)&&(r.has(i)||r.set(i,[]),r.get(i).push(n))}}for(let[a,i]of Object.entries(o))if(a!=="type"){let c=`${n}.${a}`;this.checkNestedTypes(i,t,r,c)}}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 nt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new E,this.documentRules=[new ne,new oe,new se,new ae,new ie],this.repositoryRules=[new ce,new pe,new le,new ue,new me,new ye,new fe,new de,new ge,new he,new ke,new be,new Re,new ve,new Pe,new we,new Ie,new Ae,new De]}async validateAsync(e,t){let r=new re;for(let n of this.documentRules)try{let o=n.validate(e);this.addErrorsToResult(r,o)}catch(o){let s=new k;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 i=o.get(a);i?i.push(s):o.set(a,[s])}for(let[s,a]of o){let i=new k;i.ruleType=a[0],i.severity="Error",a.length===1?i.message=`Validation rule '${a[0]}' failed: ${s}`:i.message=`${s} (affects ${a.length} rules: ${a.join(", ")})`,r.errors.push(i)}}}return r.isValid=r.errors.length===0,r}async validateYamlAsync(e,t){let r=this.parser.parseWithErrors(e);if(!r.isValid){let n=new re;n.isValid=!1;for(let o of r.errors){let s=new k;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)}};function Ne(l){if(!l.expiresAt)return!1;let e=new Date(l.expiresAt),t=300*1e3;return e.getTime()<=Date.now()+t}function ot(l){return!!l.accessToken&&!Ne(l)}function I(l){let e=l.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}import{existsSync as Wr,readFileSync as Hr}from"fs";import{homedir as Gr}from"os";import{join as zr}from"path";import{execFile as Cr}from"child_process";import{promisify as $r}from"util";var st=$r(Cr),at="kanonak",it="/usr/bin/security",_e=class{async get(e){let t=I(e);try{let{stdout:r}=await st(it,["find-generic-password","-s",at,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
50
50
  Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(Ht(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${ct(r)}
51
51
  The Keychain may be locked or inaccessible.
52
52
  Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=I(e),n=JSON.stringify(t);try{await st(it,["add-generic-password","-s",at,"-a",r,"-U","-w",n],{timeout:1e4})}catch(o){throw new Error(`macOS Keychain write failed for '${r}': ${ct(o)}
@@ -136,14 +136,14 @@ public class CredMan {
136
136
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
137
137
  }
138
138
  "@`,Vr="";import{execFile as Kr,spawn as xr}from"child_process";import{promisify as Or}from"util";var yt=Or(Kr),mt="kanonak",Fe=class{async get(e){let t=I(e);try{let{stdout:r}=await yt("secret-tool",["lookup","service",mt,"publisher",t],{timeout:1e4}),n=r.trim();return n?JSON.parse(n):null}catch{return null}}async store(e,t){let r=I(e),n=JSON.stringify(t);await new Promise((o,s)=>{let a=xr("secret-tool",["store","--label",`Kanonak: ${r}`,"service",mt,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(n),a.stdin.end(),a.on("close",i=>{i===0?o():s(new Error(`secret-tool store exited with code ${i}`))}),a.on("error",s)})}async remove(e){let t=I(e);try{await yt("secret-tool",["clear","service",mt,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await yt("secret-tool",["search","service",mt],{timeout:1e4}),t=[];for(let r of e.split(`
139
- `)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function $t(){try{return await yt("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Gt,mkdirSync as zt,readFileSync as qt,writeFileSync as Xt}from"fs";import{createCipheriv as Tr,createDecipheriv as Nr,randomBytes as Yt}from"crypto";import{homedir as _r}from"os";import{join as Et,dirname as Jt}from"path";var Qt=Et(_r(),".config","kanonak"),Ue=Et(Qt,"keyring.key"),ft=Et(Qt,"credentials.enc"),Zt="aes-256-gcm",St=32,Oe=12,jt=16,Le=class{async get(e){let t=this.loadStore(),r=I(e);return t[r]??null}async store(e,t){let r=this.loadStore(),n=I(e);r[n]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=I(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Gt(ft))return{};try{let e=this.getOrCreateKey(),t=qt(ft);if(t.length<Oe+jt)return{};let r=t.subarray(0,Oe),n=t.subarray(Oe,Oe+jt),o=t.subarray(Oe+jt),s=Nr(Zt,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=Yt(Oe),n=Tr(Zt,t,r),o=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([n.update(o),n.final()]),a=n.getAuthTag(),i=Buffer.concat([r,a,s]);zt(Jt(ft),{recursive:!0}),Xt(ft,i,{mode:384})}getOrCreateKey(){if(Gt(Ue)){let t=qt(Ue);if(t.length!==St)throw new Error(`Credential keyring key is corrupted (expected ${St} bytes, got ${t.length}). Delete ${Ue} and re-authenticate.`);return t}let e=Yt(St);return zt(Jt(Ue),{recursive:!0}),Xt(Ue,e,{mode:384}),e}};import{execFile as Mr}from"child_process";import{promisify as Fr}from"util";var Ur=Fr(Mr),er=3e4,Be=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=I(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}': ${dt(r)}
139
+ `)){let n=r.match(/attribute\.publisher\s*=\s*(.+)/);n&&t.push(n[1].trim())}return t}catch{return[]}}};async function $t(){try{return await yt("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Gt,mkdirSync as zt,readFileSync as qt,writeFileSync as Xt}from"fs";import{createCipheriv as Tr,createDecipheriv as Nr,randomBytes as Yt}from"crypto";import{homedir as _r}from"os";import{join as Et,dirname as Jt}from"path";var Qt=Et(_r(),".config","kanonak"),Le=Et(Qt,"keyring.key"),ft=Et(Qt,"credentials.enc"),Zt="aes-256-gcm",St=32,Oe=12,jt=16,Ue=class{async get(e){let t=this.loadStore(),r=I(e);return t[r]??null}async store(e,t){let r=this.loadStore(),n=I(e);r[n]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=I(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Gt(ft))return{};try{let e=this.getOrCreateKey(),t=qt(ft);if(t.length<Oe+jt)return{};let r=t.subarray(0,Oe),n=t.subarray(Oe,Oe+jt),o=t.subarray(Oe+jt),s=Nr(Zt,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=Yt(Oe),n=Tr(Zt,t,r),o=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([n.update(o),n.final()]),a=n.getAuthTag(),i=Buffer.concat([r,a,s]);zt(Jt(ft),{recursive:!0}),Xt(ft,i,{mode:384})}getOrCreateKey(){if(Gt(Le)){let t=qt(Le);if(t.length!==St)throw new Error(`Credential keyring key is corrupted (expected ${St} bytes, got ${t.length}). Delete ${Le} and re-authenticate.`);return t}let e=Yt(St);return zt(Jt(Le),{recursive:!0}),Xt(Le,e,{mode:384}),e}};import{execFile as Mr}from"child_process";import{promisify as Fr}from"util";var Lr=Fr(Mr),er=3e4,Be=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=I(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}': ${dt(r)}
140
140
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
141
141
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let r=I(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}': ${dt(n)}
142
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=I(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${dt(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: ${dt(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Ur(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:er});return r}catch(r){throw Lr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
142
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=I(e);try{await this.runHelper("erase",{publisher:t})}catch(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${dt(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: ${dt(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await Lr(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:er});return r}catch(r){throw Ur(r)?new Error(`Credential helper not found at '${this.helperPath}'.
143
143
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Br(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${er/1e3}s on '${e}'.
144
- The helper may be waiting for authentication to an external vault.`):r}}};function dt(l){return l instanceof Error?l.message:String(l)}function Lr(l){return l instanceof Error&&"code"in l&&l.code==="ENOENT"}function Br(l){return l instanceof Error&&"killed"in l&&l.killed}var Vt=zr(Gr(),".kanonak","config.json"),gt=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=qr(e);if(t)return t;let n=await(await this.getBackend()).get(e);return!n||!ot(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=Xr();return e.credentialHelper?new Be(e.credentialHelper):process.platform==="darwin"?new _e:process.platform==="win32"?new Me:await $t()?new Fe:new Le}};function qr(l){let t="KANONAK_TOKEN_"+I(l).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Xr(){if(!Wr(Vt))return{};try{return JSON.parse(Hr(Vt,"utf-8"))}catch(l){let e=l instanceof Error?l.message:String(l);return console.warn(` Warning: Failed to parse ${Vt}: ${e}
144
+ The helper may be waiting for authentication to an external vault.`):r}}};function dt(l){return l instanceof Error?l.message:String(l)}function Ur(l){return l instanceof Error&&"code"in l&&l.code==="ENOENT"}function Br(l){return l instanceof Error&&"killed"in l&&l.killed}var Vt=zr(Gr(),".kanonak","config.json"),gt=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=qr(e);if(t)return t;let n=await(await this.getBackend()).get(e);return!n||!ot(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=Xr();return e.credentialHelper?new Be(e.credentialHelper):process.platform==="darwin"?new _e:process.platform==="win32"?new Me:await $t()?new Fe:new Ue}};function qr(l){let t="KANONAK_TOKEN_"+I(l).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Xr(){if(!Wr(Vt))return{};try{return JSON.parse(Hr(Vt,"utf-8"))}catch(l){let e=l instanceof Error?l.message:String(l);return console.warn(` Warning: Failed to parse ${Vt}: ${e}
145
145
  Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Yr,createPrivateKey as Jr,generateKeyPairSync as Zr,randomUUID as Qr,sign as en}from"crypto";function rr(){let{publicKey:l,privateKey:e}=Zr("ec",{namedCurve:"P-256"});return{publicKey:l.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function We(l,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:Qr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return n&&(a.ath=Yr("sha256").update(n).digest("base64url")),o&&(a.nonce=o),tn(s,a,l)}function nr(l){return!l||l.length===0?!1:l.some(e=>e.toUpperCase()==="ES256")}function tn(l,e,t){let r=tr(JSON.stringify(l)),n=tr(JSON.stringify(e)),o=`${r}.${n}`,s=Jr({key:t,format:"jwk"}),i=en("SHA256",Buffer.from(o),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${o}.${i}`}function tr(l){return Buffer.from(l,"utf-8").toString("base64url")}function or(l){let e=new Map;return async(t,r,n="GET")=>{if(!l)return fetch(t,{method:n});let o=await l.getCredential(r);if(!o?.accessToken)return fetch(t,{method:n});Ne(o)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let s={};if(o.dpopKeyPair){let i=e.get(r);try{let c=We(o.dpopKeyPair.privateKey,o.dpopKeyPair.publicKey,n,t,o.accessToken,i);s.Authorization=`DPoP ${o.accessToken}`,s.DPoP=c}catch(c){let p=c instanceof Error?c.message:String(c);console.error(` Error: Failed to create DPoP proof for '${r}': ${p}
146
- 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 i=a.headers.get("DPoP-Nonce");if(i){e.set(r,i);try{let c=We(o.dpopKeyPair.privateKey,o.dpopKeyPair.publicKey,n,t,o.accessToken,i);s.DPoP=c,a=await fetch(t,{method:n,headers:s})}catch{}}}return a}}import{CtlKanonakUriType as He,PathSegmentType as Kt}from"@kanonak-protocol/types/ctl/parsing/enums";var rn=/\.?([a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\])/g;function nn(l){let e=l.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 De=class l{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?He.DeepLink:this.resourceName!=null?He.Resource:this.version!=null?He.VersionedPackage:this.package_!=null?He.Package:He.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,i=null,c=null,p=o.indexOf("@");if(p>=0){let m=o.substring(0,p),y=o.substring(p+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(c=y.substring(d+1),!g||g.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Version required after '@'`);if(i=nn(g),!c||c.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],c=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(!c||c.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}let u=[];return n!=null&&(u=on(n,e)),new l({publisher:s,package_:a,version:i,resourceName:c,path:u,rawUri:e})}static tryParse(e){try{return l.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_===Kt.Index?e+=`[${r.index}]`:(t||(e+="."),e+=r.name),t=!1}return e}equals(e){return e instanceof l?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 on(l,e){let t=[],r=new RegExp(rn.source,"g"),n=0,o;for(;(o=r.exec(l))!==null;){let s=o[1];if(s.startsWith("[")&&s.endsWith("]")){let a=s.substring(1,s.length-1),i=parseInt(a,10);if(isNaN(i))throw new Error(`Invalid Kanonak URI: '${e}'. Invalid array index: ${s}`);t.push({type_:Kt.Index,index:i,toString:()=>`[${i}]`})}else t.push({type_:Kt.Property,name:s,toString:()=>s});n+=o[0].length}if(n!==l.length)throw new Error(`Invalid Kanonak URI: '${e}'. Invalid path syntax in: ${l}`);return t}import{VersionOperator as G}from"@kanonak-protocol/types/document/models/enums";import*as ir from"js-yaml";var sn=/\[([^\]]+)\]\((kanonak:\/\/[^)]+)\)/gi,an=/\[([^\]]+)\]\(kan:\/\/([^)]+)\)/gi,cn=/```[\s\S]*?```|`[^`]+`/g,pn=/^---\s*\n([\s\S]*?)\n---\s*\n/;function ln(l,e,t){let r=`${l}.${e}.${t}`;return{major:l,minor:e,patch:t,toString:()=>r,equals:n=>n?.major===l&&n?.minor===e&&n?.patch===t,getHashCode:()=>l<<20|e<<10|t,compareTo:n=>l!==n.major?l-n.major:e!==n.minor?e-n.minor:t-n.patch}}function un(l,e,t,r,n){let o=r===G.Compatible?"~":r===G.Major?"^":r===G.Exact?"=":"*",s=`${e} ${o} ${t}`;return{package_:s,publisher:l,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!==G.Exact&&(a.match=o),a},toString(){return s}}}var ht=class{parse(e,t){if(e==null)throw new Error("Content cannot be null");e.charCodeAt(0)===65279&&(e=e.substring(1));let r=pn.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 c=ir.load(n);if(!c)throw new Error("Frontmatter YAML is empty");if(!c.imports||!Array.isArray(c.imports))throw new Error("Frontmatter must contain an 'imports' sequence");let p={};for(let m of c.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`);p[y]||(p[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=ln(g[0]||0,g[1]||0,g[2]||0),b=f.match?.toString(),R=b==="^"?G.Major:b==="~"?G.Compatible:b==="*"?G.Any:G.Exact,v=un(y,f.package?.toString()??"",h,R,f.alias?.toString()??null);p[y].push(v)}}let u=[];for(let m of Object.values(p))u.push(...m);s={namespace_:void 0,imports:p,get allImports(){return u}},a=this.buildAliasMap(p)}catch(c){let p={displayText:"(frontmatter)",rawUri:"",startOffset:0,endOffset:t[0].length,line:1,column:1,isResolved:!1,error:`Failed to parse frontmatter: ${c.message}`,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};return xt({metadata:null,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:[p]})}let i=this.parseMarkdownBody(o,a,t[0].length);return xt({metadata:s,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:i})}parseInline(e,t){let r=this.parseMarkdownBody(e,new Map,0);return xt({metadata:null,rawMarkdown:e,frontmatterLength:0,filePath:t,references:r})}parseMarkdownBody(e,t,r){let n=[],o=mn(e),s=new RegExp(sn.source,"gi"),a;for(;(a=s.exec(e))!==null;){if(sr(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:m}=ar(e,a.index),y={displayText:c,rawUri:p,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=De.parse(p)}catch(f){y.error=f.message}n.push(y)}let i=new RegExp(an.source,"gi");for(;(a=i.exec(e))!==null;){if(sr(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:m}=ar(e,a.index),y=null,f=null;try{y=yn(p,t)}catch(g){f=g.message}let d={displayText:c,rawUri:y??`kan://${p}`,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=De.parse(y)}catch(g){d.error=g.message}n.push(d)}return n.sort((c,p)=>c.startOffset-p.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 xt(l){return{metadata:l.metadata,get hasFrontmatter(){return l.metadata!=null},rawMarkdown:l.rawMarkdown,frontmatterLength:l.frontmatterLength,filePath:l.filePath,references:l.references,get referenceCount(){return l.references.length},get allReferencesResolved(){return l.references.every(e=>e.isResolved)},get unresolvedReferences(){return l.references.filter(e=>!e.isResolved)},get errorReferences(){return l.references.filter(e=>e.error!=null)}}}function mn(l){let e=[],t=new RegExp(cn.source,"g"),r;for(;(r=t.exec(l))!==null;)e.push([r.index,r.index+r[0].length]);return e}function sr(l,e){for(let[t,r]of e)if(l>=t&&l<r)return!0;return!1}function ar(l,e){let t=1,r=1;for(let n=0;n<e&&n<l.length;n++)l[n]===`
147
- `?(t++,r=1):r++;return{line:t,column:r}}function yn(l,e){if(!l||l.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=l,n=l.indexOf(".");if(n>0&&(t=l.substring(0,n),r=l.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 _,CtlValidationSeverity as z}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as cr,PathSegmentType as pr}from"@kanonak-protocol/types/ctl/parsing/enums";var kt=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:_.InvalidUri,severity:z.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`${z[this.severity]}: ${this.message} ${s}`.trim()}});continue}try{await this.resolveReference(o,t,r)}catch(s){t.push({errorType:_.ParseError,severity:z.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`${z[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 cr.Resource:await this.resolveResource(e,t);break;case cr.DeepLink:await this.resolveDeepLink(e,t);break;default:t.push({errorType:_.InvalidUri,severity:z.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`${z[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(_.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(_.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(_.PackageNotFound,`Package not found: ${n}`,e));return}if(!o.body||!o.body[r.resourceName]){t.push(this.createError(_.EntityNotFound,`Resource not found: ${r.resourceName} in ${n}`,e));return}let s=o.body[r.resourceName],a=r.resourceName;for(let i of r.path){if(s==null){t.push(this.createError(_.PathNotFound,`Path not found: ${a}`,e));return}if(i.type_===pr.Property){let c=i.name;a+=`.${c}`;let p=fn(s,c);if(p===void 0){let u=gn(s);t.push(this.createError(_.PathNotFound,`Path not found: ${a}`,e,u));return}s=p}else if(i.type_===pr.Index){let c=i.index;a+=`[${c}]`;let p=dn(s,c);if(p===void 0){let u=hn(s);t.push(this.createError(_.IndexOutOfBounds,`Index out of bounds: ${a}`,e,u));return}s=p}}e.isResolved=!0,e.resolvedValue=s}createError(e,t,r,n){return{errorType:e,severity:z.Error,message:t,reference:r,line:r.line,column:r.column,suggestion:n,toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${z[this.severity]}: ${this.message} ${o}`.trim()}}}};function fn(l,e){if(l&&typeof l=="object"&&!Array.isArray(l)){if(e in l)return l[e];let t=Object.keys(l).find(r=>r.toLowerCase()===e.toLowerCase());if(t)return l[t]}}function dn(l,e){if(Array.isArray(l)&&e>=0&&e<l.length)return l[e]}function gn(l){if(l&&typeof l=="object"&&!Array.isArray(l)){let e=Object.keys(l).slice(0,5);if(e.length>0)return`Available properties: ${e.join(", ")}`}}function hn(l){if(Array.isArray(l))return l.length>0?`Collection has ${l.length} items (valid indices: 0-${l.length-1})`:"Collection is empty"}import{ResolvedResourceType as $e}from"@kanonak-protocol/types/ctl/resolution/enums";var kn=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=[],i=new Set;for(let d of e.references)d.parsedUri&&i.add(d.parsedUri.toString());let c=new Map,p=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),$=`kanonak://${g}/${b}`;c.has($)||c.set($,{entity:v,namespace:g}),h.push(v)}p.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,i,n,o,s,a,c,p);m=Math.max(m,h),h>=t&&(y=!0)}let f=wn(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,i,c,p,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:i.push(g);break;case 2:p.push(g);break;default:c.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 $=m.get(v),j=await this.resolveEntityRecursive(v,$?.entity??null,null,n+1,o,s,a,i,c,p,u,m,y);b=Math.max(b,j)}}for(let R of g.properties.filter(v=>v.isObjectProperty)){let v=this.resolveReferenceToUri(R.rangeType,d,r);if(v&&!s.has(v)){let $=m.get(v),j=await this.resolveEntityRecursive(v,$?.entity??null,null,n+1,o,s,a,i,c,p,u,m,y);b=Math.max(b,j)}}if(g.instanceOf_){let R=this.resolveReferenceToUri(g.instanceOf_,d,r);if(R&&!s.has(R)){let v=m.get(R),$=await this.resolveEntityRecursive(R,v?.entity??null,null,n+1,o,s,a,i,c,p,u,m,y);b=Math.max(b,$)}}return b}createResolvedResource(e,t,r,n){let o=e,s=o.name??"",a=o.namespace??o.namespace_??"",i=this.classifyEntityType(e),c=lr(e),p=Rn(e),u=vn(e),m=[];if(i===$e.Class){let y=n.get(a);y&&(m=Pn(s,y))}return{name:s,kanonakUri:t,resource:e,resourceType:i,parentClass:p.length>0?p[0]:null,parentClasses:p,comment:c,properties:m,namespace_:a,resolutionDepth:r,instanceOf_:u}}classifyEntityType(e){if(w.isClassType(e))return $e.Class;if(w.isAnnotationPropertyType(e))return $e.AnnotationProperty;if(w.isDatatypePropertyType(e))return $e.DatatypeProperty;if(w.isObjectPropertyType(e))return $e.ObjectProperty;let t=w.getTypeUri(e);return t&&!w.isCoreOntologyType(t)?$e.Instance:$e.Other}classifyTier(e,t,r){return r.has(e)?0:bn(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 i of a)if((i.alias??i.packageName).toLowerCase()===o.toLowerCase())return`kanonak://${i.version?`${i.publisher}/${i.packageName}@${i.version}`:`${i.publisher}/${i.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 bn(l){if(!l)return!1;let e=l.split("/");if(e.length<2)return!1;let t=e[0],r=e[1],n=r.includes("@")?r.split("@")[0]:r;return kn.has(`${t}/${n}`)}function lr(l){let e=l;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 Rn(l){let e=[],t=l,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 vn(l){let e=w.getTypeUri(l);return e?w.isCoreOntologyType(e)?null:e.name:null}function Pn(l,e){let t=[];for(let r of e){if(!w.isAnyPropertyType(r))continue;let n=r,o=[],s=[];if(n.entity&&typeof n.entity=="object"){let p=n.entity.domain;if(typeof p=="string")o.push(p);else if(Array.isArray(p))for(let m of p)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(p=>p.toLowerCase()===l.toLowerCase()))continue;s.length===0&&s.push("unknown");let a=w.isObjectPropertyType(r),i=n.entity?.collection!=null,c=lr(r);t.push({name:n.name??"",rangeTypes:s,domains:o,get rangeType(){return s.length>0?s.join(", "):"unknown"},isObjectProperty:a,isCollection:i,comment:c})}return t}function wn(l){let e=l.split(`
146
+ 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 i=a.headers.get("DPoP-Nonce");if(i){e.set(r,i);try{let c=We(o.dpopKeyPair.privateKey,o.dpopKeyPair.publicKey,n,t,o.accessToken,i);s.DPoP=c,a=await fetch(t,{method:n,headers:s})}catch{}}}return a}}import{CtlKanonakUriType as He,PathSegmentType as Kt}from"@kanonak-protocol/types/ctl/parsing/enums";var rn=/\.?([a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\])/g;function nn(l){let e=l.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 Ce=class l{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?He.DeepLink:this.resourceName!=null?He.Resource:this.version!=null?He.VersionedPackage:this.package_!=null?He.Package:He.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,i=null,c=null,p=o.indexOf("@");if(p>=0){let m=o.substring(0,p),y=o.substring(p+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(c=y.substring(d+1),!g||g.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Version required after '@'`);if(i=nn(g),!c||c.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],c=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(!c||c.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}let u=[];return n!=null&&(u=on(n,e)),new l({publisher:s,package_:a,version:i,resourceName:c,path:u,rawUri:e})}static tryParse(e){try{return l.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_===Kt.Index?e+=`[${r.index}]`:(t||(e+="."),e+=r.name),t=!1}return e}equals(e){return e instanceof l?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 on(l,e){let t=[],r=new RegExp(rn.source,"g"),n=0,o;for(;(o=r.exec(l))!==null;){let s=o[1];if(s.startsWith("[")&&s.endsWith("]")){let a=s.substring(1,s.length-1),i=parseInt(a,10);if(isNaN(i))throw new Error(`Invalid Kanonak URI: '${e}'. Invalid array index: ${s}`);t.push({type_:Kt.Index,index:i,toString:()=>`[${i}]`})}else t.push({type_:Kt.Property,name:s,toString:()=>s});n+=o[0].length}if(n!==l.length)throw new Error(`Invalid Kanonak URI: '${e}'. Invalid path syntax in: ${l}`);return t}import{VersionOperator as q}from"@kanonak-protocol/types/document/models/enums";import*as ir from"js-yaml";var sn=/\[([^\]]+)\]\((kanonak:\/\/[^)]+)\)/gi,an=/\[([^\]]+)\]\(kan:\/\/([^)]+)\)/gi,cn=/```[\s\S]*?```|`[^`]+`/g,pn=/^---\s*\n([\s\S]*?)\n---\s*\n/;function ln(l,e,t){let r=`${l}.${e}.${t}`;return{major:l,minor:e,patch:t,toString:()=>r,equals:n=>n?.major===l&&n?.minor===e&&n?.patch===t,getHashCode:()=>l<<20|e<<10|t,compareTo:n=>l!==n.major?l-n.major:e!==n.minor?e-n.minor:t-n.patch}}function un(l,e,t,r,n){let o=r===q.Compatible?"~":r===q.Major?"^":r===q.Exact?"=":"*",s=`${e} ${o} ${t}`;return{package_:s,publisher:l,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!==q.Exact&&(a.match=o),a},toString(){return s}}}var ht=class{parse(e,t){if(e==null)throw new Error("Content cannot be null");e.charCodeAt(0)===65279&&(e=e.substring(1));let r=pn.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 c=ir.load(n);if(!c)throw new Error("Frontmatter YAML is empty");if(!c.imports||!Array.isArray(c.imports))throw new Error("Frontmatter must contain an 'imports' sequence");let p={};for(let m of c.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`);p[y]||(p[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=ln(g[0]||0,g[1]||0,g[2]||0),b=f.match?.toString(),R=b==="^"?q.Major:b==="~"?q.Compatible:b==="*"?q.Any:q.Exact,v=un(y,f.package?.toString()??"",h,R,f.alias?.toString()??null);p[y].push(v)}}let u=[];for(let m of Object.values(p))u.push(...m);s={namespace_:void 0,imports:p,get allImports(){return u}},a=this.buildAliasMap(p)}catch(c){let p={displayText:"(frontmatter)",rawUri:"",startOffset:0,endOffset:t[0].length,line:1,column:1,isResolved:!1,error:`Failed to parse frontmatter: ${c.message}`,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};return xt({metadata:null,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:[p]})}let i=this.parseMarkdownBody(o,a,t[0].length);return xt({metadata:s,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:i})}parseInline(e,t){let r=this.parseMarkdownBody(e,new Map,0);return xt({metadata:null,rawMarkdown:e,frontmatterLength:0,filePath:t,references:r})}parseMarkdownBody(e,t,r){let n=[],o=mn(e),s=new RegExp(sn.source,"gi"),a;for(;(a=s.exec(e))!==null;){if(sr(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:m}=ar(e,a.index),y={displayText:c,rawUri:p,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=Ce.parse(p)}catch(f){y.error=f.message}n.push(y)}let i=new RegExp(an.source,"gi");for(;(a=i.exec(e))!==null;){if(sr(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:m}=ar(e,a.index),y=null,f=null;try{y=yn(p,t)}catch(g){f=g.message}let d={displayText:c,rawUri:y??`kan://${p}`,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=Ce.parse(y)}catch(g){d.error=g.message}n.push(d)}return n.sort((c,p)=>c.startOffset-p.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 xt(l){return{metadata:l.metadata,get hasFrontmatter(){return l.metadata!=null},rawMarkdown:l.rawMarkdown,frontmatterLength:l.frontmatterLength,filePath:l.filePath,references:l.references,get referenceCount(){return l.references.length},get allReferencesResolved(){return l.references.every(e=>e.isResolved)},get unresolvedReferences(){return l.references.filter(e=>!e.isResolved)},get errorReferences(){return l.references.filter(e=>e.error!=null)}}}function mn(l){let e=[],t=new RegExp(cn.source,"g"),r;for(;(r=t.exec(l))!==null;)e.push([r.index,r.index+r[0].length]);return e}function sr(l,e){for(let[t,r]of e)if(l>=t&&l<r)return!0;return!1}function ar(l,e){let t=1,r=1;for(let n=0;n<e&&n<l.length;n++)l[n]===`
147
+ `?(t++,r=1):r++;return{line:t,column:r}}function yn(l,e){if(!l||l.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=l,n=l.indexOf(".");if(n>0&&(t=l.substring(0,n),r=l.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 _,CtlValidationSeverity as X}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as cr,PathSegmentType as pr}from"@kanonak-protocol/types/ctl/parsing/enums";var kt=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:_.InvalidUri,severity:X.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`${X[this.severity]}: ${this.message} ${s}`.trim()}});continue}try{await this.resolveReference(o,t,r)}catch(s){t.push({errorType:_.ParseError,severity:X.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`${X[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 cr.Resource:await this.resolveResource(e,t);break;case cr.DeepLink:await this.resolveDeepLink(e,t);break;default:t.push({errorType:_.InvalidUri,severity:X.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`${X[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(_.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(_.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(_.PackageNotFound,`Package not found: ${n}`,e));return}if(!o.body||!o.body[r.resourceName]){t.push(this.createError(_.EntityNotFound,`Resource not found: ${r.resourceName} in ${n}`,e));return}let s=o.body[r.resourceName],a=r.resourceName;for(let i of r.path){if(s==null){t.push(this.createError(_.PathNotFound,`Path not found: ${a}`,e));return}if(i.type_===pr.Property){let c=i.name;a+=`.${c}`;let p=fn(s,c);if(p===void 0){let u=gn(s);t.push(this.createError(_.PathNotFound,`Path not found: ${a}`,e,u));return}s=p}else if(i.type_===pr.Index){let c=i.index;a+=`[${c}]`;let p=dn(s,c);if(p===void 0){let u=hn(s);t.push(this.createError(_.IndexOutOfBounds,`Index out of bounds: ${a}`,e,u));return}s=p}}e.isResolved=!0,e.resolvedValue=s}createError(e,t,r,n){return{errorType:e,severity:X.Error,message:t,reference:r,line:r.line,column:r.column,suggestion:n,toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${X[this.severity]}: ${this.message} ${o}`.trim()}}}};function fn(l,e){if(l&&typeof l=="object"&&!Array.isArray(l)){if(e in l)return l[e];let t=Object.keys(l).find(r=>r.toLowerCase()===e.toLowerCase());if(t)return l[t]}}function dn(l,e){if(Array.isArray(l)&&e>=0&&e<l.length)return l[e]}function gn(l){if(l&&typeof l=="object"&&!Array.isArray(l)){let e=Object.keys(l).slice(0,5);if(e.length>0)return`Available properties: ${e.join(", ")}`}}function hn(l){if(Array.isArray(l))return l.length>0?`Collection has ${l.length} items (valid indices: 0-${l.length-1})`:"Collection is empty"}import{ResolvedResourceType as $e}from"@kanonak-protocol/types/ctl/resolution/enums";var kn=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=[],i=new Set;for(let d of e.references)d.parsedUri&&i.add(d.parsedUri.toString());let c=new Map,p=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),$=`kanonak://${g}/${b}`;c.has($)||c.set($,{entity:v,namespace:g}),h.push(v)}p.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,i,n,o,s,a,c,p);m=Math.max(m,h),h>=t&&(y=!0)}let f=wn(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,i,c,p,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:i.push(g);break;case 2:p.push(g);break;default:c.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 $=m.get(v),j=await this.resolveEntityRecursive(v,$?.entity??null,null,n+1,o,s,a,i,c,p,u,m,y);b=Math.max(b,j)}}for(let R of g.properties.filter(v=>v.isObjectProperty)){let v=this.resolveReferenceToUri(R.rangeType,d,r);if(v&&!s.has(v)){let $=m.get(v),j=await this.resolveEntityRecursive(v,$?.entity??null,null,n+1,o,s,a,i,c,p,u,m,y);b=Math.max(b,j)}}if(g.instanceOf_){let R=this.resolveReferenceToUri(g.instanceOf_,d,r);if(R&&!s.has(R)){let v=m.get(R),$=await this.resolveEntityRecursive(R,v?.entity??null,null,n+1,o,s,a,i,c,p,u,m,y);b=Math.max(b,$)}}return b}createResolvedResource(e,t,r,n){let o=e,s=o.name??"",a=o.namespace??o.namespace_??"",i=this.classifyEntityType(e),c=lr(e),p=Rn(e),u=vn(e),m=[];if(i===$e.Class){let y=n.get(a);y&&(m=Pn(s,y))}return{name:s,kanonakUri:t,resource:e,resourceType:i,parentClass:p.length>0?p[0]:null,parentClasses:p,comment:c,properties:m,namespace_:a,resolutionDepth:r,instanceOf_:u}}classifyEntityType(e){if(w.isClassType(e))return $e.Class;if(w.isAnnotationPropertyType(e))return $e.AnnotationProperty;if(w.isDatatypePropertyType(e))return $e.DatatypeProperty;if(w.isObjectPropertyType(e))return $e.ObjectProperty;let t=w.getTypeUri(e);return t&&!w.isCoreOntologyType(t)?$e.Instance:$e.Other}classifyTier(e,t,r){return r.has(e)?0:bn(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 i of a)if((i.alias??i.packageName).toLowerCase()===o.toLowerCase())return`kanonak://${i.version?`${i.publisher}/${i.packageName}@${i.version}`:`${i.publisher}/${i.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 bn(l){if(!l)return!1;let e=l.split("/");if(e.length<2)return!1;let t=e[0],r=e[1],n=r.includes("@")?r.split("@")[0]:r;return kn.has(`${t}/${n}`)}function lr(l){let e=l;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 Rn(l){let e=[],t=l,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 vn(l){let e=w.getTypeUri(l);return e?w.isCoreOntologyType(e)?null:e.name:null}function Pn(l,e){let t=[];for(let r of e){if(!w.isAnyPropertyType(r))continue;let n=r,o=[],s=[];if(n.entity&&typeof n.entity=="object"){let p=n.entity.domain;if(typeof p=="string")o.push(p);else if(Array.isArray(p))for(let m of p)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(p=>p.toLowerCase()===l.toLowerCase()))continue;s.length===0&&s.push("unknown");let a=w.isObjectPropertyType(r),i=n.entity?.collection!=null,c=lr(r);t.push({name:n.name??"",rangeTypes:s,domains:o,get rangeType(){return s.length>0?s.join(", "):"unknown"},isObjectProperty:a,isCollection:i,comment:c})}return t}function wn(l){let e=l.split(`
148
148
  `);for(let t of e){let r=t.trim();if(r.startsWith("# ")&&!r.startsWith("## "))return r.substring(2).trim()}return null}import{ResolvedResourceType as O}from"@kanonak-protocol/types/ctl/resolution/enums";var vt=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(`
149
- `)}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(p=>p.resourceType===O.Class),o=r.filter(p=>p.resourceType===O.AnnotationProperty),s=r.filter(p=>p.resourceType===O.DatatypeProperty),a=r.filter(p=>p.resourceType===O.ObjectProperty),i=r.filter(p=>p.resourceType===O.Instance);if(n.length>0){e.push(`### Classes (${n.length})`),e.push(""),e.push("| Class | Extends | Properties |"),e.push("|-------|---------|------------|");for(let p of[...n].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(p.name),m=p.parentClasses.length>0?this.renderInternalLinks(p.parentClasses):"-";e.push(`| ${u} | ${m} | ${p.properties.length} |`)}e.push("")}let c=[...o,...s,...a];if(c.length>0){e.push(`### Properties (${c.length})`),e.push(""),e.push("| Property | Type | Description |"),e.push("|----------|------|-------------|");for(let p of[...c].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(p.name),m=ur(p.resourceType),y=In(p.comment??"");e.push(`| ${u} | ${m} | ${y} |`)}e.push("")}if(i.length>0){let p=new Map;for(let u of i){let m=u.instanceOf_??"Unknown";p.has(m)||p.set(m,[]),p.get(m).push(u)}e.push("### Resources by Type"),e.push(""),e.push("| Type | Resources |"),e.push("|------|-----------|");for(let[u,m]of[...p.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===O.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 i of a.parentClasses)o.add(i.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((i,c)=>i.name.localeCompare(c.name))){let i=Rt(a.name);e.push(` ${i}["${a.name}"]`)}for(let a of[...o])if(!s.has(a)){let i=a;for(let p of n)for(let u of p.parentClasses)u.toLowerCase()===a&&(i=u);let c=Rt(i);e.push(` ${c}["${i}"]:::external`)}e.push("");for(let a of n){let i=Rt(a.name);for(let c of a.parentClasses){let p=Rt(c);e.push(` ${p} --> ${i}`)}}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** | ${ur(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===O.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 i=this.renderInternalLink(a);return r.isObjectProperty?`-> ${i}`:i}).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 ur(l){switch(l){case O.Class:return"Class";case O.AnnotationProperty:return"Annotation Property";case O.DatatypeProperty:return"Datatype Property";case O.ObjectProperty:return"Object Property";case O.Instance:return"Instance";default:return"Other"}}function In(l){return l?(l=l.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,""),l.length<=50?l:l.substring(0,47)+"..."):""}function Rt(l){return l.replace(/[^a-zA-Z0-9]/g,"_")}import{CtlValidationErrorType as An,CtlValidationSeverity as Cn}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as Dn,PathSegmentType as $n}from"@kanonak-protocol/types/ctl/parsing/enums";import{ResolvedResourceType as Sn}from"@kanonak-protocol/types/ctl/resolution/enums";export{Re as AmbiguousReferenceRule,Z as BooleanStatement,Ce as ClassDefinitionRule,ue as ClassHierarchyCycleRule,je as CompositeKanonakDocumentRepository,gt as CredentialStore,bt as CtlGraphResolver,De as CtlKanonakUri,Dn as CtlKanonakUriType,vt as CtlMarkdownRenderer,ht as CtlParser,An as CtlValidationErrorType,Cn as CtlValidationSeverity,kt as CtlValidator,U as DefinedKanonak,ke as DefinitionPropertyReferenceRule,wt as DocumentLocation,Ct as EdgeType,B as EmbeddedKanonak,ie as EmbeddedKanonakNoExplicitTypeRule,ee as EmbeddedStatement,q as FileSystemKanonakDocumentRepository,Ze as GitIgnoreFilter,Je as GraphBuilder,Ye as HttpKanonakDocumentRepository,ce as ImportExistenceRule,Ge as InMemoryKanonakDocumentRepository,he as InstancePropertyReferenceRule,F as Kanonak,Ke as KanonakObjectParser,nt as KanonakObjectValidator,E as KanonakParser,K as KanonakUri,tt as KanonakUriBuilder,te as ListStatement,ge as NamespaceImportCycleRule,ne as NamespacePrefixRule,At as NodeType,J as NumberStatement,Pe as ObjectPropertyImportRule,we as ObjectPropertyValueValidationRule,k as OntologyValidationError,re as OntologyValidationResult,$n as PathSegmentType,Ie as PropertyDomainRule,me as PropertyHierarchyCycleRule,et as PropertyMetadata,ve as PropertyRangeReferenceRule,ye as PropertyRangeRequiredRule,se as PropertyTypeSpecificityRule,Ae as PropertyValueTypeRule,Ee as PublisherConfigResolver,X as PublisherIndex,A as ReferenceKanonak,Q as ReferenceStatement,qe as RepositoryFactory,Sn as ResolvedResourceType,oe as ResourceNamingRule,V as ResourceResolver,w as ResourceTypeClassifier,T as ScalarStatement,x as Statement,Y as StringStatement,fe as SubClassOfReferenceRule,de as SubPropertyOfReferenceRule,L as SubjectKanonak,ae as SubjectKanonakTypeRequiredRule,le as TypeAmbiguityRule,W as TypeResolver,pe as UnresolvedReferenceRule,rt as ValidationContext,P as ValidationSeverity,be as XsdImportRule,or as createAuthenticatedFetch,We as createDPoPProof,Wt as findInstancesByType,rr as generateDPoPKeyPair,Te as getGlobalCachePath,ot as hasValidToken,Ne as isExpired,I as normalizeHost,nr as serverSupportsDPoP};
149
+ `)}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(p=>p.resourceType===O.Class),o=r.filter(p=>p.resourceType===O.AnnotationProperty),s=r.filter(p=>p.resourceType===O.DatatypeProperty),a=r.filter(p=>p.resourceType===O.ObjectProperty),i=r.filter(p=>p.resourceType===O.Instance);if(n.length>0){e.push(`### Classes (${n.length})`),e.push(""),e.push("| Class | Extends | Properties |"),e.push("|-------|---------|------------|");for(let p of[...n].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(p.name),m=p.parentClasses.length>0?this.renderInternalLinks(p.parentClasses):"-";e.push(`| ${u} | ${m} | ${p.properties.length} |`)}e.push("")}let c=[...o,...s,...a];if(c.length>0){e.push(`### Properties (${c.length})`),e.push(""),e.push("| Property | Type | Description |"),e.push("|----------|------|-------------|");for(let p of[...c].sort((u,m)=>u.name.localeCompare(m.name))){let u=this.renderInternalLink(p.name),m=ur(p.resourceType),y=In(p.comment??"");e.push(`| ${u} | ${m} | ${y} |`)}e.push("")}if(i.length>0){let p=new Map;for(let u of i){let m=u.instanceOf_??"Unknown";p.has(m)||p.set(m,[]),p.get(m).push(u)}e.push("### Resources by Type"),e.push(""),e.push("| Type | Resources |"),e.push("|------|-----------|");for(let[u,m]of[...p.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===O.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 i of a.parentClasses)o.add(i.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((i,c)=>i.name.localeCompare(c.name))){let i=Rt(a.name);e.push(` ${i}["${a.name}"]`)}for(let a of[...o])if(!s.has(a)){let i=a;for(let p of n)for(let u of p.parentClasses)u.toLowerCase()===a&&(i=u);let c=Rt(i);e.push(` ${c}["${i}"]:::external`)}e.push("");for(let a of n){let i=Rt(a.name);for(let c of a.parentClasses){let p=Rt(c);e.push(` ${p} --> ${i}`)}}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** | ${ur(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===O.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 i=this.renderInternalLink(a);return r.isObjectProperty?`-> ${i}`:i}).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 ur(l){switch(l){case O.Class:return"Class";case O.AnnotationProperty:return"Annotation Property";case O.DatatypeProperty:return"Datatype Property";case O.ObjectProperty:return"Object Property";case O.Instance:return"Instance";default:return"Other"}}function In(l){return l?(l=l.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,""),l.length<=50?l:l.substring(0,47)+"..."):""}function Rt(l){return l.replace(/[^a-zA-Z0-9]/g,"_")}import{CtlValidationErrorType as An,CtlValidationSeverity as Dn}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as Cn,PathSegmentType as $n}from"@kanonak-protocol/types/ctl/parsing/enums";import{ResolvedResourceType as Sn}from"@kanonak-protocol/types/ctl/resolution/enums";export{Re as AmbiguousReferenceRule,ee as BooleanStatement,De as ClassDefinitionRule,ue as ClassHierarchyCycleRule,je as CompositeKanonakDocumentRepository,gt as CredentialStore,bt as CtlGraphResolver,Ce as CtlKanonakUri,Cn as CtlKanonakUriType,vt as CtlMarkdownRenderer,ht as CtlParser,An as CtlValidationErrorType,Dn as CtlValidationSeverity,kt as CtlValidator,U as DefinedKanonak,ke as DefinitionPropertyReferenceRule,wt as DocumentLocation,Dt as EdgeType,M as EmbeddedKanonak,ie as EmbeddedKanonakNoExplicitTypeRule,W as EmbeddedStatement,Y as FileSystemKanonakDocumentRepository,Ze as GitIgnoreFilter,Je as GraphBuilder,Ye as HttpKanonakDocumentRepository,ce as ImportExistenceRule,Ge as InMemoryKanonakDocumentRepository,he as InstancePropertyReferenceRule,L as Kanonak,Ke as KanonakObjectParser,nt as KanonakObjectValidator,E as KanonakParser,K as KanonakUri,tt as KanonakUriBuilder,H as ListStatement,ge as NamespaceImportCycleRule,ne as NamespacePrefixRule,At as NodeType,Q as NumberStatement,Pe as ObjectPropertyImportRule,we as ObjectPropertyValueValidationRule,k as OntologyValidationError,re as OntologyValidationResult,$n as PathSegmentType,Ie as PropertyDomainRule,me as PropertyHierarchyCycleRule,et as PropertyMetadata,ve as PropertyRangeReferenceRule,ye as PropertyRangeRequiredRule,se as PropertyTypeSpecificityRule,Ae as PropertyValueTypeRule,Ee as PublisherConfigResolver,J as PublisherIndex,A as ReferenceKanonak,te as ReferenceStatement,qe as RepositoryFactory,Sn as ResolvedResourceType,oe as ResourceNamingRule,V as ResourceResolver,w as ResourceTypeClassifier,T as ScalarStatement,x as Statement,Z as StringStatement,fe as SubClassOfReferenceRule,de as SubPropertyOfReferenceRule,B as SubjectKanonak,ae as SubjectKanonakTypeRequiredRule,le as TypeAmbiguityRule,G as TypeResolver,pe as UnresolvedReferenceRule,rt as ValidationContext,P as ValidationSeverity,be as XsdImportRule,or as createAuthenticatedFetch,We as createDPoPProof,Wt as findInstancesByType,rr as generateDPoPKeyPair,Te as getGlobalCachePath,ot as hasValidToken,Ne as isExpired,I as normalizeHost,nr as serverSupportsDPoP};