@kanonak-protocol/sdk 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,53 +1,53 @@
1
- var St=Object.defineProperty;var Kt=(l,e)=>()=>(l&&(e=l(l=0)),e);var Ot=(l,e)=>{for(var t in e)St(l,t,{get:e[t],enumerable:!0})};var lt={};Ot(lt,{KanonakUri:()=>V});var V,De=Kt(()=>{"use strict";V=class l{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as Ce from"js-yaml";var O=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=Ce.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),Ce.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===s&&i.package_===o&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let c=0;c<s.length;c++)i=(i<<5)-i+s.charCodeAt(c);for(let c=0;c<o.length;c++)i=(i<<5)-i+o.charCodeAt(c);return i|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let i=0;i<o[1].length;i++)a=(a<<5)-a+o[1].charCodeAt(i);for(let i=0;i<o[2].length;i++)a=(a<<5)-a+o[2].charCodeAt(i);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),i=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:c,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let p=i[1].trim(),u=i[2],y=this.parseVersion(i[3].trim()),m=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:y,alias:m,minVersion:y,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:y.toString()};return m&&(g.alias=m),g},toString:()=>`${p} ${u} ${y.toString()} as ${m}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),u=c[2],y=this.parseVersion(c[3].trim()),m=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:m,version:y,alias:void 0,minVersion:y,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:y.toString()}),toString:()=>`${p} ${u} ${y.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let i={package:o,match:s,version:n.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],i={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(i.alias=s.alias),i})};t.push(o)}return t}};var E=class{};var L=class extends E{statement=[]};var F=class extends L{namespace;name;icon};var _=class extends L{};De();var I=class l extends E{subject;static parse(e){let t=new l;return t.subject=V.parse(e),t}};var je=class extends E{value};var S=class{predicate;object};var C=class extends S{};var B=class l extends C{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var Y=class l extends C{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var J=class extends C{};var Z=class l extends S{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=I.parse(t),r}};var W=class extends S{};var H=class extends S{};De();function D(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var $=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],a=await this.findDocumentForAlias(t,o);return a?await this.resolveAllEntitiesAsync(s,a):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[a,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:a,uri:new V(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:i,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((i,c)=>i+c.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[i,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let y=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...y),this.logger?.debug?.(`Added ${y.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(u){let y=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[i,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(i,{entityName:i,uri:new V(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let y=await this.repository.getHighestCompatibleVersionAsync(c,u);if(y){this.logger?.debug?.(`Successfully loaded import: ${y.metadata?.namespace_?.toString()}`);let m=await this.buildEntityIndexAsyncInternal(y,t,s),f=0;for(let[d,g]of m.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${y.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(y){let m=y;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:y})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=D(s);for(let i of a)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=D(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var 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 $e=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new $(e),o=new G(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new F;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,i]of Object.entries(e))try{let c=await this.getPropertyMetadata(a,t,r,o,n);if(!c)continue;let p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}catch(c){console.error(`Error parsing property ${a}:`,c)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,i=a.type?.toString()??"",c=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let u=o.getPropertyTypeClassification(i),y=a.range?.toString(),m;if(u==="ObjectProperty")m="ObjectProperty";else if(u==="DatatypeProperty")m="DatatypeProperty";else{let d=y&&y.includes(".")?y.substring(y.lastIndexOf(".")+1):y??"";(y?o.isKnownXsdDatatypeName(y):!1)||d==="Literal"?m="DatatypeProperty":m="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:m,range:y,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return B.parse(e,t.toISOString());if(typeof t=="string")return B.parse(e,t);if(typeof t=="number")return Y.parse(e,t);if(typeof t=="boolean"){let n=new J;return n.predicate=I.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let i=new Z;return i.predicate=I.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new _;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new W;return p.predicate=I.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new _;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=I.parse(e),p.object=i,p}let c=new W;return c.predicate=I.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[],i=r.propertyType==="DatatypeProperty";for(let p of t){if(i&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let u=new je;u.value=p,a.push(u);continue}if(i&&p instanceof Date){let u=new je;u.value=p.toISOString(),a.push(u);continue}if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&a.push(u)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new _;u.statement=await this.parseStatements(p,n,o,s,{}),a.push(u)}}let c=new H;return c.predicate=I.parse(e),c.object=a,c}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new I;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(De(),lt)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[y,m]of Object.entries(t.metadata.imports))for(let f of m)if((f.alias??f.packageName)===p){let g=new I;return g.subject=new s(y,f.packageName,u,f.version),g}}}let i=new I;return i.subject=new s(o.publisher,o.package_,e,a),i}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof F&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),a=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,a)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof F&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new O().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let i of s.statement){let[c,p]=this.convertStatementToProperty(i);c&&p!==null&&p!==void 0&&(a[c]=p),this.collectImportsFromStatement(i,e,o)}n.body[s.name]=a}return n}convertStatementToProperty(e){if(e instanceof B)return[e.predicate.subject.name,e.object];if(e instanceof Y)return[e.predicate.subject.name,e.object];if(e instanceof J)return[e.predicate.subject.name,e.object];if(e instanceof Z)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof 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 I?t.push(r.subject.name):r instanceof _&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var xe=class{propertyUri;propertyType;range;isImported;definedInNamespace};var Et=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),ut={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 x(l){let e=l;if(e.entity&&typeof e.entity=="object"){let t=e.entity.type;if(typeof t=="string"){let r=ut[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=ut[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function M(l,e){return Et.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return x(e)}static isCoreOntologyType(e){return M(e.publisher,e.package_)}static isClassType(e){let t=x(e);return t?M(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=x(e);return t?M(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=x(e);return t?M(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=x(e);return t?M(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=x(e);return t?M(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=x(e);return t?M(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=x(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=x(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=x(e);return r?t.has(r.name):!1}};var et=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(et||{}),tt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(tt||{}),Te=class{static async buildFromRepository(e){let r=await new $e().parseKanonaks(e),n=await e.getAllDocumentsAsync(),o=[],s=[],a=new Set,i=new Set,c=new Map;for(let u of r){let y=u;y.name&&(w.isClassType(y)&&a.add(y.name),(w.isObjectPropertyType(y)||w.isGenericPropertyType(y))&&i.add(y.name))}for(let u of n)for(let[y,m]of Object.entries(u.body))i.has(y)&&m?.range&&typeof m.range=="string"&&c.set(y,m.range);let p=new Map;for(let u of r){let y=u;y.name&&p.set(y.name,y)}for(let u of n){let y=u.metadata.namespace_,m=y?`${y.publisher}/${y.package_}`:"",f=y?.version?`${y.version.major}.${y.version.minor}.${y.version.patch}`:"",d=yt(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let k=p.get(g),R="Unknown";if(k){let j=k;w.isClassType(j)?R="Class":w.isObjectPropertyType(j)?R="ObjectProperty":w.isDatatypePropertyType(j)?R="DatatypeProperty":w.isAnnotationPropertyType(j)?R="AnnotationProperty":w.isDatatypeType(j)?R="Datatype":w.isGenericPropertyType(j)?R="ObjectProperty":w.isInstanceOfKnownClass(j,a)&&(R="Instance")}let v=m&&f?`${m}/${g}@${f}`:g,A={};for(let[j,Ze]of Object.entries(h))j!=="type"&&(typeof Ze!="object"||Ze===null)&&(A[j]=Ze);o.push({id:v,label:h.label??g,type:R,namespace:m,properties:A}),mt(v,h,R,a,i,s,m,f,d),Qe(v,h,i,c,o,s,m,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,i=new Set,c=new Map,p=yt(e);for(let[m,f]of Object.entries(e.body)){let d=f?.type;d&&(xt(d,p)&&a.add(m),Tt(d,p)&&(i.add(m),f.range&&typeof f.range=="string"&&c.set(m,f.range)))}for(let[m,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=Nt(d,m,a,p),h=s&&o?`${s}/${m}@${o}`:m,k={};for(let[R,v]of Object.entries(f))R!=="type"&&(typeof v!="object"||v===null)&&(k[R]=v);t.push({id:h,label:f.label??m,type:g,namespace:s,properties:k}),mt(h,f,g,a,i,r,s,o,p),Qe(h,f,i,c,t,r,s,o,p)}let u=new Set(t.map(m=>m.id)),y=r.filter(m=>u.has(m.source)&&u.has(m.target));return{nodes:t,edges:y}}};function yt(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 ft={"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"},Ct=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function rt(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 xt(l,e){let t=rt(l,e);return t?ft[t]==="Class":!1}function Tt(l,e){let t=rt(l,e);return t?Ct.has(t):!1}function Nt(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=rt(l,r);if(n){let s=ft[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 dt=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function mt(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(dt.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&_t(h)&&o.push({source:l,target:z(h,s,a,i),type:"propertyValue",label:f,propertyId:z(f,s,a,i)})}let y=t==="ObjectProperty"||t==="DatatypeProperty",m=e.domain&&e.range;if((y||m)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:z(f,s,a,i),target:z(d,s,a,i),type:"objectRelationship",label:e.label??l.split("/").pop()??"",propertyId:l})}}function Qe(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if(dt.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,y=`${l}/${c}`,m=r.get(c),f=m?m.split(".").pop()??m:"Unknown",d={};for(let[h,k]of Object.entries(u))(typeof k!="object"||k===null)&&(d[h]=k);n.push({id:y,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:l,target:y,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),m&&o.push({source:y,target:z(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),Qe(y,u,t,r,n,o,s,a,i)}}function _t(l){return!(!l||l.includes(" ")||l.includes(`
2
- `)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function 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}var Q=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var P=(t=>(t.Warning="Warning",t.Error="Error",t))(P||{});var b=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var Ne=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ee=class l{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&l.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new b;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=n,c.expectedValue=a,c.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var te=class l{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){if(!r&&l.RESERVED_WORDS.has(n.toLowerCase())){let s=new b;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Entity name '${n}' is a reserved word and cannot be used.`,s.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(s);continue}if(!l.VALID_NAME_PATTERN.test(n)){let s;/^\d/.test(n)?s="Entity names must start with a letter, not a number.":n.includes(" ")?s="Entity names cannot contain spaces. Use camelCase or underscores instead.":s="Entity names must start with a letter and contain only letters, numbers, and underscores.";let a=new b;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Invalid entity name '${n}'. ${s}`,a.suggestion=s,t.push(a)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!l.VALID_PROPERTIES.has(n)&&!l.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new b;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var re=class l{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let i=[];if(Array.isArray(a))for(let c of a){let p=c?.toString();p&&p==="Property"&&!r&&i.push(p)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let p=this.getPropertyValue(s,"range"),u=this.determinePropertyType(p),y=new b;y.ruleType=this.ruleName,y.severity="Error",y.entityName=n,y.propertyName="type",y.actualValue=c,y.expectedValue=u,y.message=`Invalid property type '${c}'. Use '${u}' instead.`,y.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(y)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":l.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var ne=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let i=new b;i.ruleType=this.ruleName,i.severity="Error",i.entityName=r,i.propertyName="type",i.message=`Subject Kanonak '${r}' must have a 'type' property.`,i.suggestion=`Add a type statement like:
1
+ var Xt=Object.defineProperty;var Yt=(l,e)=>()=>(l&&(e=l(l=0)),e);var Jt=(l,e)=>{for(var t in e)Xt(l,t,{get:e[t],enumerable:!0})};var wt={};Jt(wt,{KanonakUri:()=>E});var E,$e=Yt(()=>{"use strict";E=class l{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],n=t[1],o=r.split("/");if(o.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=n.split(".").map(Number),a={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(s[0]||0)&&i.minor===(s[1]||0)&&i.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:i=>(s[0]||0)!==i.major?(s[0]||0)-i.major:(s[1]||0)!==i.minor?(s[1]||0)-i.minor:(s[2]||0)-i.patch};return new l(o[0],o[1],o[2],a)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as Ue from"js-yaml";var $=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=Ue.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),Ue.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,a=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:i=>!i||typeof i!="object"?!1:i.publisher===s&&i.package_===o&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let c=0;c<s.length;c++)i=(i<<5)-i+s.charCodeAt(c);for(let c=0;c<o.length;c++)i=(i<<5)-i+o.charCodeAt(c);return i|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:a=>!a||typeof a!="object"?!1:a.publisher===o[1]&&a.package_===o[2]&&(!s||!a.version||s.equals(a.version)),getHashCode:()=>{let a=0;for(let i=0;i<o[1].length;i++)a=(a<<5)-a+o[1].charCodeAt(i);for(let i=0;i<o[2].length;i++)a=(a<<5)-a+o[2].charCodeAt(i);return a|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),a=this.parseVersionOperator(n),i=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:a,version:s,alias:c,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let p={package:r,match:n,version:s.toString()};return c&&(p.alias=c),p},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let p=i[1].trim(),u=i[2],y=this.parseVersion(i[3].trim()),m=i[4].trim(),f=this.parseVersionOperator(u),d=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:y,alias:m,minVersion:y,maxVersion:d,toEmbeddedObject:()=>{let g={package:p,match:u,version:y.toString()};return m&&(g.alias=m),g},toString:()=>`${p} ${u} ${y.toString()} as ${m}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),u=c[2],y=this.parseVersion(c[3].trim()),m=this.parseVersionOperator(u),f=this.calculateMaxVersion(u,y);return{package_:e,publisher:t,packageName:p,versionOperator:m,version:y,alias:void 0,minVersion:y,maxVersion:f,toEmbeddedObject:()=>({package:p,match:u,version:y.toString()}),toString:()=>`${p} ${u} ${y.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],a=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:a,toEmbeddedObject:()=>{let i={package:o,match:s,version:n.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let a=["=","~","^","*"][s.versionOperator],i={package:s.packageName,match:a,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(i.alias=s.alias),i})};t.push(o)}return t}};var O=class{};var W=class extends O{statement=[]};var H=class extends W{namespace;name;icon};var U=class extends W{};$e();var I=class l extends O{subject;static parse(e){let t=new l;return t.subject=E.parse(e),t}};var Ee=class extends O{value};var K=class{predicate;object};var T=class extends K{};var q=class l extends T{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var ee=class l extends T{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=t,r}};var te=class extends T{};var re=class l extends K{static parse(e,t){let r=new l;return r.predicate=I.parse(e),r.object=I.parse(t),r}};var G=class extends K{};var z=class extends K{};$e();function D(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var 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 E(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,c),entity:i,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((i,c)=>i+c.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[i,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,p);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let y=await this.buildAllEntitiesIndexAsync(u,t,s);n.push(...y),this.logger?.debug?.(`Added ${y.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(u){let y=u;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${y.message}`,y),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:u})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,a=0;for(let[i,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(i,{entityName:i,uri:new E(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),a++}if(this.logger?.debug?.(`Indexed ${a} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let u of p)try{this.logger?.debug?.(`Resolving import: ${c}/${u.packageName}`);let y=await this.repository.getHighestCompatibleVersionAsync(c,u);if(y){this.logger?.debug?.(`Successfully loaded import: ${y.metadata?.namespace_?.toString()}`);let m=await this.buildEntityIndexAsyncInternal(y,t,s),f=0;for(let[d,g]of m.entries())if(n.has(d)||(n.set(d,g),f++),u.alias&&!d.includes(".")){let h=`${u.alias}.${d}`;n.has(h)||(n.set(h,g),f++)}this.logger?.debug?.(`Merged ${f} entities from import ${y.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${u.packageName}`)}catch(y){let m=y;throw this.logger?.error?.(`Failed to process import ${c}/${u.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${c}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:y})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let a=D(s);for(let i of a)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let a=D(s);for(let i of a)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,n))return!0}return!1}};var X=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 X(n);for(let s of r)for(let[a,i]of Object.entries(s.body)){let c=new H;c.namespace=s.metadata.namespace_?.toString()??"",c.name=a,c.statement=[];let p=await this.parseStatements(i,s,n,o,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[a,i]of Object.entries(e))try{let c=await this.getPropertyMetadata(a,t,r,o,n);if(!c)continue;let p=await this.parsePropertyValue(a,i,c,t,r,n);p&&s.push(p)}catch(c){console.error(`Error parsing property ${a}:`,c)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let a=s.entity,i=a.type?.toString()??"",c=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let u=o.getPropertyTypeClassification(i),y=a.range?.toString(),m;if(u==="ObjectProperty")m="ObjectProperty";else if(u==="DatatypeProperty")m="DatatypeProperty";else{let d=y&&y.includes(".")?y.substring(y.lastIndexOf(".")+1):y??"";(y?o.isKnownXsdDatatypeName(y):!1)||d==="Literal"?m="DatatypeProperty":m="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:m,range:y,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let a=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(a,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(a,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(a,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return q.parse(e,t.toISOString());if(typeof t=="string")return q.parse(e,t);if(typeof t=="number")return ee.parse(e,t);if(typeof t=="boolean"){let n=new te;return n.predicate=I.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let a=await this.resolveReference(t,n,o);if(!a)return;let i=new re;return i.predicate=I.parse(e),i.object=a,i}if(typeof t=="object"&&!Array.isArray(t)){let a=new U;if(a.statement=await this.parseStatements(t,n,o,s,{}),a.statement.length>0){let p=new G;return p.predicate=I.parse(e),p.object=a,p}let i=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new U;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 z;return p.predicate=I.parse(e),p.object=i,p}let c=new G;return c.predicate=I.parse(e),c.object=a,c}}async parseListValue(e,t,r,n,o,s){let a=[],i=r.propertyType==="DatatypeProperty";for(let p of t){if(i&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let u=new Ee;u.value=p,a.push(u);continue}if(i&&p instanceof Date){let u=new Ee;u.value=p.toISOString(),a.push(u);continue}if(typeof p=="string"){let u=await this.resolveReference(p,n,o);u&&a.push(u)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=new U;u.statement=await this.parseStatements(p,n,o,s,{}),a.push(u)}}let c=new z;return c.predicate=I.parse(e),c.object=a,c}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new I;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>($e(),wt)),a=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),u=e.substring(c+1);if(t.metadata?.imports){for(let[y,m]of Object.entries(t.metadata.imports))for(let f of m)if((f.alias??f.packageName)===p){let g=new I;return g.subject=new s(y,f.packageName,u,f.version),g}}}let i=new I;return i.subject=new s(o.publisher,o.package_,e,a),i}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof H&&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 H&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new $().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let a of Object.values(this.imports))s.push(...a);return s}},body:{}},o=new Map;for(let s of t){let a={};for(let 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 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];if(e instanceof re)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof z){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof G){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof I?t.push(r.subject.name):r instanceof U&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var Le=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as Zt,LineCounter as Qt,isMap as Te,isPair as j,isScalar as x,isSeq as pt}from"yaml";var xe=class l{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;static fromContent(e){let t=new l,r=new Qt,n=Zt(e,{lineCounter:r});if(n.errors.length>0||!Te(n.contents))return t;for(let o of n.contents.items){if(!j(o)||!x(o.key))continue;let s=String(o.key.value),a=o.key.range;if(!a)continue;t.entities.set(s,Y(a,r));let i=o.value,c=i&&typeof i=="object"&&"range"in i?i.range:void 0;if(c?t.entityBlocks.set(s,Y([a[0],a[1],c[2]],r)):t.entityBlocks.set(s,Y(a,r)),Te(o.value)){let p=new Map,u=new Map,y=new Map;for(let f of o.value.items){if(!j(f)||!x(f.key))continue;let d=String(f.key.value),g=f.key.range;g&&p.set(d,Y(g,r));let h=f.value;if(h&&typeof h=="object"&&"range"in h&&Array.isArray(h.range)){let k=h.range;u.set(d,Y(k,r))}if(pt(h)){let k=[];for(let R of h.items)R&&typeof R=="object"&&"range"in R&&Array.isArray(R.range)&&k.push(Y(R.range,r));k.length>0&&y.set(d,k)}}p.size>0&&t.properties.set(s,p),u.size>0&&t.propertyValues.set(s,u),y.size>0&&t.valueListItems.set(s,y);let m=er(o.value,r);m.length>0&&t.importPackages.set(s,m)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(ct(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,a;if(o)for(let[i,c]of o)ct(c,e,t)&&(!a||It(c,a))&&(s=i,a=c);if(n)for(let[i,c]of n)ct(c,e,t)&&(!a||It(c,a))&&(s=i,a=c);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function er(l,e){let t=[];if(!Te(l))return t;let r=l.items.find(n=>j(n)&&x(n.key)&&String(n.key.value)==="imports");if(!r||!j(r)||!pt(r.value))return t;for(let n of r.value.items){if(!Te(n))continue;let o=n.items.find(i=>j(i)&&x(i.key)&&String(i.key.value)==="publisher");if(!o||!j(o)||!x(o.value))continue;let s=String(o.value.value),a=n.items.find(i=>j(i)&&x(i.key)&&String(i.key.value)==="packages");if(!(!a||!j(a)||!pt(a.value)))for(let i of a.value.items){if(!Te(i))continue;let c=i.items.find(g=>j(g)&&x(g.key)&&String(g.key.value)==="package");if(!c||!j(c)||!x(c.value)||!c.value.range)continue;let p=String(c.value.value),u=i.items.find(g=>j(g)&&x(g.key)&&String(g.key.value)==="version"),y=u&&j(u)&&x(u.value)?String(u.value.value):"",m=i.items.find(g=>j(g)&&x(g.key)&&String(g.key.value)==="alias"),f=m&&j(m)&&x(m.value)?String(m.value.value):void 0,d=f!==void 0?{publisher:s,package_:p,version:y,alias:f,position:Y(c.value.range,e)}:{publisher:s,package_:p,version:y,position:Y(c.value.range,e)};t.push(d)}}return t}function ct(l,e,t){return!(e<l.line||e>l.endLine||e===l.line&&t<l.column||e===l.endLine&&t>l.endColumn)}function It(l,e){let t=l.endLine-l.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=l.endLine===l.line?l.endColumn-l.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function Y(l,e){let t=e.linePos(l[0]),r=e.linePos(l[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function At(l,e){let r=(e??new $).parse(l),n=xe.fromContent(l);return{document:r,positions:n}}var tr=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]),Dt={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=Dt[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=Dt[r.name];if(n)return{publisher:n.publisher,package_:n.package_,name:r.name}}return r}}return null}function L(l,e){return tr.has(`${l}/${e}`)}var w=class l{static getTypeUri(e){return N(e)}static isCoreOntologyType(e){return L(e.publisher,e.package_)}static isClassType(e){let t=N(e);return t?L(t.publisher,t.package_)&&t.name==="Class":!1}static isDatatypeType(e){let t=N(e);return t?L(t.publisher,t.package_)&&t.name==="Datatype":!1}static isDatatypePropertyType(e){let t=N(e);return t?L(t.publisher,t.package_)&&t.name==="DatatypeProperty":!1}static isObjectPropertyType(e){let t=N(e);return t?L(t.publisher,t.package_)&&t.name==="ObjectProperty":!1}static isAnnotationPropertyType(e){let t=N(e);return t?L(t.publisher,t.package_)&&t.name==="AnnotationProperty":!1}static isGenericPropertyType(e){let t=N(e);return t?L(t.publisher,t.package_)&&t.name==="Property":!1}static isAnyPropertyType(e){let t=N(e);return!t||!L(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||!L(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 ut=(a=>(a.Class="Class",a.DatatypeProperty="DatatypeProperty",a.ObjectProperty="ObjectProperty",a.AnnotationProperty="AnnotationProperty",a.Instance="Instance",a.Datatype="Datatype",a.Unknown="Unknown",a))(ut||{}),yt=(a=>(a.InstanceOf="instanceOf",a.SubClassOf="subClassOf",a.Domain="domain",a.Range="range",a.ObjectRelationship="objectRelationship",a.SubPropertyOf="subPropertyOf",a.PropertyValue="propertyValue",a))(yt||{}),Fe=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 y=u;y.name&&(w.isClassType(y)&&a.add(y.name),(w.isObjectPropertyType(y)||w.isGenericPropertyType(y))&&i.add(y.name))}for(let u of n)for(let[y,m]of Object.entries(u.body))i.has(y)&&m?.range&&typeof m.range=="string"&&c.set(y,m.range);let p=new Map;for(let u of r){let y=u;y.name&&p.set(y.name,y)}for(let u of n){let y=u.metadata.namespace_,m=y?`${y.publisher}/${y.package_}`:"",f=y?.version?`${y.version.major}.${y.version.minor}.${y.version.patch}`:"",d=St(u);for(let[g,h]of Object.entries(u.body)){if(!h||typeof h!="object")continue;let k=p.get(g),R="Unknown";if(k){let S=k;w.isClassType(S)?R="Class":w.isObjectPropertyType(S)?R="ObjectProperty":w.isDatatypePropertyType(S)?R="DatatypeProperty":w.isAnnotationPropertyType(S)?R="AnnotationProperty":w.isDatatypeType(S)?R="Datatype":w.isGenericPropertyType(S)?R="ObjectProperty":w.isInstanceOfKnownClass(S,a)&&(R="Instance")}let P=m&&f?`${m}/${g}@${f}`:g,A={};for(let[S,it]of Object.entries(h))S!=="type"&&(typeof it!="object"||it===null)&&(A[S]=it);o.push({id:P,label:h.label??g,type:R,namespace:m,properties:A}),Vt(P,h,R,a,i,s,m,f,d),lt(P,h,i,c,o,s,m,f,d)}}return{nodes:o,edges:s}}static buildFromDocument(e){let t=[],r=[],n=e.metadata.namespace_,o=n?.version?`${n.version.major}.${n.version.minor}.${n.version.patch}`:"",s=n?`${n.publisher}/${n.package_}`:"",a=new Set,i=new Set,c=new Map,p=St(e);for(let[m,f]of Object.entries(e.body)){let d=f?.type;d&&(nr(d,p)&&a.add(m),or(d,p)&&(i.add(m),f.range&&typeof f.range=="string"&&c.set(m,f.range)))}for(let[m,f]of Object.entries(e.body)){if(!f||typeof f!="object")continue;let d=f.type,g=sr(d,m,a,p),h=s&&o?`${s}/${m}@${o}`:m,k={};for(let[R,P]of Object.entries(f))R!=="type"&&(typeof P!="object"||P===null)&&(k[R]=P);t.push({id:h,label:f.label??m,type:g,namespace:s,properties:k}),Vt(h,f,g,a,i,r,s,o,p),lt(h,f,i,c,t,r,s,o,p)}let u=new Set(t.map(m=>m.id)),y=r.filter(m=>u.has(m.source)&&u.has(m.target));return{nodes:t,edges:y}}};function St(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 jt={"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 mt(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 nr(l,e){let t=mt(l,e);return t?jt[t]==="Class":!1}function or(l,e){let t=mt(l,e);return t?rr.has(t):!1}function sr(l,e,t,r){if(!l||l==="Package")return"Unknown";let n=mt(l,r);if(n){let s=jt[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 $t=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function Vt(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:J(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:J(d,s,a,i),type:"subPropertyOf",label:"subPropertyOf"})}if(t==="Instance"&&c){let f=c.split(".").pop()??c;o.push({source:l,target:J(f,s,a,i),type:"instanceOf",label:"type"})}if(t==="Instance")for(let[f,d]of Object.entries(e)){if($t.has(f)||!n.has(f))continue;let g=Array.isArray(d)?d:[d];for(let h of g)typeof h=="string"&&ar(h)&&o.push({source:l,target:J(h,s,a,i),type:"propertyValue",label:f,propertyId:J(f,s,a,i)})}let y=t==="ObjectProperty"||t==="DatatypeProperty",m=e.domain&&e.range;if((y||m)&&e.domain&&e.range){let f=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;f&&d&&o.push({source:J(f,s,a,i),target:J(d,s,a,i),type:"objectRelationship",label:e.label??l.split("/").pop()??"",propertyId:l})}}function lt(l,e,t,r,n,o,s,a,i){for(let[c,p]of Object.entries(e)){if($t.has(c)||typeof p!="object"||p===null||Array.isArray(p))continue;let u=p,y=`${l}/${c}`,m=r.get(c),f=m?m.split(".").pop()??m:"Unknown",d={};for(let[h,k]of Object.entries(u))(typeof k!="object"||k===null)&&(d[h]=k);n.push({id:y,label:`${f} (embedded)`,type:"Instance",namespace:s,properties:d});let g=s&&a?`${s}/${c}@${a}`:c;o.push({source:l,target:y,type:"propertyValue",label:c,propertyId:t.has(c)?g:void 0}),m&&o.push({source:y,target:J(f,s,a,i),type:"instanceOf",label:"type (inferred)"}),lt(y,u,t,r,n,o,s,a,i)}}function ar(l){return!(!l||l.includes(" ")||l.includes(`
2
+ `)||l.startsWith("http://")||l.startsWith("https://")||/^\d{4}-\d{2}/.test(l)||/^\d+(\.\d+)?$/.test(l))}function J(l,e,t,r){if(l.includes("@")&&l.includes("/"))return l;if(l.includes(".")){let n=l.indexOf("."),o=l.substring(0,n),s=l.substring(n+1);if(r){let a=r.get(o);if(a)return`${a.publisher}/${a.package_}/${s}@${a.version}`}return e&&t?`${e}/${s}@${t}`:s}return e&&t?`${e}/${l}@${t}`:l}var ne=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var v=(t=>(t.Warning="Warning",t.Error="Error",t))(v||{});var b=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var Be=class l{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new l;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var oe=class l{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[r,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(r,n,t);return t}validateEntity(e,t,r){for(let[n,o]of Object.entries(t)){let s=o?.toString()??"";if(s&&l.NAMESPACE_PREFIX_PATTERN.test(s)){let a=this.getSuggestionForPrefixedValue(s),i=e.split(".")[0],c=new b;c.ruleType=this.ruleName,c.severity="Error",c.entityName=i,c.propertyName=e,c.actualValue=n,c.expectedValue=a,c.message=`Invalid namespace prefix '${s}'. Use '${a}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",r.push(c)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(`${e}.${n}`,o,r)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let r=e.indexOf(":");return r>=0?e.substring(r+1):e}};var se=class l{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],r=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,o]of Object.entries(e.body)){if(!r&&l.RESERVED_WORDS.has(n.toLowerCase())){let s=new b;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Entity name '${n}' is a reserved word and cannot be used.`,s.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(s);continue}if(!l.VALID_NAME_PATTERN.test(n)){let s;/^\d/.test(n)?s="Entity names must start with a letter, not a number.":n.includes(" ")?s="Entity names cannot contain spaces. Use camelCase or underscores instead.":s="Entity names must start with a letter and contain only letters, numbers, and underscores.";let a=new b;a.ruleType=this.ruleName,a.severity="Error",a.entityName=n,a.message=`Invalid entity name '${n}'. ${s}`,a.suggestion=s,t.push(a)}o&&typeof o=="object"&&!Array.isArray(o)&&this.validatePropertyNames(n,o,t)}return t}validatePropertyNames(e,t,r){for(let n of Object.keys(t))if(!l.VALID_PROPERTIES.has(n)&&!l.VALID_PROPERTY_NAME_PATTERN.test(n)){let o=new b;o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=n,o.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,o.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",r.push(o)}}};var ae=class l{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let r=this.isPropertyDefinedAsClass(e);for(let[n,o]of Object.entries(e.body))if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,a=s.type;if(a){let i=[];if(Array.isArray(a))for(let c of a){let p=c?.toString();p&&p==="Property"&&!r&&i.push(p)}else{let c=a?.toString();c&&c==="Property"&&!r&&i.push(c)}for(let c of i){let p=this.getPropertyValue(s,"range"),u=this.determinePropertyType(p),y=new b;y.ruleType=this.ruleName,y.severity="Error",y.entityName=n,y.propertyName="type",y.actualValue=c,y.expectedValue=u,y.message=`Invalid property type '${c}'. Use '${u}' instead.`,y.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(y)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":l.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let o=n.toString();return o==="Class"||o.endsWith(".Class")}}return!1}};var ie=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let o=n,s="type"in o,a=o.type?.toString().trim();if(!s||!a){let i=new b;i.ruleType=this.ruleName,i.severity="Error",i.entityName=r,i.propertyName="type",i.message=`Subject Kanonak '${r}' must have a 'type' property.`,i.suggestion=`Add a type statement like:
3
3
  type: Scene
4
4
 
5
- Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,i.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(i)}}return t}};var oe=class{get ruleName(){return"EmbeddedKanonakNoExplicitType"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&this.checkForEmbeddedTypeViolations(r,n,t,0);return t}checkForEmbeddedTypeViolations(e,t,r,n){for(let[o,s]of Object.entries(t)){let a=o;if(n>0&&a.toLowerCase()==="type"){let i=s?.toString(),c=e.split(".")[0],p=new b;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue="type",p.message=`Embedded object at '${e}' cannot have explicit 'type' property.`,p.suggestion=`Remove the 'type: ${i}' line.
5
+ Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,i.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(i)}}return t}};var ce=class{get ruleName(){return"EmbeddedKanonakNoExplicitType"}validate(e){let t=[];for(let[r,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&this.checkForEmbeddedTypeViolations(r,n,t,0);return t}checkForEmbeddedTypeViolations(e,t,r,n){for(let[o,s]of Object.entries(t)){let a=o;if(n>0&&a.toLowerCase()==="type"){let i=s?.toString(),c=e.split(".")[0],p=new b;p.ruleType=this.ruleName,p.severity="Error",p.entityName=c,p.propertyName=e,p.actualValue="type",p.message=`Embedded object at '${e}' cannot have explicit 'type' property.`,p.suggestion=`Remove the 'type: ${i}' line.
6
6
 
7
7
  Type is automatically inferred from the containing property's range.
8
8
  If you need a different type, modify the 'range' of the parent property and version it appropriately.
9
9
 
10
- Example: If the parent property is 'hasCharacter' with range 'Character', all embedded objects in that property will be typed as 'Character' automatically.`,p.expectedValue="No explicit type (inferred from parent property's range)",r.push(p)}if(typeof s=="object"&&s!==null)if(Array.isArray(s))for(let i=0;i<s.length;i++){let c=s[i];typeof c=="object"&&c!==null&&!Array.isArray(c)&&this.checkForEmbeddedTypeViolations(`${e}.${a}[${i}]`,c,r,n+1)}else this.checkForEmbeddedTypeViolations(`${e}.${a}`,s,r,n+1)}}};var se=class{ruleName="ImportExistence";async validateAsync(e,t){let r=[];if(!e.metadata?.imports)return r;let n=await t.getAllDocumentsAsync();for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!await t.getHighestCompatibleVersionAsync(o,a)){let c=await this.determineImportErrorAsync(t,o,a,n),p=new b;p.ruleType=this.ruleName,p.severity="Error",p.message=c.message,p.suggestion=c.suggestion,p.entityName=`Import: ${o}/${a.packageName}`,p.actualValue=a.toString(),p.expectedValue=c.expectedValue,r.push(p)}return r}async determineImportErrorAsync(e,t,r,n){let o=await e.getDocumentsByNamespaceAsync(t,r.packageName);if(o.length===0){let c=n.filter(m=>m.metadata.namespace_?.publisher===t).map(m=>m.metadata.namespace_.package_).filter((m,f,d)=>d.indexOf(m)===f),p=this.findSimilarPackages(r.packageName,c),u=`Import '${t}/${r.package_}' not found - package does not exist`,y=p.length>0?`Did you mean: ${p.slice(0,3).join(", ")}?`:c.length>0?`Available packages in ${t}: ${c.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:u,suggestion:y,expectedValue:"Existing package"}}let a=o.filter(c=>c.metadata.namespace_?.version).map(c=>c.metadata.namespace_.version.toString()).sort().join(", "),i=this.getAcceptableVersionRange(r);return{message:`Import '${t}/${r.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${i}`,expectedValue:i}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let r=t.filter(s=>s.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(s.toLowerCase()));if(r.length>0)return r.sort((s,a)=>s.length-a.length);let n=t.map(s=>({package:s,distance:this.levenshteinDistance(e.toLowerCase(),s.toLowerCase())})).sort((s,a)=>s.distance-a.distance),o=Math.max(3,Math.floor(e.length*.4));return n.filter(s=>s.distance<=o).map(s=>s.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let r=e.length,n=t.length,o=Array(r+1).fill(null).map(()=>Array(n+1).fill(0));for(let s=0;s<=r;s++)o[s][0]=s;for(let s=0;s<=n;s++)o[0][s]=s;for(let s=1;s<=r;s++)for(let a=1;a<=n;a++){let i=e[s-1]===t[a-1]?0:1;o[s][a]=Math.min(Math.min(o[s-1][a]+1,o[s][a-1]+1),o[s-1][a-1]+i)}return o[r][n]}};var ae=class{ruleName="UnresolvedReference";async validateAsync(e,t){let r=[],n=new $(t),o=await n.buildEntityIndexAsync(e),s=new Set;for(let[a,i]of o.entries()){let c=i.entity.type;if(c){let p=c.toString();(p==="ObjectProperty"||p.endsWith(".ObjectProperty"))&&s.add(a)}}for(let[a,i]of Object.entries(e.body)){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,p=this.getPropertyValue(c,"type");if(!(!p||p==="Class"||p.endsWith("Property")||p==="AnnotationProperty"))for(let[u,y]of Object.entries(c))u==="type"||u==="label"||u==="comment"||!(s.has(u)||Array.from(s).some(f=>f.endsWith(`.${u}`)))||await this.validateReferenceValue(a,u,y,e,n,r)}return r}async validateReferenceValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string")await o.resolveEntityAsync(r,n)||s.push(this.createUnresolvedReferenceError(e,t,r));else if(Array.isArray(r))for(let a=0;a<r.length;a++){let i=r[a];typeof i=="string"&&(await o.resolveEntityAsync(i,n)||s.push(this.createUnresolvedReferenceError(e,`${t}[${a}]`,i)))}}}createUnresolvedReferenceError(e,t,r){let n=`The entity '${r}' cannot be found in the current document or any imported namespaces.
10
+ Example: If the parent property is 'hasCharacter' with range 'Character', all embedded objects in that property will be typed as 'Character' automatically.`,p.expectedValue="No explicit type (inferred from parent property's range)",r.push(p)}if(typeof s=="object"&&s!==null)if(Array.isArray(s))for(let i=0;i<s.length;i++){let c=s[i];typeof c=="object"&&c!==null&&!Array.isArray(c)&&this.checkForEmbeddedTypeViolations(`${e}.${a}[${i}]`,c,r,n+1)}else this.checkForEmbeddedTypeViolations(`${e}.${a}`,s,r,n+1)}}};var pe=class{ruleName="ImportExistence";async validateAsync(e,t){let r=[];if(!e.metadata?.imports)return r;let n=await t.getAllDocumentsAsync();for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s)if(!await t.getHighestCompatibleVersionAsync(o,a)){let c=await this.determineImportErrorAsync(t,o,a,n),p=new b;p.ruleType=this.ruleName,p.severity="Error",p.message=c.message,p.suggestion=c.suggestion,p.entityName=`Import: ${o}/${a.packageName}`,p.actualValue=a.toString(),p.expectedValue=c.expectedValue,r.push(p)}return r}async determineImportErrorAsync(e,t,r,n){let o=await e.getDocumentsByNamespaceAsync(t,r.packageName);if(o.length===0){let c=n.filter(m=>m.metadata.namespace_?.publisher===t).map(m=>m.metadata.namespace_.package_).filter((m,f,d)=>d.indexOf(m)===f),p=this.findSimilarPackages(r.packageName,c),u=`Import '${t}/${r.package_}' not found - package does not exist`,y=p.length>0?`Did you mean: ${p.slice(0,3).join(", ")}?`:c.length>0?`Available packages in ${t}: ${c.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:u,suggestion:y,expectedValue:"Existing package"}}let a=o.filter(c=>c.metadata.namespace_?.version).map(c=>c.metadata.namespace_.version.toString()).sort().join(", "),i=this.getAcceptableVersionRange(r);return{message:`Import '${t}/${r.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${a}. Required: ${i}`,expectedValue:i}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let r=t.filter(s=>s.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(s.toLowerCase()));if(r.length>0)return r.sort((s,a)=>s.length-a.length);let n=t.map(s=>({package:s,distance:this.levenshteinDistance(e.toLowerCase(),s.toLowerCase())})).sort((s,a)=>s.distance-a.distance),o=Math.max(3,Math.floor(e.length*.4));return n.filter(s=>s.distance<=o).map(s=>s.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let r=e.length,n=t.length,o=Array(r+1).fill(null).map(()=>Array(n+1).fill(0));for(let s=0;s<=r;s++)o[s][0]=s;for(let s=0;s<=n;s++)o[0][s]=s;for(let s=1;s<=r;s++)for(let a=1;a<=n;a++){let i=e[s-1]===t[a-1]?0:1;o[s][a]=Math.min(Math.min(o[s-1][a]+1,o[s][a-1]+1),o[s-1][a-1]+i)}return o[r][n]}};var le=class{ruleName="UnresolvedReference";async validateAsync(e,t){let r=[],n=new V(t),o=await n.buildEntityIndexAsync(e),s=new Set;for(let[a,i]of o.entries()){let c=i.entity.type;if(c){let p=c.toString();(p==="ObjectProperty"||p.endsWith(".ObjectProperty"))&&s.add(a)}}for(let[a,i]of Object.entries(e.body)){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,p=this.getPropertyValue(c,"type");if(!(!p||p==="Class"||p.endsWith("Property")||p==="AnnotationProperty"))for(let[u,y]of Object.entries(c))u==="type"||u==="label"||u==="comment"||!(s.has(u)||Array.from(s).some(f=>f.endsWith(`.${u}`)))||await this.validateReferenceValue(a,u,y,e,n,r)}return r}async validateReferenceValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string")await o.resolveEntityAsync(r,n)||s.push(this.createUnresolvedReferenceError(e,t,r));else if(Array.isArray(r))for(let a=0;a<r.length;a++){let i=r[a];typeof i=="string"&&(await o.resolveEntityAsync(i,n)||s.push(this.createUnresolvedReferenceError(e,`${t}[${a}]`,i)))}}}createUnresolvedReferenceError(e,t,r){let n=`The entity '${r}' cannot be found in the current document or any imported namespaces.
11
11
 
12
12
  Possible solutions:
13
13
  \u2022 Add import if the entity is defined in another namespace:
14
14
  kanonak namespace add-import <publisher>/<package>@<version>
15
15
  \u2022 Check for typos in the reference name '${r}'
16
16
  \u2022 Define '${r}' in the current namespace or an appropriate namespace
17
- \u2022 Use 'kanonak search type ${r} --include-imports' to locate the entity`,o=new b;return o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=t,o.actualValue=r,o.message=`Reference to '${r}' could not be resolved`,o.suggestion=n,o.expectedValue="A valid entity reference that exists in the current document or imported namespaces",o}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}};var ie=class{ruleName="TypeAmbiguity";async validateAsync(e,t){let r=[],n=new Map,o=[];if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);if(c){o.push({doc:c,import:i,publisher:s});let p=await this.getTransitiveImportsAsync(t,c,new Set);o.push(...p.map(u=>({doc:u,import:null,publisher:s})))}}for(let{doc:s,import:a}of o){let i=s.metadata?.namespace_?.toString()??"unknown";for(let c of Object.keys(s.body))n.has(c)||n.set(c,[]),n.get(c).push({namespace:i,import:a})}for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a;this.checkAmbiguousReference(i,"type",n,s,r),this.checkAmbiguousReference(i,"subClassOf",n,s,r),this.checkAmbiguousReference(i,"subPropertyOf",n,s,r),this.checkAmbiguousReference(i,"domain",n,s,r),this.checkAmbiguousReference(i,"range",n,s,r)}return r}checkAmbiguousReference(e,t,r,n,o){let s=e[t];if(!s)return;let a=D(s);for(let i of a){if(i.includes("."))continue;let c=r.get(i);if(c&&c.length>1){let p=c.map(f=>f.namespace).join(", "),u=[];for(let{namespace:f,import:d}of c)if(d?.alias)u.push(`${d.alias}.${i}`);else{let g=f.split("/"),k=g[g.length-1]?.split("@")[0]??"alias";u.push(`${k}.${i}`)}let y=u.length>0?`Use one of: ${u.join(", ")}`:"Consider adding namespace aliases to your imports",m=new b;m.ruleType=this.ruleName,m.severity="Warning",m.entityName=n,m.propertyName=t,m.actualValue=i,m.message=`Type '${i}' is ambiguous. It's defined in: ${p}`,m.suggestion=y,o.push(m)}}}async getTransitiveImportsAsync(e,t,r){let n=[],o=t.metadata?.namespace_?.toString()??"";if(r.has(o))return n;if(r.add(o),t.metadata?.imports)for(let[s,a]of Object.entries(t.metadata.imports))for(let i of a){let c=await e.getHighestCompatibleVersionAsync(s,i);if(c){n.push(c);let p=await this.getTransitiveImportsAsync(e,c,r);n.push(...p)}}return n}};var ce=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildClassHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,c=i.type,p=i.subClassOf;if(c?.toString()==="Class"&&p){let u=s,y=this.detectCycle(u,n);if(y){let m=y.join(" \u2192 "),f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Circular class hierarchy detected: ${m}`,f.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",f.entityName=u,f.propertyName="subClassOf",f.actualValue=m,r.push(f);break}}}return r}async buildClassHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,c=i.type,p=i.subClassOf;if(c?.toString()==="Class"&&p){let u=D(p);u.length>0&&r.set(s,u)}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);c&&await this.buildClassHierarchy(c,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var pe=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildPropertyHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&a.subPropertyOf){let p=s,u=this.detectCycle(p,n);if(u){let y=u.join(" \u2192 "),m=new b;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${y}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=p,m.propertyName="subPropertyOf",m.actualValue=y,r.push(m);break}}return r}async buildPropertyHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,c=i.type;if(c){let p=c.toString();if(p==="DatatypeProperty"||p==="ObjectProperty"||p==="AnnotationProperty"){let u=i.subPropertyOf;if(u){let y=D(u);y.length>0&&r.set(s,y)}}}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);c&&await this.buildPropertyHierarchy(c,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var le=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,t){let r=[];for(let[n,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o))continue;let s=o,a=s.type?.toString();if(a==="DatatypeProperty"||a==="ObjectProperty"||a?.endsWith(".DatatypeProperty")||a?.endsWith(".ObjectProperty")){let i="range"in s,c=s.range?.toString().trim();if(!i||!c){let p=new b;p.ruleType=this.ruleName,p.severity="Error",p.entityName=n,p.propertyName="range",p.message=`Property '${n}' must have a 'range' defined.`,p.suggestion=a==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",p.expectedValue=a==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",r.push(p)}}}return r}};var ue=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();(i==="Class"||i&&i.endsWith(".Class"))&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=D(s.subClassOf);for(let c=0;c<i.length;c++){let p=i[c];if(this.builtInClasses.has(p)||n.has(p))continue;if(!await this.isClassAvailableInImports(e,t,p)){let y=i.length>1?`[${c}]`:"",m=new b;m.ruleType=this.ruleName,m.severity="Error",m.message=`Class '${p}' referenced in subClassOf${y} is not defined or imported`,m.suggestion=`Define '${p}' as a Class, or import a namespace that contains it`,m.entityName=o,m.propertyName="subClassOf",m.actualValue=p,m.expectedValue="Defined or imported class",r.push(m)}}}return r}async isClassAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let 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(f==="Class"||f&&f.endsWith(".Class"))return!0}let y=new Set;if(await this.isClassAvailableInImportsRecursive(c,t,p,y))return!0}}return!1}async isClassAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(y==="Class"||y&&y.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var ye=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();(i==="DatatypeProperty"||i==="ObjectProperty"||i==="AnnotationProperty")&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=D(s.subPropertyOf);for(let c=0;c<i.length;c++){let p=i[c];if(this.builtInProperties.has(p)||n.has(p))continue;if(!await this.isPropertyAvailableInImports(e,t,p)){let y=i.length>1?`[${c}]`:"",m=new b;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${p}' referenced in subPropertyOf${y} is not defined or imported`,m.suggestion=`Define '${p}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,m.entityName=o,m.propertyName="subPropertyOf",m.actualValue=p,m.expectedValue="Defined or imported property",r.push(m)}}}return r}async isPropertyAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let 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(f==="DatatypeProperty"||f==="ObjectProperty"||f==="AnnotationProperty")return!0}let y=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,t,p,y))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var me=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let r=[],n=e.metadata.namespace_?.toString();if(!n)return r;let o=new Map,s=new Set;await this.buildImportGraph(e,t,o,s);let a=this.detectCycle(n,o);if(a){let i=a.join(" \u2192 "),c=new b;c.ruleType=this.ruleName,c.severity="Error",c.message=`Circular namespace import detected: ${i}`,c.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",c.entityName="imports",c.propertyName="imports",c.actualValue=i,r.push(c)}return r}async buildImportGraph(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!(!o||n.has(o))&&(n.add(o),e.metadata.imports)){let s=[];for(let[a,i]of Object.entries(e.metadata.imports))for(let c of i){let p=`${a}/${c.packageName}@${c.version}`;s.push(p);let u=await t.getHighestCompatibleVersionAsync(a,c);u&&await this.buildImportGraph(u,t,r,n)}s.length>0&&r.set(o,s)}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){let o=r.indexOf(e);if(o>=0){let a=r.slice(o);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let s=t.get(e);if(s)for(let a of s){let i=this.detectCycleRecursive(a,t,r,n);if(i)return i}return r.pop(),null}};var fe=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();this.isPropertyType(i)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,i=a.type?.toString();if(this.isPropertyType(i)||this.isClassType(i))continue;for(let[c,p]of Object.entries(a)){if(!c||this.metadataKeys.has(c))continue;let u=c,y=null;if(c.includes(".")){let f=c.lastIndexOf(".");y=c.substring(0,f),u=c.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,y)){let f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${c}' is not defined or imported`,f.suggestion=y?`The property '${u}' is not found in the imported namespace with alias '${y}'.
17
+ \u2022 Use 'kanonak search type ${r} --include-imports' to locate the entity`,o=new b;return o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=t,o.actualValue=r,o.message=`Reference to '${r}' could not be resolved`,o.suggestion=n,o.expectedValue="A valid entity reference that exists in the current document or imported namespaces",o}getPropertyValue(e,t){let r=e[t];return r?r.toString():null}};var ue=class{ruleName="TypeAmbiguity";async validateAsync(e,t){let r=[],n=new Map,o=[];if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);if(c){o.push({doc:c,import:i,publisher:s});let p=await this.getTransitiveImportsAsync(t,c,new Set);o.push(...p.map(u=>({doc:u,import:null,publisher:s})))}}for(let{doc:s,import:a}of o){let i=s.metadata?.namespace_?.toString()??"unknown";for(let c of Object.keys(s.body))n.has(c)||n.set(c,[]),n.get(c).push({namespace:i,import:a})}for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a;this.checkAmbiguousReference(i,"type",n,s,r),this.checkAmbiguousReference(i,"subClassOf",n,s,r),this.checkAmbiguousReference(i,"subPropertyOf",n,s,r),this.checkAmbiguousReference(i,"domain",n,s,r),this.checkAmbiguousReference(i,"range",n,s,r)}return r}checkAmbiguousReference(e,t,r,n,o){let s=e[t];if(!s)return;let a=D(s);for(let i of a){if(i.includes("."))continue;let c=r.get(i);if(c&&c.length>1){let p=c.map(f=>f.namespace).join(", "),u=[];for(let{namespace:f,import:d}of c)if(d?.alias)u.push(`${d.alias}.${i}`);else{let g=f.split("/"),k=g[g.length-1]?.split("@")[0]??"alias";u.push(`${k}.${i}`)}let y=u.length>0?`Use one of: ${u.join(", ")}`:"Consider adding namespace aliases to your imports",m=new b;m.ruleType=this.ruleName,m.severity="Warning",m.entityName=n,m.propertyName=t,m.actualValue=i,m.message=`Type '${i}' is ambiguous. It's defined in: ${p}`,m.suggestion=y,o.push(m)}}}async getTransitiveImportsAsync(e,t,r){let n=[],o=t.metadata?.namespace_?.toString()??"";if(r.has(o))return n;if(r.add(o),t.metadata?.imports)for(let[s,a]of Object.entries(t.metadata.imports))for(let i of a){let c=await e.getHighestCompatibleVersionAsync(s,i);if(c){n.push(c);let p=await this.getTransitiveImportsAsync(e,c,r);n.push(...p)}}return n}};var ye=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildClassHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,c=i.type,p=i.subClassOf;if(c?.toString()==="Class"&&p){let u=s,y=this.detectCycle(u,n);if(y){let m=y.join(" \u2192 "),f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Circular class hierarchy detected: ${m}`,f.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",f.entityName=u,f.propertyName="subClassOf",f.actualValue=m,r.push(f);break}}}return r}async buildClassHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,c=i.type,p=i.subClassOf;if(c?.toString()==="Class"&&p){let u=D(p);u.length>0&&r.set(s,u)}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);c&&await this.buildClassHierarchy(c,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var me=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t){let r=[],n=new Map,o=new Set;await this.buildPropertyHierarchy(e,t,n,o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)&&a.subPropertyOf){let p=s,u=this.detectCycle(p,n);if(u){let y=u.join(" \u2192 "),m=new b;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${y}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=p,m.propertyName="subPropertyOf",m.actualValue=y,r.push(m);break}}return r}async buildPropertyHierarchy(e,t,r,n){let o=e.metadata?.namespace_?.toString()??"";if(!(o&&n.has(o))){o&&n.add(o);for(let[s,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,c=i.type;if(c){let p=c.toString();if(p==="DatatypeProperty"||p==="ObjectProperty"||p==="AnnotationProperty"){let u=i.subPropertyOf;if(u){let y=D(u);y.length>0&&r.set(s,y)}}}}if(e.metadata?.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await t.getHighestCompatibleVersionAsync(s,i);c&&await this.buildPropertyHierarchy(c,t,r,n)}}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){if(r.includes(e)){let s=r.indexOf(e),a=r.slice(s);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let o=t.get(e);if(o)for(let s of o){let a=this.detectCycleRecursive(s,t,r,n);if(a)return a}return r.pop(),null}};var fe=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,t){let r=[];for(let[n,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o))continue;let s=o,a=s.type?.toString();if(a==="DatatypeProperty"||a==="ObjectProperty"||a?.endsWith(".DatatypeProperty")||a?.endsWith(".ObjectProperty")){let i="range"in s,c=s.range?.toString().trim();if(!i||!c){let p=new b;p.ruleType=this.ruleName,p.severity="Error",p.entityName=n,p.propertyName="range",p.message=`Property '${n}' must have a 'range' defined.`,p.suggestion=a==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",p.expectedValue=a==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",r.push(p)}}}return r}};var de=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();(i==="Class"||i&&i.endsWith(".Class"))&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=D(s.subClassOf);for(let c=0;c<i.length;c++){let p=i[c];if(this.builtInClasses.has(p)||n.has(p))continue;if(!await this.isClassAvailableInImports(e,t,p)){let y=i.length>1?`[${c}]`:"",m=new b;m.ruleType=this.ruleName,m.severity="Error",m.message=`Class '${p}' referenced in subClassOf${y} is not defined or imported`,m.suggestion=`Define '${p}' as a Class, or import a namespace that contains it`,m.entityName=o,m.propertyName="subClassOf",m.actualValue=p,m.expectedValue="Defined or imported class",r.push(m)}}}return r}async isClassAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let 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(f==="Class"||f&&f.endsWith(".Class"))return!0}let y=new Set;if(await this.isClassAvailableInImportsRecursive(c,t,p,y))return!0}}return!1}async isClassAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(y==="Class"||y&&y.endsWith(".Class"))return!0}if(await this.isClassAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var ge=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();(i==="DatatypeProperty"||i==="ObjectProperty"||i==="AnnotationProperty")&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=D(s.subPropertyOf);for(let c=0;c<i.length;c++){let p=i[c];if(this.builtInProperties.has(p)||n.has(p))continue;if(!await this.isPropertyAvailableInImports(e,t,p)){let y=i.length>1?`[${c}]`:"",m=new b;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${p}' referenced in subPropertyOf${y} is not defined or imported`,m.suggestion=`Define '${p}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,m.entityName=o,m.propertyName="subPropertyOf",m.actualValue=p,m.expectedValue="Defined or imported property",r.push(m)}}}return r}async isPropertyAvailableInImports(e,t,r){if(!e.metadata.imports)return!1;let n=null,o=r;if(r.includes(".")){let s=r.split(".",2);n=s[0],o=s[1]}for(let[s,a]of Object.entries(e.metadata.imports))for(let 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(f==="DatatypeProperty"||f==="ObjectProperty"||f==="AnnotationProperty")return!0}let y=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,t,p,y))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var he=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let r=[],n=e.metadata.namespace_?.toString();if(!n)return r;let o=new Map,s=new Set;await this.buildImportGraph(e,t,o,s);let a=this.detectCycle(n,o);if(a){let i=a.join(" \u2192 "),c=new b;c.ruleType=this.ruleName,c.severity="Error",c.message=`Circular namespace import detected: ${i}`,c.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",c.entityName="imports",c.propertyName="imports",c.actualValue=i,r.push(c)}return r}async buildImportGraph(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!(!o||n.has(o))&&(n.add(o),e.metadata.imports)){let s=[];for(let[a,i]of Object.entries(e.metadata.imports))for(let c of i){let p=`${a}/${c.packageName}@${c.version}`;s.push(p);let u=await t.getHighestCompatibleVersionAsync(a,c);u&&await this.buildImportGraph(u,t,r,n)}s.length>0&&r.set(o,s)}}detectCycle(e,t){let r=[],n=new Set;return this.detectCycleRecursive(e,t,r,n)}detectCycleRecursive(e,t,r,n){let o=r.indexOf(e);if(o>=0){let a=r.slice(o);return a.push(e),a}if(n.has(e))return null;r.push(e),n.add(e);let s=t.get(e);if(s)for(let a of s){let i=this.detectCycleRecursive(a,t,r,n);if(i)return i}return r.pop(),null}};var ke=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();this.isPropertyType(i)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,i=a.type?.toString();if(this.isPropertyType(i)||this.isClassType(i))continue;for(let[c,p]of Object.entries(a)){if(!c||this.metadataKeys.has(c))continue;let u=c,y=null;if(c.includes(".")){let f=c.lastIndexOf(".");y=c.substring(0,f),u=c.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,y)){let f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${c}' is not defined or imported`,f.suggestion=y?`The property '${u}' is not found in the imported namespace with alias '${y}'.
18
18
  1. Verify the namespace is imported with the correct alias
19
19
  2. Check if the property name is spelled correctly
20
20
  3. Ensure the imported namespace version contains this property`:`The property '${c}' is not defined in this namespace or any imported namespace.
21
21
  1. Define '${c}' as an ObjectProperty or DatatypeProperty in this namespace, OR
22
22
  2. Import the namespace that contains '${c}', OR
23
- 3. Use a qualified reference like 'alias.${c}' if already imported with an alias`,f.entityName=o,f.propertyName=c,f.actualValue=p?.toString(),f.expectedValue="A defined or imported property",r.push(f)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let i=await t.getHighestCompatibleVersionAsync(o,a);if(i){let c=i.body[r];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}let p=new Set;if(await this.isPropertyAvailableInImportsRecursive(i,t,r,p))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var de=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();this.isPropertyType(i)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,i=a.type?.toString();if(!this.isPropertyType(i)&&!this.isClassType(i))continue;for(let[c,p]of Object.entries(a)){if(!c||this.metadataKeys.has(c))continue;let u=c,y=null;if(c.includes(".")){let f=c.lastIndexOf(".");y=c.substring(0,f),u=c.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,y)){let f=this.isClassType(i)?"class":"property",d=new b;d.ruleType=this.ruleName,d.severity="Error",d.message=`Property '${c}' used on ${f} '${o}' is not defined or imported`,d.suggestion=y?`The property '${u}' is not found in the imported namespace with alias '${y}'.
23
+ 3. Use a qualified reference like 'alias.${c}' if already imported with an alias`,f.entityName=o,f.propertyName=c,f.actualValue=p?.toString(),f.expectedValue="A defined or imported property",r.push(f)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let i=await t.getHighestCompatibleVersionAsync(o,a);if(i){let c=i.body[r];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}let p=new Set;if(await this.isPropertyAvailableInImportsRecursive(i,t,r,p))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var be=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();this.isPropertyType(i)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,i=a.type?.toString();if(!this.isPropertyType(i)&&!this.isClassType(i))continue;for(let[c,p]of Object.entries(a)){if(!c||this.metadataKeys.has(c))continue;let u=c,y=null;if(c.includes(".")){let f=c.lastIndexOf(".");y=c.substring(0,f),u=c.substring(f+1)}if(n.has(u))continue;if(!await this.isPropertyAvailableInImports(e,t,u,y)){let f=this.isClassType(i)?"class":"property",d=new b;d.ruleType=this.ruleName,d.severity="Error",d.message=`Property '${c}' used on ${f} '${o}' is not defined or imported`,d.suggestion=y?`The property '${u}' is not found in the imported namespace with alias '${y}'.
24
24
  1. Verify the namespace is imported with the correct alias
25
25
  2. Check if the property name is spelled correctly
26
26
  3. Ensure the imported namespace version contains this property`:`The property '${c}' is not defined in this namespace or any imported namespace.
27
27
  1. Define '${c}' as an ObjectProperty or DatatypeProperty in this namespace, OR
28
28
  2. Import the namespace that contains '${c}', OR
29
- 3. Use a qualified reference like 'alias.${c}' if already imported with an alias`,d.entityName=o,d.propertyName=c,d.actualValue=p?.toString(),d.expectedValue="A defined or imported property",r.push(d)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let i=await t.getHighestCompatibleVersionAsync(o,a);if(i){let c=i.body[r];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}let p=new Set;if(await this.isPropertyAvailableInImportsRecursive(i,t,r,p))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var ge=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,t){let r=[],n=new Set,o=[];for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=!1,p=i.type;if(Array.isArray(p)){for(let u of p)if(u?.toString()==="DatatypeProperty"){c=!0;break}}else p?.toString()==="DatatypeProperty"&&(c=!0);if(c){o.push(s);let u=this.getPropertyValue(i,"range");u&&this.xsdTypes.has(u)&&n.add(u)}}if(n.size>0&&!await this.checkXsdImportAsync(e.metadata,t)){let a=Array.from(n).sort().join(", "),i=o.sort().join(", "),c=new b;c.ruleType=this.ruleName,c.severity="Error",c.message=`XSD namespace not imported but XSD types are used: ${a}`,c.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${i}`,c.entityName="imports",r.push(c)}return r}async checkXsdImportAsync(e,t,r=new Set){if(!e?.imports)return!1;let n=e.namespace_?.toString()??"";if(n&&r.has(n))return!1;n&&r.add(n);for(let[,o]of Object.entries(e.imports))for(let s of o)if(s.packageName==="xsd"||s.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[o,s]of Object.entries(e.imports))for(let a of s){let i=await t.getHighestCompatibleVersionAsync(o,a);if(i?.metadata&&await this.checkXsdImportAsync(i.metadata,t,r))return!0}return!1}getPropertyValue(e,t){return e[t]?.toString()}};var he=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,t){let r=[],n=await this.buildEntitySourceMapAsync(e,t);for(let[o,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&this.validateEntityReferences(o,s,n,e,r);return r}async buildEntitySourceMapAsync(e,t){let r=new Map,n=new Set;for(let o of Object.keys(e.body)){let s=e.metadata.namespace_?.toString()??"";r.has(o)||r.set(o,[]),r.get(o).push(`(local:${s})`)}if(e.metadata.imports)for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){let i=await t.getHighestCompatibleVersionAsync(o,a);i&&await this.collectEntitiesRecursivelyAsync(i,r,n,t)}return r}async collectEntitiesRecursivelyAsync(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!r.has(o)){r.add(o);for(let s of Object.keys(e.body)){t.has(s)||t.set(s,[]);let a=t.get(s);a.includes(o)||a.push(o)}if(e.metadata.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await n.getHighestCompatibleVersionAsync(s,i);c&&await this.collectEntitiesRecursivelyAsync(c,t,r,n)}}}validateEntityReferences(e,t,r,n,o){for(let[s,a]of Object.entries(t)){let i=s;if(i&&!i.includes(".")){let c=r.get(i);if(c&&c.length>1&&!c.some(u=>u.startsWith("(local:"))){let u=c.filter(y=>!y.startsWith("(local:"));u.length>1&&o.push(this.createAmbiguityError(e,i,`Property '${i}'`,u,n,!0,i))}}this.validatePropertyValue(e,i,a,r,n,o)}}validatePropertyValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string"&&!r.includes(".")){let a=n.get(r);if(a&&a.length>1&&!a.some(c=>c.startsWith("(local:"))){let c=a.filter(p=>!p.startsWith("(local:"));c.length>1&&s.push(this.createAmbiguityError(e,t,`Reference '${r}'`,c,o,!1,r))}}else if(Array.isArray(r))for(let a=0;a<r.length;a++){let i=`${e}.${t}[${a}]`;this.validatePropertyValue(i,null,r[a],n,o,s)}else if(typeof r=="object"&&!Array.isArray(r)){let a=t?`${e}.${t}`:e;this.validateEntityReferences(a,r,n,o,s)}}}createAmbiguityError(e,t,r,n,o,s,a){let i=[];for(let d of n){let g=this.findAliasForNamespace(o,d);if(g){let h=t?.split(".").pop()??t;i.push(`${g}.${h}`)}}let c=i.length>0?`Use one of: ${i.map(d=>`'${d}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${t}')`,p=n.map(d=>` \u2022 ${d}`).join(`
29
+ 3. Use a qualified reference like 'alias.${c}' if already imported with an alias`,d.entityName=o,d.propertyName=c,d.actualValue=p?.toString(),d.expectedValue="A defined or imported property",r.push(d)}}}return r}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,t,r,n){if(!e.metadata.imports)return!1;for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){if(n!==null&&a.alias!==n)continue;let i=await t.getHighestCompatibleVersionAsync(o,a);if(i){let c=i.body[r];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}let p=new Set;if(await this.isPropertyAvailableInImportsRecursive(i,t,r,p))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(o&&n.has(o)||(o&&n.add(o),!e.metadata.imports))return!1;for(let[s,a]of Object.entries(e.metadata.imports))for(let 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 y=p.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(c,t,r,n))return!0}}return!1}};var Re=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,t){let r=[],n=new Set,o=[];for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=!1,p=i.type;if(Array.isArray(p)){for(let u of p)if(u?.toString()==="DatatypeProperty"){c=!0;break}}else p?.toString()==="DatatypeProperty"&&(c=!0);if(c){o.push(s);let u=this.getPropertyValue(i,"range");u&&this.xsdTypes.has(u)&&n.add(u)}}if(n.size>0&&!await this.checkXsdImportAsync(e.metadata,t)){let a=Array.from(n).sort().join(", "),i=o.sort().join(", "),c=new b;c.ruleType=this.ruleName,c.severity="Error",c.message=`XSD namespace not imported but XSD types are used: ${a}`,c.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${i}`,c.entityName="imports",r.push(c)}return r}async checkXsdImportAsync(e,t,r=new Set){if(!e?.imports)return!1;let n=e.namespace_?.toString()??"";if(n&&r.has(n))return!1;n&&r.add(n);for(let[,o]of Object.entries(e.imports))for(let s of o)if(s.packageName==="xsd"||s.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[o,s]of Object.entries(e.imports))for(let a of s){let i=await t.getHighestCompatibleVersionAsync(o,a);if(i?.metadata&&await this.checkXsdImportAsync(i.metadata,t,r))return!0}return!1}getPropertyValue(e,t){return e[t]?.toString()}};var Pe=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,t){let r=[],n=await this.buildEntitySourceMapAsync(e,t);for(let[o,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&this.validateEntityReferences(o,s,n,e,r);return r}async buildEntitySourceMapAsync(e,t){let r=new Map,n=new Set;for(let o of Object.keys(e.body)){let s=e.metadata.namespace_?.toString()??"";r.has(o)||r.set(o,[]),r.get(o).push(`(local:${s})`)}if(e.metadata.imports)for(let[o,s]of Object.entries(e.metadata.imports))for(let a of s){let i=await t.getHighestCompatibleVersionAsync(o,a);i&&await this.collectEntitiesRecursivelyAsync(i,r,n,t)}return r}async collectEntitiesRecursivelyAsync(e,t,r,n){let o=e.metadata.namespace_?.toString()??"";if(!r.has(o)){r.add(o);for(let s of Object.keys(e.body)){t.has(s)||t.set(s,[]);let a=t.get(s);a.includes(o)||a.push(o)}if(e.metadata.imports)for(let[s,a]of Object.entries(e.metadata.imports))for(let i of a){let c=await n.getHighestCompatibleVersionAsync(s,i);c&&await this.collectEntitiesRecursivelyAsync(c,t,r,n)}}}validateEntityReferences(e,t,r,n,o){for(let[s,a]of Object.entries(t)){let i=s;if(i&&!i.includes(".")){let c=r.get(i);if(c&&c.length>1&&!c.some(u=>u.startsWith("(local:"))){let u=c.filter(y=>!y.startsWith("(local:"));u.length>1&&o.push(this.createAmbiguityError(e,i,`Property '${i}'`,u,n,!0,i))}}this.validatePropertyValue(e,i,a,r,n,o)}}validatePropertyValue(e,t,r,n,o,s){if(r!=null){if(typeof r=="string"&&!r.includes(".")){let a=n.get(r);if(a&&a.length>1&&!a.some(c=>c.startsWith("(local:"))){let c=a.filter(p=>!p.startsWith("(local:"));c.length>1&&s.push(this.createAmbiguityError(e,t,`Reference '${r}'`,c,o,!1,r))}}else if(Array.isArray(r))for(let a=0;a<r.length;a++){let i=`${e}.${t}[${a}]`;this.validatePropertyValue(i,null,r[a],n,o,s)}else if(typeof r=="object"&&!Array.isArray(r)){let a=t?`${e}.${t}`:e;this.validateEntityReferences(a,r,n,o,s)}}}createAmbiguityError(e,t,r,n,o,s,a){let i=[];for(let d of n){let g=this.findAliasForNamespace(o,d);if(g){let h=t?.split(".").pop()??t;i.push(`${g}.${h}`)}}let c=i.length>0?`Use one of: ${i.map(d=>`'${d}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${t}')`,p=n.map(d=>` \u2022 ${d}`).join(`
30
30
  `),u=e.split(".")[0],y=e.includes(".")?e:t,m=new b;m.ruleType=this.ruleName,m.severity="Error",m.entityName=u,y&&(m.propertyName=y);let f=a??t;return f&&(m.actualValue=f),m.message=`${r} is ambiguous - defined in multiple imported namespaces`,m.suggestion=`${c}
31
31
 
32
32
  Defined in:
33
- ${p}`,m.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",m}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(`${r}/${o.packageName}@${o.version}`===t&&o.alias)return o.alias;return null}};var be=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();this.isValidRangeTargetType(i)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,i=a.type?.toString();if(i!=="DatatypeProperty"&&i!=="ObjectProperty"&&!i?.endsWith(".DatatypeProperty")&&!i?.endsWith(".ObjectProperty"))continue;let c=a.range;if(!c)continue;let p=[];if(Array.isArray(c))for(let u of c){let y=u?.toString();y&&p.push(y)}else{let u=c?.toString();u&&p.push(u)}if(p.length===0)continue;for(let u of p){if(this.primitiveTypes.has(u)||this.builtInClasses.has(u)||n.has(u))continue;if(!await this.isTypeAvailableInImports(e,t,u)){let m=i?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${o}' has range '${u}' which is not defined or imported`,f.suggestion=m==="ObjectProperty"?`For ObjectProperty:
33
+ ${p}`,m.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",m}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n)if(`${r}/${o.packageName}@${o.version}`===t&&o.alias)return o.alias;return null}};var ve=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,t){let r=[],n=new Set;for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=s.type?.toString();this.isValidRangeTargetType(i)&&n.add(o)}for(let[o,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=s,i=a.type?.toString();if(i!=="DatatypeProperty"&&i!=="ObjectProperty"&&!i?.endsWith(".DatatypeProperty")&&!i?.endsWith(".ObjectProperty"))continue;let c=a.range;if(!c)continue;let p=[];if(Array.isArray(c))for(let u of c){let y=u?.toString();y&&p.push(y)}else{let u=c?.toString();u&&p.push(u)}if(p.length===0)continue;for(let u of p){if(this.primitiveTypes.has(u)||this.builtInClasses.has(u)||n.has(u))continue;if(!await this.isTypeAvailableInImports(e,t,u)){let m=i?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",f=new b;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${o}' has range '${u}' which is not defined or imported`,f.suggestion=m==="ObjectProperty"?`For ObjectProperty:
34
34
  1. Define '${u}' as a Class in this namespace, OR
35
35
  2. Import the namespace that contains '${u}', OR
36
36
  3. Use a qualified reference like 'alias.${u}' if already imported with an alias`:`For DatatypeProperty:
37
37
  1. Use a primitive type (string, integer, boolean, dateTime, etc.), OR
38
- 2. If '${u}' should be a class, change property type to ObjectProperty`,f.entityName=o,f.propertyName="range",f.actualValue=u,f.expectedValue=m==="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 y=new Set;if(await this.isTypeAvailableInImportsRecursive(c,t,p,y))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 y=p.type?.toString();if(this.isValidRangeTargetType(y))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 ke=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"ObjectPropertyImport"}async validateAsync(e,t){let r=[],n=new Map,o=new $(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,y=[];if(Array.isArray(u))for(let m of u){let f=m?.toString();f&&y.push(f)}else{let m=u?.toString();m&&y.push(m)}for(let m of y)this.xsdTypes.has(m)||(n.has(m)||n.set(m,[]),n.get(m).push(s))}}for(let[s,a]of n)if(!await o.resolveEntityAsync(s,e))for(let c of a){let p=new b;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 Re=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 $(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,y=c.lastIndexOf(".");y>0&&y<c.length-1&&(u=c.substring(y+1));let m=n.get(u);if(m&&s.isEffectiveObjectProperty(m.propertyType,m.rangeUri)){let d=r?`${r}.${c}`:c;if(typeof p=="string"&&p.trim().length>0){let g=p.trim();if(g.includes(",")){let k=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:
38
+ 2. If '${u}' should be a class, change property type to ObjectProperty`,f.entityName=o,f.propertyName="range",f.actualValue=u,f.expectedValue=m==="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 y=new Set;if(await this.isTypeAvailableInImportsRecursive(c,t,p,y))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 y=p.type?.toString();if(this.isValidRangeTargetType(y))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 we=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,y=[];if(Array.isArray(u))for(let m of u){let f=m?.toString();f&&y.push(f)}else{let m=u?.toString();m&&y.push(m)}for(let m of y)this.xsdTypes.has(m)||(n.has(m)||n.set(m,[]),n.get(m).push(s))}}for(let[s,a]of n)if(!await o.resolveEntityAsync(s,e))for(let c of a){let p=new b;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 Ie=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 X(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,y=c.lastIndexOf(".");y>0&&y<c.length-1&&(u=c.substring(y+1));let m=n.get(u);if(m&&s.isEffectiveObjectProperty(m.propertyType,m.rangeUri)){let d=r?`${r}.${c}`:c;if(typeof p=="string"&&p.trim().length>0){let g=p.trim();if(g.includes(",")){let k=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
39
  ${c}:
40
40
  - ${k[0]}
41
41
  ${k.slice(1).map(R=>` - ${R}`).join(`
42
- `)}`,entityName:t,propertyName:c,propertyPath:d,actualValue:g,expectedValue:`A single reference to ${m.range??"an entity"} OR a YAML list`});continue}let h=await o.resolveEntityAsync(g,a);if(h)m.range&&(await this.validateRangeType(h,m.range,o,a)||i.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${c}' expects a ${m.range}, but '${g}' may not be a ${m.range}`,suggestion:`Ensure '${g}' is defined with appropriate type`,entityName:t,propertyName:c,propertyPath:d,actualValue:g,expectedValue:m.range}));else{let k=m.range??"entity";i.push({ruleType:this.ruleName,severity:"Error",message:`Property '${c}' references '${g}' which is not defined or imported`,suggestion:`Define '${g}' or import a namespace that contains it. Expected range: ${k}`,entityName:t,propertyName:c,propertyPath:d,actualValue:g,expectedValue:"Defined or imported entity"})}}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let g=r?`${r}.${c}`:c;await this.scanEntityForObjectProperties(p,t,g,n,o,s,a,i)}else if(Array.isArray(p))for(let g=0;g<p.length;g++){let h=p[g];if(typeof h=="string"&&h.trim().length>0){let k=h.trim(),R=await o.resolveEntityAsync(k,a);if(R){if(m.range&&!await this.validateRangeType(R,m.range,o,a)){let A=r?`${r}.${c}[${g}]`:`${c}[${g}]`;i.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${c}' expects a ${m.range}, but '${k}' may not be a ${m.range}`,suggestion:`Ensure '${k}' is defined with appropriate type`,entityName:t,propertyName:`${c}[${g}]`,propertyPath:A,actualValue:k,expectedValue:m.range})}}else{let v=m.range??"entity",A=r?`${r}.${c}[${g}]`:`${c}[${g}]`;i.push({ruleType:this.ruleName,severity:"Error",message:`Property '${c}' references '${k}' which is not defined or imported`,suggestion:`Define '${k}' or import a namespace that contains it. Expected range: ${v}`,entityName:t,propertyName:`${c}[${g}]`,propertyPath:A,actualValue:k,expectedValue:"Defined or imported entity"})}}else if(typeof h=="object"&&h!==null&&!Array.isArray(h)){let k=r?`${r}.${c}[${g}]`:`${c}[${g}]`;await this.scanEntityForObjectProperties(h,t,k,n,o,s,a,i)}}}if(typeof p=="object"&&p!==null&&!Array.isArray(p)&&!n.has(c)){let f=r?`${r}.${c}`:c;await this.scanEntityForObjectProperties(p,t,f,n,o,s,a,i)}else if(Array.isArray(p))for(let f=0;f<p.length;f++){let d=p[f];if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let g=r?`${r}.${c}[${f}]`:`${c}[${f}]`;await this.scanEntityForObjectProperties(d,t,g,n,o,s,a,i)}}}}async validateRangeType(e,t,r,n){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(t))return!0;let s=e.entity.type;if(s){let a=[];if(Array.isArray(s))for(let i of s){let c=i?.toString();c&&c.trim().length>0&&a.push(c)}else{let i=s?.toString();i&&i.trim().length>0&&a.push(i)}for(let i of a){let c=i.includes(".")?i.split(".")[1]:i;if(c===t||t==="Property"&&(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty")||t==="Class"&&c==="Class"||await r.isSubclassOfAsync(i,t,n))return!0}}return!1}async buildPropertyMetadataAsync(e,t,r,n){let o=new Map;for(let[s,a]of n){let i=a.entity.type;if(i){let c=[];if(Array.isArray(i))for(let y of i){let m=y?.toString();m&&m.trim().length>0&&c.push(m)}else{let y=i?.toString();y&&y.trim().length>0&&c.push(y)}let p=!1,u="Property";for(let y of c){let m=y.includes(".")?y.split(".")[1]:y;if(m==="Property"||m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty"){p=!0,u=y;break}}if(p){let y={propertyType:u},m=a.entity.range;if(m){let f=m?.toString();if(f&&f.trim().length>0){y.range=f;let d=await r.resolveEntityAsync(f,e);d&&(y.rangeUri=d.uri)}}o.set(s,y)}}}return o}};var ve=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"PropertyDomain"}async validateAsync(e,t){let r=[],n=new Map;for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=this.getPropertyValue(i,"type");(c==="DatatypeProperty"||c?.endsWith(".DatatypeProperty")||c==="ObjectProperty"||c?.endsWith(".ObjectProperty")||c==="AnnotationProperty"||c?.endsWith(".AnnotationProperty"))&&n.set(s,i)}let o=await this.buildCompleteClassHierarchyAsync(e,t);for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=this.getPropertyValue(i,"type");if(!c||c==="Class"||c.endsWith(".Class")||c.endsWith("Property")||c==="AnnotationProperty")continue;this.validateEntityProperties(i,s,c,n,o,r)}return r}async buildCompleteClassHierarchyAsync(e,t){let r=new Map,n=new Set,o=async(a,i)=>{if(!n.has(i)){n.add(i);for(let[c,p]of Object.entries(a.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=p,y=this.getPropertyValue(u,"type");if(y==="Class"||y?.endsWith(".Class")){let m=u.subClassOf;if(m===void 0){for(let d of Object.keys(u))if(d.endsWith(".subClassOf")){m=u[d];break}}let f=D(m);f.length>0&&r.set(c,f)}}if(a.metadata.imports)for(let[c,p]of Object.entries(a.metadata.imports))for(let u of p)try{let y=await t.getHighestCompatibleVersionAsync(c,u);if(y){let m=`${c}/${u.packageName}@${u.version}`;await o(y,m)}}catch{}}},s=e.metadata.namespace_?.toString()??"unknown";return await o(e,s),r}validateEntityProperties(e,t,r,n,o,s){for(let[a,i]of Object.entries(e)){if(this.standardProperties.has(a))continue;let c=a,p=a.lastIndexOf(".");p>0&&p<a.length-1&&(c=a.substring(p+1));let u=n.get(c);if(!u)continue;let y=this.getPropertyValue(u,"domain");if(y){if(!this.isTypeCompatibleWithDomain(r,y,o)){let m=t.split(".")[0];s.push({ruleType:this.ruleName,severity:"Error",entityName:m,propertyName:t,actualValue:a,message:`Property '${a}' has domain '${y}' but is used on '${r}' at '${t}'`,suggestion:`Either:
42
+ `)}`,entityName:t,propertyName:c,propertyPath:d,actualValue:g,expectedValue:`A single reference to ${m.range??"an entity"} OR a YAML list`});continue}let h=await o.resolveEntityAsync(g,a);if(h)m.range&&(await this.validateRangeType(h,m.range,o,a)||i.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${c}' expects a ${m.range}, but '${g}' may not be a ${m.range}`,suggestion:`Ensure '${g}' is defined with appropriate type`,entityName:t,propertyName:c,propertyPath:d,actualValue:g,expectedValue:m.range}));else{let k=m.range??"entity";i.push({ruleType:this.ruleName,severity:"Error",message:`Property '${c}' references '${g}' which is not defined or imported`,suggestion:`Define '${g}' or import a namespace that contains it. Expected range: ${k}`,entityName:t,propertyName:c,propertyPath:d,actualValue:g,expectedValue:"Defined or imported entity"})}}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let g=r?`${r}.${c}`:c;await this.scanEntityForObjectProperties(p,t,g,n,o,s,a,i)}else if(Array.isArray(p))for(let g=0;g<p.length;g++){let h=p[g];if(typeof h=="string"&&h.trim().length>0){let k=h.trim(),R=await o.resolveEntityAsync(k,a);if(R){if(m.range&&!await this.validateRangeType(R,m.range,o,a)){let A=r?`${r}.${c}[${g}]`:`${c}[${g}]`;i.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${c}' expects a ${m.range}, but '${k}' may not be a ${m.range}`,suggestion:`Ensure '${k}' is defined with appropriate type`,entityName:t,propertyName:`${c}[${g}]`,propertyPath:A,actualValue:k,expectedValue:m.range})}}else{let P=m.range??"entity",A=r?`${r}.${c}[${g}]`:`${c}[${g}]`;i.push({ruleType:this.ruleName,severity:"Error",message:`Property '${c}' references '${k}' which is not defined or imported`,suggestion:`Define '${k}' or import a namespace that contains it. Expected range: ${P}`,entityName:t,propertyName:`${c}[${g}]`,propertyPath:A,actualValue:k,expectedValue:"Defined or imported entity"})}}else if(typeof h=="object"&&h!==null&&!Array.isArray(h)){let k=r?`${r}.${c}[${g}]`:`${c}[${g}]`;await this.scanEntityForObjectProperties(h,t,k,n,o,s,a,i)}}}if(typeof p=="object"&&p!==null&&!Array.isArray(p)&&!n.has(c)){let f=r?`${r}.${c}`:c;await this.scanEntityForObjectProperties(p,t,f,n,o,s,a,i)}else if(Array.isArray(p))for(let f=0;f<p.length;f++){let d=p[f];if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let g=r?`${r}.${c}[${f}]`:`${c}[${f}]`;await this.scanEntityForObjectProperties(d,t,g,n,o,s,a,i)}}}}async validateRangeType(e,t,r,n){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(t))return!0;let s=e.entity.type;if(s){let a=[];if(Array.isArray(s))for(let i of s){let c=i?.toString();c&&c.trim().length>0&&a.push(c)}else{let i=s?.toString();i&&i.trim().length>0&&a.push(i)}for(let i of a){let c=i.includes(".")?i.split(".")[1]:i;if(c===t||t==="Property"&&(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty")||t==="Class"&&c==="Class"||await r.isSubclassOfAsync(i,t,n))return!0}}return!1}async buildPropertyMetadataAsync(e,t,r,n){let o=new Map;for(let[s,a]of n){let i=a.entity.type;if(i){let c=[];if(Array.isArray(i))for(let y of i){let m=y?.toString();m&&m.trim().length>0&&c.push(m)}else{let y=i?.toString();y&&y.trim().length>0&&c.push(y)}let p=!1,u="Property";for(let y of c){let m=y.includes(".")?y.split(".")[1]:y;if(m==="Property"||m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty"){p=!0,u=y;break}}if(p){let y={propertyType:u},m=a.entity.range;if(m){let f=m?.toString();if(f&&f.trim().length>0){y.range=f;let d=await r.resolveEntityAsync(f,e);d&&(y.rangeUri=d.uri)}}o.set(s,y)}}}return o}};var Ae=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"PropertyDomain"}async validateAsync(e,t){let r=[],n=new Map;for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=this.getPropertyValue(i,"type");(c==="DatatypeProperty"||c?.endsWith(".DatatypeProperty")||c==="ObjectProperty"||c?.endsWith(".ObjectProperty")||c==="AnnotationProperty"||c?.endsWith(".AnnotationProperty"))&&n.set(s,i)}let o=await this.buildCompleteClassHierarchyAsync(e,t);for(let[s,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=a,c=this.getPropertyValue(i,"type");if(!c||c==="Class"||c.endsWith(".Class")||c.endsWith("Property")||c==="AnnotationProperty")continue;this.validateEntityProperties(i,s,c,n,o,r)}return r}async buildCompleteClassHierarchyAsync(e,t){let r=new Map,n=new Set,o=async(a,i)=>{if(!n.has(i)){n.add(i);for(let[c,p]of Object.entries(a.body))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let u=p,y=this.getPropertyValue(u,"type");if(y==="Class"||y?.endsWith(".Class")){let m=u.subClassOf;if(m===void 0){for(let d of Object.keys(u))if(d.endsWith(".subClassOf")){m=u[d];break}}let f=D(m);f.length>0&&r.set(c,f)}}if(a.metadata.imports)for(let[c,p]of Object.entries(a.metadata.imports))for(let u of p)try{let y=await t.getHighestCompatibleVersionAsync(c,u);if(y){let m=`${c}/${u.packageName}@${u.version}`;await o(y,m)}}catch{}}},s=e.metadata.namespace_?.toString()??"unknown";return await o(e,s),r}validateEntityProperties(e,t,r,n,o,s){for(let[a,i]of Object.entries(e)){if(this.standardProperties.has(a))continue;let c=a,p=a.lastIndexOf(".");p>0&&p<a.length-1&&(c=a.substring(p+1));let u=n.get(c);if(!u)continue;let y=this.getPropertyValue(u,"domain");if(y){if(!this.isTypeCompatibleWithDomain(r,y,o)){let m=t.split(".")[0];s.push({ruleType:this.ruleName,severity:"Error",entityName:m,propertyName:t,actualValue:a,message:`Property '${a}' has domain '${y}' but is used on '${r}' at '${t}'`,suggestion:`Either:
43
43
  1. Use this property only on '${y}' instances
44
44
  2. Change the property domain to include '${r}'
45
- 3. Create a different property for '${r}'`,expectedValue:`Property used on ${y} or its subclasses`})}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let m=i,f=this.getPropertyValue(m,"type");if(f){let d=`${t}.${a}`;this.validateEntityProperties(m,d,f,n,o,s)}else{let d=this.getPropertyValue(u,"range");if(d){let g=`${t}.${a}`;this.validateEntityProperties(m,g,d,n,o,s)}}}else if(Array.isArray(i))for(let m=0;m<i.length;m++){let f=i[m];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let d=f,g=this.getPropertyValue(d,"type");if(g){let h=`${t}.${a}[${m}]`;this.validateEntityProperties(d,h,g,n,o,s)}else{let h=this.getPropertyValue(u,"range");if(h){let k=`${t}.${a}[${m}]`;this.validateEntityProperties(d,k,h,n,o,s)}}}}}}}isTypeCompatibleWithDomain(e,t,r){if(e===t)return!0;let n=new Set,o=[e];for(;o.length>0;){let s=o.shift();if(n.has(s))continue;n.add(s);let a=r.get(s);if(a)for(let 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 Pe=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,y=c.lastIndexOf(".");y>0&&y<c.length-1&&(u=c.substring(y+1));let m=n.get(u);if(!m)continue;let f=this.getPropertyValue(m,"type"),d=this.getPropertyValue(m,"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:
45
+ 3. Create a different property for '${r}'`,expectedValue:`Property used on ${y} or its subclasses`})}if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let m=i,f=this.getPropertyValue(m,"type");if(f){let d=`${t}.${a}`;this.validateEntityProperties(m,d,f,n,o,s)}else{let d=this.getPropertyValue(u,"range");if(d){let g=`${t}.${a}`;this.validateEntityProperties(m,g,d,n,o,s)}}}else if(Array.isArray(i))for(let m=0;m<i.length;m++){let f=i[m];if(typeof f=="object"&&f!==null&&!Array.isArray(f)){let d=f,g=this.getPropertyValue(d,"type");if(g){let h=`${t}.${a}[${m}]`;this.validateEntityProperties(d,h,g,n,o,s)}else{let h=this.getPropertyValue(u,"range");if(h){let k=`${t}.${a}[${m}]`;this.validateEntityProperties(d,k,h,n,o,s)}}}}}}}isTypeCompatibleWithDomain(e,t,r){if(e===t)return!0;let n=new Set,o=[e];for(;o.length>0;){let s=o.shift();if(n.has(s))continue;n.add(s);let a=r.get(s);if(a)for(let 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 De=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,y=c.lastIndexOf(".");y>0&&y<c.length-1&&(u=c.substring(y+1));let m=n.get(u);if(!m)continue;let f=this.getPropertyValue(m,"type"),d=this.getPropertyValue(m,"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:
46
46
  1. Create a class for this data and change '${c}' to an ObjectProperty
47
47
  2. Store as a JSON string to keep it as DatatypeProperty
48
- 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 we=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 y=u?.toString();if(y==="Class"||y&&y.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 y of p){let m=y?.toString();if(m&&this.isDefinitionType(m)){u=!0;break}}if(!u)for(let y of p){let m=y?.toString();m&&m.trim().length>0&&(n.has(m)||n.set(m,[]),n.get(m).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 $(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 y 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:y,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 _e=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new O,this.documentRules=[new ee,new te,new re,new ne,new oe],this.repositoryRules=[new se,new ae,new ie,new ce,new pe,new le,new ue,new ye,new me,new fe,new de,new ge,new he,new be,new ke,new Re,new ve,new Pe,new we]}async validateAsync(e,t){let r=new Q;for(let n of this.documentRules)try{let o=n.validate(e);this.addErrorsToResult(r,o)}catch(o){let s=new b;s.ruleType=n.ruleName,s.severity="Error",s.message=`Validation rule '${n.ruleName}' failed: ${o instanceof Error?o.message:String(o)}`,r.errors.push(s)}if(t){let n=[];for(let o of this.repositoryRules)try{let s=await o.validateAsync(e,t);this.addErrorsToResult(r,s)}catch(s){let a=s instanceof Error?s.message:String(s);n.push({ruleName:o.ruleName,cause:a})}if(n.length>0){let o=new Map;for(let{ruleName:s,cause:a}of n){let i=o.get(a);i?i.push(s):o.set(a,[s])}for(let[s,a]of o){let i=new b;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 Q;n.isValid=!1;for(let o of r.errors){let s=new b;s.ruleType="ParseError",s.severity="Error",s.lineNumber=o.line,s.column=o.column,s.message=o.message,o.keyName&&(s.entityName=o.keyName),o.errorType==="DuplicateKey"&&(s.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),n.errors.push(s)}return n}return await this.validateAsync(r.document,t)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(r=>r instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(r=>r instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let r of t)r.severity==="Error"?e.errors.push(r):this.includeWarnings&&e.warnings.push(r)}};De();De();var Me=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 V(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}};var nt=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{VersionOperator as Ue}from"@kanonak-protocol/types/document/models/enums";var Mt="https://{publisher}/index.txt",Ut="https://{publisher}/{package}/{version}.kan.yml",gt={version:1},Ke=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 gt}if(r.status===404)return gt;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??Mt;return ht(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??Ut;return ht(o,{publisher:e,package:t,version:r})}};function ht(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 Ve=class l{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Ke,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(o=>this.isVersionCompatible(o,t.version,t.versionOperator));return n.length===0?null:(n.sort((o,s)=>this.compareVersionStrings(s,o)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((o,s)=>this.compareVersionStrings(s,o))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let r=[];for(let[n,o]of t){if(o.length===0)continue;let s=[...o].sort((a,i)=>this.compareVersionStrings(i,a));r.push({packageName:n,version:s[0]})}return r.sort((n,o)=>n.packageName.localeCompare(o.packageName)),r}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let o=await n.text();return l.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
49
- `)){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 Ue.Any:return!0;case Ue.Exact:return n.major===t.major&&n.minor===t.minor&&n.patch===t.patch;case Ue.Compatible:return n.major===t.major&&n.minor===t.minor&&n.patch>=t.patch;case Ue.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 ot=class{parser=new O;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 Ve({fetchFn:e.fetchFn}):new Ve}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)}};import{CtlKanonakUriType as Oe,PathSegmentType as st}from"@kanonak-protocol/types/ctl/parsing/enums";var Lt=/\.?([a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\])/g;function Ft(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 Ie=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?Oe.DeepLink:this.resourceName!=null?Oe.Resource:this.version!=null?Oe.VersionedPackage:this.package_!=null?Oe.Package:Oe.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 y=o.substring(0,p),m=o.substring(p+1),f=y.indexOf("/");if(f<0)throw new Error(`Invalid Kanonak URI: '${e}'. Expected format: publisher/package@version/resource`);if(s=y.substring(0,f),a=y.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=m.indexOf("/");if(d<0)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package@version/resource)`);let g=m.substring(0,d);if(c=m.substring(d+1),!g||g.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Version required after '@'`);if(i=Ft(g),!c||c.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}else{let y=o.split("/");if(y.length<3)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package/resource)`);if(y.length>3)throw new Error(`Invalid Kanonak URI: '${e}'. Too many path segments. Expected: publisher/package/resource`);if(s=y[0],a=y[1],c=y[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=Bt(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_===st.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 Bt(l,e){let t=[],r=new RegExp(Lt.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_:st.Index,index:i,toString:()=>`[${i}]`})}else t.push({type_:st.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 Rt from"js-yaml";var Wt=/\[([^\]]+)\]\((kanonak:\/\/[^)]+)\)/gi,Ht=/\[([^\]]+)\]\(kan:\/\/([^)]+)\)/gi,Gt=/```[\s\S]*?```|`[^`]+`/g,zt=/^---\s*\n([\s\S]*?)\n---\s*\n/;function qt(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 Xt(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 Le=class{parse(e,t){if(e==null)throw new Error("Content cannot be null");e.charCodeAt(0)===65279&&(e=e.substring(1));let r=zt.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=Rt.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 y of c.imports){if(!y||typeof y!="object")throw new Error("Each import entry must be a mapping with 'publisher' and 'packages'");let m=y.publisher?.toString();if(!m)throw new Error("Each import entry requires a 'publisher' property");if(!y.packages||!Array.isArray(y.packages))throw new Error(`Import entry for publisher '${m}' requires a 'packages' sequence`);p[m]||(p[m]=[]);for(let f of y.packages){if(!f||typeof f!="object")throw new Error(`Each package in publisher '${m}' must be a mapping`);let g=(f.version?.toString()??"1.0.0").split(".").map(Number),h=qt(g[0]||0,g[1]||0,g[2]||0),k=f.match?.toString(),R=k==="^"?q.Major:k==="~"?q.Compatible:k==="*"?q.Any:q.Exact,v=Xt(m,f.package?.toString()??"",h,R,f.alias?.toString()??null);p[m].push(v)}}let u=[];for(let y of Object.values(p))u.push(...y);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 at({metadata:null,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:[p]})}let i=this.parseMarkdownBody(o,a,t[0].length);return at({metadata:s,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:i})}parseInline(e,t){let r=this.parseMarkdownBody(e,new Map,0);return at({metadata:null,rawMarkdown:e,frontmatterLength:0,filePath:t,references:r})}parseMarkdownBody(e,t,r){let n=[],o=Yt(e),s=new RegExp(Wt.source,"gi"),a;for(;(a=s.exec(e))!==null;){if(bt(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:y}=kt(e,a.index),m={displayText:c,rawUri:p,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:y,isResolved:!1,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};try{m.parsedUri=Ie.parse(p)}catch(f){m.error=f.message}n.push(m)}let i=new RegExp(Ht.source,"gi");for(;(a=i.exec(e))!==null;){if(bt(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:y}=kt(e,a.index),m=null,f=null;try{m=Jt(p,t)}catch(g){f=g.message}let d={displayText:c,rawUri:m??`kan://${p}`,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:y,isResolved:!1,error:f,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};if(m!=null&&f==null)try{d.parsedUri=Ie.parse(m)}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 at(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 Yt(l){let e=[],t=new RegExp(Gt.source,"g"),r;for(;(r=t.exec(l))!==null;)e.push([r.index,r.index+r[0].length]);return e}function bt(l,e){for(let[t,r]of e)if(l>=t&&l<r)return!0;return!1}function kt(l,e){let t=1,r=1;for(let n=0;n<e&&n<l.length;n++)l[n]===`
50
- `?(t++,r=1):r++;return{line:t,column:r}}function Jt(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 T,CtlValidationSeverity as X}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as vt,PathSegmentType as Pt}from"@kanonak-protocol/types/ctl/parsing/enums";var Fe=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:T.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:T.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 vt.Resource:await this.resolveResource(e,t);break;case vt.DeepLink:await this.resolveDeepLink(e,t);break;default:t.push({errorType:T.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(T.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(T.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(T.PackageNotFound,`Package not found: ${n}`,e));return}if(!o.body||!o.body[r.resourceName]){t.push(this.createError(T.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(T.PathNotFound,`Path not found: ${a}`,e));return}if(i.type_===Pt.Property){let c=i.name;a+=`.${c}`;let p=Zt(s,c);if(p===void 0){let u=er(s);t.push(this.createError(T.PathNotFound,`Path not found: ${a}`,e,u));return}s=p}else if(i.type_===Pt.Index){let c=i.index;a+=`[${c}]`;let p=Qt(s,c);if(p===void 0){let u=tr(s);t.push(this.createError(T.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 Zt(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 Qt(l,e){if(Array.isArray(l)&&e>=0&&e<l.length)return l[e]}function er(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 tr(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 Ae}from"@kanonak-protocol/types/ctl/resolution/enums";var rr=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);var Be=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[k,R]of Object.entries(d.body))if(R&&typeof R=="object"&&!Array.isArray(R)){let v=this.createMockSubjectKanonak(k,R,g),A=`kanonak://${g}/${k}`;c.has(A)||c.set(A,{entity:v,namespace:g}),h.push(v)}p.set(g,h)}let y=0,m=!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);y=Math.max(y,h),h>=t&&(m=!0)}let f=ir(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:y,wasTruncated:m,unresolvedResources:a}}async resolveEntityRecursive(e,t,r,n,o,s,a,i,c,p,u,y,m){if(s.has(e)||(s.add(e),n>=o))return n;if(!t){let R=y.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,m);switch(this.classifyTier(e,d,a)){case 0:i.push(g);break;case 2:p.push(g);break;default:c.push(g);break}let k=n;for(let R of g.parentClasses){let v=this.resolveReferenceToUri(R,d,r);if(v&&!s.has(v)){let A=y.get(v),j=await this.resolveEntityRecursive(v,A?.entity??null,null,n+1,o,s,a,i,c,p,u,y,m);k=Math.max(k,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 A=y.get(v),j=await this.resolveEntityRecursive(v,A?.entity??null,null,n+1,o,s,a,i,c,p,u,y,m);k=Math.max(k,j)}}if(g.instanceOf_){let R=this.resolveReferenceToUri(g.instanceOf_,d,r);if(R&&!s.has(R)){let v=y.get(R),A=await this.resolveEntityRecursive(R,v?.entity??null,null,n+1,o,s,a,i,c,p,u,y,m);k=Math.max(k,A)}}return k}createResolvedResource(e,t,r,n){let o=e,s=o.name??"",a=o.namespace??o.namespace_??"",i=this.classifyEntityType(e),c=wt(e),p=or(e),u=sr(e),y=[];if(i===Ae.Class){let m=n.get(a);m&&(y=ar(s,m))}return{name:s,kanonakUri:t,resource:e,resourceType:i,parentClass:p.length>0?p[0]:null,parentClasses:p,comment:c,properties:y,namespace_:a,resolutionDepth:r,instanceOf_:u}}classifyEntityType(e){if(w.isClassType(e))return Ae.Class;if(w.isAnnotationPropertyType(e))return Ae.AnnotationProperty;if(w.isDatatypePropertyType(e))return Ae.DatatypeProperty;if(w.isObjectPropertyType(e))return Ae.ObjectProperty;let t=w.getTypeUri(e);return t&&!w.isCoreOntologyType(t)?Ae.Instance:Ae.Other}classifyTier(e,t,r){return r.has(e)?0:nr(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 nr(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 rr.has(`${t}/${n}`)}function wt(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 or(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 sr(l){let e=w.getTypeUri(l);return e?w.isCoreOntologyType(e)?null:e.name:null}function ar(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 y of p)o.push(typeof y=="string"?y:y?.name??String(y));let u=n.entity.range;if(typeof u=="string")s.push(u);else if(Array.isArray(u))for(let y of u)s.push(typeof y=="string"?y:y?.name??String(y))}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=wt(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 ir(l){let e=l.split(`
51
- `);for(let t of e){let r=t.trim();if(r.startsWith("# ")&&!r.startsWith("## "))return r.substring(2).trim()}return null}import{ResolvedResourceType as K}from"@kanonak-protocol/types/ctl/resolution/enums";var He=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(`
52
- `)}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===K.Class),o=r.filter(p=>p.resourceType===K.AnnotationProperty),s=r.filter(p=>p.resourceType===K.DatatypeProperty),a=r.filter(p=>p.resourceType===K.ObjectProperty),i=r.filter(p=>p.resourceType===K.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,y)=>u.name.localeCompare(y.name))){let u=this.renderInternalLink(p.name),y=p.parentClasses.length>0?this.renderInternalLinks(p.parentClasses):"-";e.push(`| ${u} | ${y} | ${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,y)=>u.name.localeCompare(y.name))){let u=this.renderInternalLink(p.name),y=It(p.resourceType),m=cr(p.comment??"");e.push(`| ${u} | ${y} | ${m} |`)}e.push("")}if(i.length>0){let p=new Map;for(let u of i){let y=u.instanceOf_??"Unknown";p.has(y)||p.set(y,[]),p.get(y).push(u)}e.push("### Resources by Type"),e.push(""),e.push("| Type | Resources |"),e.push("|------|-----------|");for(let[u,y]of[...p.entries()].sort((m,f)=>m[0].localeCompare(f[0]))){let m=this.renderInternalLink(u),f=this.renderInternalLinks(y.map(d=>d.name));e.push(`| ${m} | ${f} |`)}e.push("")}}renderHierarchyDiagram(e,t){let r=t.allResources.filter(a=>a.resourceType===K.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=We(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=We(i);e.push(` ${c}["${i}"]:::external`)}e.push("");for(let a of n){let i=We(a.name);for(let c of a.parentClasses){let p=We(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** | ${It(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===K.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 It(l){switch(l){case K.Class:return"Class";case K.AnnotationProperty:return"Annotation Property";case K.DatatypeProperty:return"Datatype Property";case K.ObjectProperty:return"Object Property";case K.Instance:return"Instance";default:return"Other"}}function cr(l){return l?(l=l.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,""),l.length<=50?l:l.substring(0,47)+"..."):""}function We(l){return l.replace(/[^a-zA-Z0-9]/g,"_")}import{CtlValidationErrorType as pr,CtlValidationSeverity as lr}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as ur,PathSegmentType as yr}from"@kanonak-protocol/types/ctl/parsing/enums";import{ResolvedResourceType as mr}from"@kanonak-protocol/types/ctl/resolution/enums";function it(l){if(!l.expiresAt)return!1;let e=new Date(l.expiresAt),t=300*1e3;return e.getTime()<=Date.now()+t}function At(l){return!!l.accessToken&&!it(l)}function U(l){let e=l.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}var Dt="kanonak-credentials",N="credentials",fr=1,Se=class{async get(e){let t=U(e),r=await Ge();return new Promise((n,o)=>{let s=r.transaction(N,"readonly"),i=s.objectStore(N).get(t);i.onsuccess=()=>n(i.result??null),i.onerror=()=>o(new Error(`IndexedDB read failed for '${t}': ${i.error?.message}`)),s.oncomplete=()=>r.close()})}async store(e,t){let r=U(e),n=await Ge();return new Promise((o,s)=>{let a=n.transaction(N,"readwrite"),c=a.objectStore(N).put(t,r);c.onsuccess=()=>o(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${r}': ${c.error?.message}`)),a.oncomplete=()=>n.close()})}async remove(e){let t=U(e),r=await Ge();return new Promise((n,o)=>{let s=r.transaction(N,"readwrite"),i=s.objectStore(N).delete(t);i.onsuccess=()=>n(),i.onerror=()=>o(new Error(`IndexedDB delete failed for '${t}': ${i.error?.message}`)),s.oncomplete=()=>r.close()})}async list(){let e=await Ge();return new Promise((t,r)=>{let n=e.transaction(N,"readonly"),s=n.objectStore(N).getAllKeys();s.onsuccess=()=>t(s.result??[]),s.onerror=()=>r(new Error(`IndexedDB list failed: ${s.error?.message}`)),n.oncomplete=()=>e.close()})}};function Ge(){return new Promise((l,e)=>{let t=indexedDB.open(Dt,fr);t.onupgradeneeded=()=>{let r=t.result;r.objectStoreNames.contains(N)||r.createObjectStore(N)},t.onsuccess=()=>l(t.result),t.onerror=()=>e(new Error(`Failed to open IndexedDB '${Dt}': ${t.error?.message}
53
- Credential storage requires IndexedDB support in your browser.`))})}async function $t(){let l=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),e=await crypto.subtle.exportKey("jwk",l.publicKey);return{signingKey:l.privateKey,publicKeyJwk:e}}async function ze(){let l=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),e=await crypto.subtle.exportKey("jwk",l.publicKey),t=await crypto.subtle.exportKey("jwk",l.privateKey);return{keys:{signingKey:l.privateKey,publicKeyJwk:e},dpopKeyPair:{publicKey:e,privateKey:t}}}async function qe(l){return{signingKey:await crypto.subtle.importKey("jwk",l.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:l.publicKey}}async function Xe(l,e,t,r,n){let o={alg:"ES256",typ:"dpop+jwt",jwk:{kty:l.publicKeyJwk.kty,crv:l.publicKeyJwk.crv,x:l.publicKeyJwk.x,y:l.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:e.toUpperCase(),htu:t,iat:Math.floor(Date.now()/1e3)};return r&&(s.ath=await gr(r)),n&&(s.nonce=n),await dr(o,s,l.signingKey)}function Ye(l){return!l||l.length===0?!1:l.some(e=>e.toUpperCase()==="ES256")}async function dr(l,e,t){let r=jt(JSON.stringify(l)),n=jt(JSON.stringify(e)),o=new TextEncoder().encode(`${r}.${n}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},t,o),a=ct(s);return`${r}.${n}.${a}`}async function gr(l){let e=new TextEncoder().encode(l),t=await crypto.subtle.digest("SHA-256",e);return ct(t)}function jt(l){let e=new TextEncoder().encode(l);return ct(e.buffer)}function ct(l){let e=new Uint8Array(l),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var hr=300*1e3,Je=class{credentialBackend;callbackUrl;constructor(e){this.credentialBackend=new Se,this.callbackUrl=e??`${window.location.origin}/browser/callback.html`}async authorize(e){let t=U(e),r=await this.discover(t);if(!r)return{success:!1,error:`No OAuth discovery endpoint found for '${t}'.`};if(!r.authorizationEndpoint||!r.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${t}'.`};let n=Ye(r.dpopSigningAlgValuesSupported),o=null,s=null;if(n){let h=await ze();o=h.keys,s=h.dpopKeyPair}let a=await this.credentialBackend.get(t),i=a?.clientId??null,c=a?.clientSecret??null;if(!i&&r.registrationEndpoint){let h=await this.registerClient(r.registrationEndpoint);if(!h)return{success:!1,error:`Dynamic client registration failed for '${t}'.`};i=h.clientId,c=h.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${t}'.`};let p=br(),u=await kr(p),y=Rr(),m=vr(r.authorizationEndpoint,i,this.callbackUrl,y,u),f=await this.openAuthPopup(m,y);if(!f)return{success:!1,error:"Authorization timed out or was cancelled."};if(f.error)return{success:!1,error:`Authorization failed: ${f.error}`};if(!f.code)return{success:!1,error:"No authorization code received."};if(f.state!==y)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let d=await this.exchangeCode(r.tokenEndpoint,i,c,f.code,this.callbackUrl,p,o);if(!d)return{success:!1,error:"Token exchange failed."};let g={clientId:i,clientSecret:c,accessToken:d.accessToken??null,refreshToken:d.refreshToken??null,expiresAt:d.expiresIn?new Date(Date.now()+d.expiresIn*1e3).toISOString():null,tokenEndpoint:r.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(t,g),{success:!0,host:t}}async getCredentialWithKeys(e){let t=await this.credentialBackend.get(e);if(!t)return null;let r=null;return t.dpopKeyPair&&(r=await qe(t.dpopKeyPair)),{credential:t,dpopKeys:r}}async logout(e){let t=U(e);return await this.credentialBackend.remove(t),{success:!0,host:t}}async listAuthenticated(){return this.credentialBackend.list()}async discover(e){for(let t of[`https://${e}/.well-known/oauth-authorization-server`,`https://${e}/.well-known/openid-configuration`])try{let r=await fetch(t);if(!r.ok)continue;let n=await r.json();return{issuer:Ee(n.issuer),authorizationEndpoint:Ee(n.authorization_endpoint),tokenEndpoint:Ee(n.token_endpoint),registrationEndpoint:Ee(n.registration_endpoint),revocationEndpoint:Ee(n.revocation_endpoint),dpopSigningAlgValuesSupported:Vt(n.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:Vt(n.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!t.ok)return null;let r=await t.json(),n=r.client_id;return n?{clientId:n,clientSecret:r.client_secret}:null}catch{return null}}openAuthPopup(e,t){return new Promise(r=>{let n=window.open(e,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!n){r(null);return}let o=setTimeout(()=>{i(),r(null)},hr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),r({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},a=setInterval(()=>{n.closed&&(i(),r(null))},500),i=()=>{clearTimeout(o),clearInterval(a),window.removeEventListener("message",s);try{n.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(e,t,r,n,o,s,a){let i=new URLSearchParams({grant_type:"authorization_code",client_id:t,code:n,redirect_uri:o,code_verifier:s});r&&i.set("client_secret",r);let c={"Content-Type":"application/x-www-form-urlencoded"};a&&(c.DPoP=await Xe(a,"POST",e));try{let p=await fetch(e,{method:"POST",headers:c,body:i.toString()});if(!p.ok)return null;let u=await p.json();return{accessToken:u.access_token,refreshToken:u.refresh_token,expiresIn:typeof u.expires_in=="number"?u.expires_in:void 0}}catch{return null}}};function br(){let l=new Uint8Array(32);return crypto.getRandomValues(l),pt(l.buffer)}async function kr(l){let e=new TextEncoder().encode(l),t=await crypto.subtle.digest("SHA-256",e);return pt(t)}function Rr(){let l=new Uint8Array(16);return crypto.getRandomValues(l),pt(l.buffer)}function vr(l,e,t,r,n){let o=new URLSearchParams({client_id:e,response_type:"code",redirect_uri:t,state:r,code_challenge:n,code_challenge_method:"S256"});return`${l}?${o}`}function pt(l){let e=new Uint8Array(l),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ee(l){return typeof l=="string"?l:null}function Vt(l){return Array.isArray(l)?l.filter(e=>typeof e=="string"):null}export{he as AmbiguousReferenceRule,J as BooleanStatement,Se as BrowserCredentialBackend,Je as BrowserOAuthFlow,we as ClassDefinitionRule,ce as ClassHierarchyCycleRule,Be as CtlGraphResolver,Ie as CtlKanonakUri,ur as CtlKanonakUriType,He as CtlMarkdownRenderer,Le as CtlParser,pr as CtlValidationErrorType,lr as CtlValidationSeverity,Fe as CtlValidator,L as DefinedKanonak,de as DefinitionPropertyReferenceRule,tt as EdgeType,_ as EmbeddedKanonak,oe as EmbeddedKanonakNoExplicitTypeRule,W as EmbeddedStatement,Te as GraphBuilder,ot as HttpKanonakDocumentRepository,se as ImportExistenceRule,nt as InMemoryKanonakDocumentRepository,fe as InstancePropertyReferenceRule,E as Kanonak,$e as KanonakObjectParser,_e as KanonakObjectValidator,O as KanonakParser,V as KanonakUri,Me as KanonakUriBuilder,H as ListStatement,me as NamespaceImportCycleRule,ee as NamespacePrefixRule,et as NodeType,Y as NumberStatement,ke as ObjectPropertyImportRule,Re as ObjectPropertyValueValidationRule,b as OntologyValidationError,Q as OntologyValidationResult,yr as PathSegmentType,ve as PropertyDomainRule,pe as PropertyHierarchyCycleRule,xe as PropertyMetadata,be as PropertyRangeReferenceRule,le as PropertyRangeRequiredRule,re as PropertyTypeSpecificityRule,Pe as PropertyValueTypeRule,Ke as PublisherConfigResolver,Ve as PublisherIndex,I as ReferenceKanonak,Z as ReferenceStatement,mr as ResolvedResourceType,te as ResourceNamingRule,$ as ResourceResolver,w as ResourceTypeClassifier,C as ScalarStatement,S as Statement,B as StringStatement,ue as SubClassOfReferenceRule,ye as SubPropertyOfReferenceRule,F as SubjectKanonak,ne as SubjectKanonakTypeRequiredRule,ie as TypeAmbiguityRule,G as TypeResolver,ae as UnresolvedReferenceRule,Ne as ValidationContext,P as ValidationSeverity,ge as XsdImportRule,Ye as browserServerSupportsDPoP,Xe as createBrowserDPoPProof,ze as generateBrowserDPoPKeyPair,$t as generateBrowserDPoPKeys,At as hasValidToken,qe as importDPoPKeys,it as isExpired,U as normalizeHost};
48
+ 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 Se=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 y=u?.toString();if(y==="Class"||y&&y.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 y of p){let m=y?.toString();if(m&&this.isDefinitionType(m)){u=!0;break}}if(!u)for(let y of p){let m=y?.toString();m&&m.trim().length>0&&(n.has(m)||n.set(m,[]),n.get(m).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 y 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:y,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 We=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new $,this.documentRules=[new oe,new se,new ae,new ie,new ce],this.repositoryRules=[new pe,new le,new ue,new ye,new me,new fe,new de,new ge,new he,new ke,new be,new Re,new Pe,new ve,new we,new Ie,new Ae,new De,new Se]}async validateAsync(e,t){let r=new ne;for(let n of this.documentRules)try{let o=n.validate(e);this.addErrorsToResult(r,o)}catch(o){let s=new b;s.ruleType=n.ruleName,s.severity="Error",s.message=`Validation rule '${n.ruleName}' failed: ${o instanceof Error?o.message:String(o)}`,r.errors.push(s)}if(t){let n=[];for(let o of this.repositoryRules)try{let s=await o.validateAsync(e,t);this.addErrorsToResult(r,s)}catch(s){let a=s instanceof Error?s.message:String(s);n.push({ruleName:o.ruleName,cause:a})}if(n.length>0){let o=new Map;for(let{ruleName:s,cause:a}of n){let i=o.get(a);i?i.push(s):o.set(a,[s])}for(let[s,a]of o){let i=new b;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 ne;n.isValid=!1;for(let o of r.errors){let s=new b;s.ruleType="ParseError",s.severity="Error",s.lineNumber=o.line,s.column=o.column,s.message=o.message,o.keyName&&(s.entityName=o.keyName),o.errorType==="DuplicateKey"&&(s.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),n.errors.push(s)}return n}return await this.validateAsync(r.document,t)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(r=>r instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(r=>r instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let r of t)r.severity==="Error"?e.errors.push(r):this.includeWarnings&&e.warnings.push(r)}};$e();$e();var He=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 E(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 Kt(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"&&ir(u,e)&&t.push({entityName:c,entity:p,documentNamespace:`${s}/${a}@${i}`,publisher:s,package_:a,version:i})}}return t}function ir(l,e){let t=Et(l),r=Et(e);return t===r}function Et(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}function F(l,e){return l.major!==e.major?l.major-e.major:l.minor!==e.minor?l.minor-e.minor:l.patch-e.patch}function qe(l,e){return l.major===e.major&&l.minor===e.minor&&l.patch===e.patch}function ft(l){return`${l.major}.${l.minor}.${l.patch}`}function dt(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 xt(l){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(l);return e?dt(Number(e[1]),Number(e[2]),Number(e[3])):null}function Ge(l,e){return F(l,e)>=0&&l.major===e.major&&l.minor===e.minor}function ze(l,e){return e.major===0?F(l,e)>=0&&l.major===0&&l.minor===e.minor:F(l,e)>=0&&l.major===e.major}function Ct(l,e={}){let{requestedVersion:t}=e;if(l.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let n=l.find(o=>{let s=o.metadata.namespace_?.version;return!!s&&ft(s)===t});return n?{chosen:n,alternatives:l.filter(o=>o!==n),multipleVersionsPresent:l.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:l,multipleVersionsPresent:l.length>1,exactRequestedVersionMissing:!0}}if(l.length===1)return{chosen:l[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let r=[...l].sort((n,o)=>{let s=n.metadata.namespace_?.version,a=o.metadata.namespace_?.version;return!s&&!a?0:s?a?F(a,s):-1:1});return{chosen:r[0],alternatives:r.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}var gt=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 qe(s,t.version);case 1:return Ge(s,t.version);case 2:return ze(s,t.version);case 3:return F(s,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((o,s)=>{let a=o.metadata.namespace_.version,i=s.metadata.namespace_.version;return!a&&!i?0:a?i?F(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}};import{VersionOperator as Xe}from"@kanonak-protocol/types/document/models/enums";var cr="https://{publisher}/index.txt",pr="https://{publisher}/{package}/{version}.kan.yml",Ot={version:1},Ne=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??cr;return Tt(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let o=n.package??pr;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 Ce=class l{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new Ne,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(o=>this.isVersionCompatible(o,t.version,t.versionOperator));return n.length===0?null:(n.sort((o,s)=>this.compareVersionStrings(s,o)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((o,s)=>this.compareVersionStrings(s,o))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let r=[];for(let[n,o]of t){if(o.length===0)continue;let s=[...o].sort((a,i)=>this.compareVersionStrings(i,a));r.push({packageName:n,version:s[0]})}return r.sort((n,o)=>n.packageName.localeCompare(o.packageName)),r}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let o=await n.text();return l.parseIndex(o)}static parseIndex(e){let t=new Map;for(let r of e.split(`
49
+ `)){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 ht=class{parser=new $;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new Ce({fetchFn:e.fetchFn}):new Ce}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)}};import{CtlKanonakUriType as _e,PathSegmentType as kt}from"@kanonak-protocol/types/ctl/parsing/enums";var lr=/\.?([a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\])/g;function ur(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 Ve=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?_e.DeepLink:this.resourceName!=null?_e.Resource:this.version!=null?_e.VersionedPackage:this.package_!=null?_e.Package:_e.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 y=o.substring(0,p),m=o.substring(p+1),f=y.indexOf("/");if(f<0)throw new Error(`Invalid Kanonak URI: '${e}'. Expected format: publisher/package@version/resource`);if(s=y.substring(0,f),a=y.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=m.indexOf("/");if(d<0)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package@version/resource)`);let g=m.substring(0,d);if(c=m.substring(d+1),!g||g.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Version required after '@'`);if(i=ur(g),!c||c.trim().length===0)throw new Error(`Invalid Kanonak URI: '${e}'. Resource name cannot be empty`)}else{let y=o.split("/");if(y.length<3)throw new Error(`Invalid Kanonak URI: '${e}'. CTL requires resource references (kanonak://publisher/package/resource)`);if(y.length>3)throw new Error(`Invalid Kanonak URI: '${e}'. Too many path segments. Expected: publisher/package/resource`);if(s=y[0],a=y[1],c=y[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=yr(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 yr(l,e){let t=[],r=new RegExp(lr.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 Z}from"@kanonak-protocol/types/document/models/enums";import*as Mt from"js-yaml";var mr=/\[([^\]]+)\]\((kanonak:\/\/[^)]+)\)/gi,fr=/\[([^\]]+)\]\(kan:\/\/([^)]+)\)/gi,dr=/```[\s\S]*?```|`[^`]+`/g,gr=/^---\s*\n([\s\S]*?)\n---\s*\n/;function hr(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 kr(l,e,t,r,n){let o=r===Z.Compatible?"~":r===Z.Major?"^":r===Z.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!==Z.Exact&&(a.match=o),a},toString(){return s}}}var Ye=class{parse(e,t){if(e==null)throw new Error("Content cannot be null");e.charCodeAt(0)===65279&&(e=e.substring(1));let r=gr.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=Mt.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 y of c.imports){if(!y||typeof y!="object")throw new Error("Each import entry must be a mapping with 'publisher' and 'packages'");let m=y.publisher?.toString();if(!m)throw new Error("Each import entry requires a 'publisher' property");if(!y.packages||!Array.isArray(y.packages))throw new Error(`Import entry for publisher '${m}' requires a 'packages' sequence`);p[m]||(p[m]=[]);for(let f of y.packages){if(!f||typeof f!="object")throw new Error(`Each package in publisher '${m}' must be a mapping`);let g=(f.version?.toString()??"1.0.0").split(".").map(Number),h=hr(g[0]||0,g[1]||0,g[2]||0),k=f.match?.toString(),R=k==="^"?Z.Major:k==="~"?Z.Compatible:k==="*"?Z.Any:Z.Exact,P=kr(m,f.package?.toString()??"",h,R,f.alias?.toString()??null);p[m].push(P)}}let u=[];for(let y of Object.values(p))u.push(...y);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 bt({metadata:null,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:[p]})}let i=this.parseMarkdownBody(o,a,t[0].length);return bt({metadata:s,rawMarkdown:o,frontmatterLength:t[0].length,filePath:r,references:i})}parseInline(e,t){let r=this.parseMarkdownBody(e,new Map,0);return bt({metadata:null,rawMarkdown:e,frontmatterLength:0,filePath:t,references:r})}parseMarkdownBody(e,t,r){let n=[],o=br(e),s=new RegExp(mr.source,"gi"),a;for(;(a=s.exec(e))!==null;){if(Nt(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:y}=_t(e,a.index),m={displayText:c,rawUri:p,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:y,isResolved:!1,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};try{m.parsedUri=Ve.parse(p)}catch(f){m.error=f.message}n.push(m)}let i=new RegExp(fr.source,"gi");for(;(a=i.exec(e))!==null;){if(Nt(a.index,o))continue;let c=a[1],p=a[2],{line:u,column:y}=_t(e,a.index),m=null,f=null;try{m=Rr(p,t)}catch(g){f=g.message}let d={displayText:c,rawUri:m??`kan://${p}`,startOffset:a.index+r,endOffset:a.index+a[0].length+r,line:u,column:y,isResolved:!1,error:f,get fullMarkdownLink(){return`[${this.displayText}](${this.rawUri})`}};if(m!=null&&f==null)try{d.parsedUri=Ve.parse(m)}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 bt(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 br(l){let e=[],t=new RegExp(dr.source,"g"),r;for(;(r=t.exec(l))!==null;)e.push([r.index,r.index+r[0].length]);return e}function Nt(l,e){for(let[t,r]of e)if(l>=t&&l<r)return!0;return!1}function _t(l,e){let t=1,r=1;for(let n=0;n<e&&n<l.length;n++)l[n]===`
50
+ `?(t++,r=1):r++;return{line:t,column:r}}function Rr(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 Q}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as Ut,PathSegmentType as Lt}from"@kanonak-protocol/types/ctl/parsing/enums";var Je=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:Q.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`${Q[this.severity]}: ${this.message} ${s}`.trim()}});continue}try{await this.resolveReference(o,t,r)}catch(s){t.push({errorType:_.ParseError,severity:Q.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`${Q[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 Ut.Resource:await this.resolveResource(e,t);break;case Ut.DeepLink:await this.resolveDeepLink(e,t);break;default:t.push({errorType:_.InvalidUri,severity:Q.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`${Q[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_===Lt.Property){let c=i.name;a+=`.${c}`;let p=Pr(s,c);if(p===void 0){let u=wr(s);t.push(this.createError(_.PathNotFound,`Path not found: ${a}`,e,u));return}s=p}else if(i.type_===Lt.Index){let c=i.index;a+=`[${c}]`;let p=vr(s,c);if(p===void 0){let u=Ir(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:Q.Error,message:t,reference:r,line:r.line,column:r.column,suggestion:n,toString(){let o=this.line!=null?`(${this.line}:${this.column})`:"";return`${Q[this.severity]}: ${this.message} ${o}`.trim()}}}};function Pr(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 vr(l,e){if(Array.isArray(l)&&e>=0&&e<l.length)return l[e]}function wr(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 Ir(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 je}from"@kanonak-protocol/types/ctl/resolution/enums";var Ar=new Set(["kanonak.org/core-rdf","kanonak.org/core-rdfs","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);var Ze=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[k,R]of Object.entries(d.body))if(R&&typeof R=="object"&&!Array.isArray(R)){let P=this.createMockSubjectKanonak(k,R,g),A=`kanonak://${g}/${k}`;c.has(A)||c.set(A,{entity:P,namespace:g}),h.push(P)}p.set(g,h)}let y=0,m=!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);y=Math.max(y,h),h>=t&&(m=!0)}let f=$r(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:y,wasTruncated:m,unresolvedResources:a}}async resolveEntityRecursive(e,t,r,n,o,s,a,i,c,p,u,y,m){if(s.has(e)||(s.add(e),n>=o))return n;if(!t){let R=y.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,m);switch(this.classifyTier(e,d,a)){case 0:i.push(g);break;case 2:p.push(g);break;default:c.push(g);break}let k=n;for(let R of g.parentClasses){let P=this.resolveReferenceToUri(R,d,r);if(P&&!s.has(P)){let A=y.get(P),S=await this.resolveEntityRecursive(P,A?.entity??null,null,n+1,o,s,a,i,c,p,u,y,m);k=Math.max(k,S)}}for(let R of g.properties.filter(P=>P.isObjectProperty)){let P=this.resolveReferenceToUri(R.rangeType,d,r);if(P&&!s.has(P)){let A=y.get(P),S=await this.resolveEntityRecursive(P,A?.entity??null,null,n+1,o,s,a,i,c,p,u,y,m);k=Math.max(k,S)}}if(g.instanceOf_){let R=this.resolveReferenceToUri(g.instanceOf_,d,r);if(R&&!s.has(R)){let P=y.get(R),A=await this.resolveEntityRecursive(R,P?.entity??null,null,n+1,o,s,a,i,c,p,u,y,m);k=Math.max(k,A)}}return k}createResolvedResource(e,t,r,n){let o=e,s=o.name??"",a=o.namespace??o.namespace_??"",i=this.classifyEntityType(e),c=Ft(e),p=Sr(e),u=Vr(e),y=[];if(i===je.Class){let m=n.get(a);m&&(y=jr(s,m))}return{name:s,kanonakUri:t,resource:e,resourceType:i,parentClass:p.length>0?p[0]:null,parentClasses:p,comment:c,properties:y,namespace_:a,resolutionDepth:r,instanceOf_:u}}classifyEntityType(e){if(w.isClassType(e))return je.Class;if(w.isAnnotationPropertyType(e))return je.AnnotationProperty;if(w.isDatatypePropertyType(e))return je.DatatypeProperty;if(w.isObjectPropertyType(e))return je.ObjectProperty;let t=w.getTypeUri(e);return t&&!w.isCoreOntologyType(t)?je.Instance:je.Other}classifyTier(e,t,r){return r.has(e)?0:Dr(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 Dr(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 Ar.has(`${t}/${n}`)}function Ft(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 Sr(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 Vr(l){let e=w.getTypeUri(l);return e?w.isCoreOntologyType(e)?null:e.name:null}function jr(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 y of p)o.push(typeof y=="string"?y:y?.name??String(y));let u=n.entity.range;if(typeof u=="string")s.push(u);else if(Array.isArray(u))for(let y of u)s.push(typeof y=="string"?y:y?.name??String(y))}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=Ft(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 $r(l){let e=l.split(`
51
+ `);for(let t of e){let r=t.trim();if(r.startsWith("# ")&&!r.startsWith("## "))return r.substring(2).trim()}return null}import{ResolvedResourceType as C}from"@kanonak-protocol/types/ctl/resolution/enums";var et=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(`
52
+ `)}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===C.Class),o=r.filter(p=>p.resourceType===C.AnnotationProperty),s=r.filter(p=>p.resourceType===C.DatatypeProperty),a=r.filter(p=>p.resourceType===C.ObjectProperty),i=r.filter(p=>p.resourceType===C.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,y)=>u.name.localeCompare(y.name))){let u=this.renderInternalLink(p.name),y=p.parentClasses.length>0?this.renderInternalLinks(p.parentClasses):"-";e.push(`| ${u} | ${y} | ${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,y)=>u.name.localeCompare(y.name))){let u=this.renderInternalLink(p.name),y=Bt(p.resourceType),m=Er(p.comment??"");e.push(`| ${u} | ${y} | ${m} |`)}e.push("")}if(i.length>0){let p=new Map;for(let u of i){let y=u.instanceOf_??"Unknown";p.has(y)||p.set(y,[]),p.get(y).push(u)}e.push("### Resources by Type"),e.push(""),e.push("| Type | Resources |"),e.push("|------|-----------|");for(let[u,y]of[...p.entries()].sort((m,f)=>m[0].localeCompare(f[0]))){let m=this.renderInternalLink(u),f=this.renderInternalLinks(y.map(d=>d.name));e.push(`| ${m} | ${f} |`)}e.push("")}}renderHierarchyDiagram(e,t){let r=t.allResources.filter(a=>a.resourceType===C.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=Qe(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=Qe(i);e.push(` ${c}["${i}"]:::external`)}e.push("");for(let a of n){let i=Qe(a.name);for(let c of a.parentClasses){let p=Qe(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** | ${Bt(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===C.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 Bt(l){switch(l){case C.Class:return"Class";case C.AnnotationProperty:return"Annotation Property";case C.DatatypeProperty:return"Datatype Property";case C.ObjectProperty:return"Object Property";case C.Instance:return"Instance";default:return"Other"}}function Er(l){return l?(l=l.replace(/\|/g,"\\|").replace(/\n/g," ").replace(/\r/g,""),l.length<=50?l:l.substring(0,47)+"..."):""}function Qe(l){return l.replace(/[^a-zA-Z0-9]/g,"_")}import{CtlValidationErrorType as Kr,CtlValidationSeverity as xr}from"@kanonak-protocol/types/ctl/models/enums";import{CtlKanonakUriType as Cr,PathSegmentType as Or}from"@kanonak-protocol/types/ctl/parsing/enums";import{ResolvedResourceType as Tr}from"@kanonak-protocol/types/ctl/resolution/enums";function Rt(l){if(!l.expiresAt)return!1;let e=new Date(l.expiresAt),t=300*1e3;return e.getTime()<=Date.now()+t}function Wt(l){return!!l.accessToken&&!Rt(l)}function B(l){let e=l.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}var Ht="kanonak-credentials",M="credentials",Nr=1,Oe=class{async get(e){let t=B(e),r=await tt();return new Promise((n,o)=>{let s=r.transaction(M,"readonly"),i=s.objectStore(M).get(t);i.onsuccess=()=>n(i.result??null),i.onerror=()=>o(new Error(`IndexedDB read failed for '${t}': ${i.error?.message}`)),s.oncomplete=()=>r.close()})}async store(e,t){let r=B(e),n=await tt();return new Promise((o,s)=>{let a=n.transaction(M,"readwrite"),c=a.objectStore(M).put(t,r);c.onsuccess=()=>o(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${r}': ${c.error?.message}`)),a.oncomplete=()=>n.close()})}async remove(e){let t=B(e),r=await tt();return new Promise((n,o)=>{let s=r.transaction(M,"readwrite"),i=s.objectStore(M).delete(t);i.onsuccess=()=>n(),i.onerror=()=>o(new Error(`IndexedDB delete failed for '${t}': ${i.error?.message}`)),s.oncomplete=()=>r.close()})}async list(){let e=await tt();return new Promise((t,r)=>{let n=e.transaction(M,"readonly"),s=n.objectStore(M).getAllKeys();s.onsuccess=()=>t(s.result??[]),s.onerror=()=>r(new Error(`IndexedDB list failed: ${s.error?.message}`)),n.oncomplete=()=>e.close()})}};function tt(){return new Promise((l,e)=>{let t=indexedDB.open(Ht,Nr);t.onupgradeneeded=()=>{let r=t.result;r.objectStoreNames.contains(M)||r.createObjectStore(M)},t.onsuccess=()=>l(t.result),t.onerror=()=>e(new Error(`Failed to open IndexedDB '${Ht}': ${t.error?.message}
53
+ Credential storage requires IndexedDB support in your browser.`))})}async function Gt(){let l=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),e=await crypto.subtle.exportKey("jwk",l.publicKey);return{signingKey:l.privateKey,publicKeyJwk:e}}async function rt(){let l=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),e=await crypto.subtle.exportKey("jwk",l.publicKey),t=await crypto.subtle.exportKey("jwk",l.privateKey);return{keys:{signingKey:l.privateKey,publicKeyJwk:e},dpopKeyPair:{publicKey:e,privateKey:t}}}async function nt(l){return{signingKey:await crypto.subtle.importKey("jwk",l.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:l.publicKey}}async function ot(l,e,t,r,n){let o={alg:"ES256",typ:"dpop+jwt",jwk:{kty:l.publicKeyJwk.kty,crv:l.publicKeyJwk.crv,x:l.publicKeyJwk.x,y:l.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:e.toUpperCase(),htu:t,iat:Math.floor(Date.now()/1e3)};return r&&(s.ath=await Mr(r)),n&&(s.nonce=n),await _r(o,s,l.signingKey)}function st(l){return!l||l.length===0?!1:l.some(e=>e.toUpperCase()==="ES256")}async function _r(l,e,t){let r=qt(JSON.stringify(l)),n=qt(JSON.stringify(e)),o=new TextEncoder().encode(`${r}.${n}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},t,o),a=Pt(s);return`${r}.${n}.${a}`}async function Mr(l){let e=new TextEncoder().encode(l),t=await crypto.subtle.digest("SHA-256",e);return Pt(t)}function qt(l){let e=new TextEncoder().encode(l);return Pt(e.buffer)}function Pt(l){let e=new Uint8Array(l),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Ur=300*1e3,at=class{credentialBackend;callbackUrl;constructor(e){this.credentialBackend=new Oe,this.callbackUrl=e??`${window.location.origin}/browser/callback.html`}async authorize(e){let t=B(e),r=await this.discover(t);if(!r)return{success:!1,error:`No OAuth discovery endpoint found for '${t}'.`};if(!r.authorizationEndpoint||!r.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${t}'.`};let n=st(r.dpopSigningAlgValuesSupported),o=null,s=null;if(n){let h=await rt();o=h.keys,s=h.dpopKeyPair}let a=await this.credentialBackend.get(t),i=a?.clientId??null,c=a?.clientSecret??null;if(!i&&r.registrationEndpoint){let h=await this.registerClient(r.registrationEndpoint);if(!h)return{success:!1,error:`Dynamic client registration failed for '${t}'.`};i=h.clientId,c=h.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${t}'.`};let p=Lr(),u=await Fr(p),y=Br(),m=Wr(r.authorizationEndpoint,i,this.callbackUrl,y,u),f=await this.openAuthPopup(m,y);if(!f)return{success:!1,error:"Authorization timed out or was cancelled."};if(f.error)return{success:!1,error:`Authorization failed: ${f.error}`};if(!f.code)return{success:!1,error:"No authorization code received."};if(f.state!==y)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let d=await this.exchangeCode(r.tokenEndpoint,i,c,f.code,this.callbackUrl,p,o);if(!d)return{success:!1,error:"Token exchange failed."};let g={clientId:i,clientSecret:c,accessToken:d.accessToken??null,refreshToken:d.refreshToken??null,expiresAt:d.expiresIn?new Date(Date.now()+d.expiresIn*1e3).toISOString():null,tokenEndpoint:r.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(t,g),{success:!0,host:t}}async getCredentialWithKeys(e){let t=await this.credentialBackend.get(e);if(!t)return null;let r=null;return t.dpopKeyPair&&(r=await nt(t.dpopKeyPair)),{credential:t,dpopKeys:r}}async logout(e){let t=B(e);return await this.credentialBackend.remove(t),{success:!0,host:t}}async listAuthenticated(){return this.credentialBackend.list()}async discover(e){for(let t of[`https://${e}/.well-known/oauth-authorization-server`,`https://${e}/.well-known/openid-configuration`])try{let r=await fetch(t);if(!r.ok)continue;let n=await r.json();return{issuer:Me(n.issuer),authorizationEndpoint:Me(n.authorization_endpoint),tokenEndpoint:Me(n.token_endpoint),registrationEndpoint:Me(n.registration_endpoint),revocationEndpoint:Me(n.revocation_endpoint),dpopSigningAlgValuesSupported:zt(n.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:zt(n.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!t.ok)return null;let r=await t.json(),n=r.client_id;return n?{clientId:n,clientSecret:r.client_secret}:null}catch{return null}}openAuthPopup(e,t){return new Promise(r=>{let n=window.open(e,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!n){r(null);return}let o=setTimeout(()=>{i(),r(null)},Ur),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),r({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},a=setInterval(()=>{n.closed&&(i(),r(null))},500),i=()=>{clearTimeout(o),clearInterval(a),window.removeEventListener("message",s);try{n.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(e,t,r,n,o,s,a){let i=new URLSearchParams({grant_type:"authorization_code",client_id:t,code:n,redirect_uri:o,code_verifier:s});r&&i.set("client_secret",r);let c={"Content-Type":"application/x-www-form-urlencoded"};a&&(c.DPoP=await ot(a,"POST",e));try{let p=await fetch(e,{method:"POST",headers:c,body:i.toString()});if(!p.ok)return null;let u=await p.json();return{accessToken:u.access_token,refreshToken:u.refresh_token,expiresIn:typeof u.expires_in=="number"?u.expires_in:void 0}}catch{return null}}};function Lr(){let l=new Uint8Array(32);return crypto.getRandomValues(l),vt(l.buffer)}async function Fr(l){let e=new TextEncoder().encode(l),t=await crypto.subtle.digest("SHA-256",e);return vt(t)}function Br(){let l=new Uint8Array(16);return crypto.getRandomValues(l),vt(l.buffer)}function Wr(l,e,t,r,n){let o=new URLSearchParams({client_id:e,response_type:"code",redirect_uri:t,state:r,code_challenge:n,code_challenge_method:"S256"});return`${l}?${o}`}function vt(l){let e=new Uint8Array(l),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Me(l){return typeof l=="string"?l:null}function zt(l){return Array.isArray(l)?l.filter(e=>typeof e=="string"):null}export{Pe as AmbiguousReferenceRule,te as BooleanStatement,Oe as BrowserCredentialBackend,at as BrowserOAuthFlow,Se as ClassDefinitionRule,ye as ClassHierarchyCycleRule,Ze as CtlGraphResolver,Ve as CtlKanonakUri,Cr as CtlKanonakUriType,et as CtlMarkdownRenderer,Ye as CtlParser,Kr as CtlValidationErrorType,xr as CtlValidationSeverity,Je as CtlValidator,W as DefinedKanonak,be as DefinitionPropertyReferenceRule,yt as EdgeType,U as EmbeddedKanonak,ce as EmbeddedKanonakNoExplicitTypeRule,G as EmbeddedStatement,Fe as GraphBuilder,ht as HttpKanonakDocumentRepository,pe as ImportExistenceRule,gt as InMemoryKanonakDocumentRepository,ke as InstancePropertyReferenceRule,O as Kanonak,xe as KanonakDocumentPositions,Ke as KanonakObjectParser,We as KanonakObjectValidator,$ as KanonakParser,E as KanonakUri,He as KanonakUriBuilder,z as ListStatement,he as NamespaceImportCycleRule,oe as NamespacePrefixRule,ut as NodeType,ee as NumberStatement,we as ObjectPropertyImportRule,Ie as ObjectPropertyValueValidationRule,b as OntologyValidationError,ne as OntologyValidationResult,Or as PathSegmentType,Ae as PropertyDomainRule,me as PropertyHierarchyCycleRule,Le as PropertyMetadata,ve as PropertyRangeReferenceRule,fe as PropertyRangeRequiredRule,ae as PropertyTypeSpecificityRule,De as PropertyValueTypeRule,Ne as PublisherConfigResolver,Ce as PublisherIndex,I as ReferenceKanonak,re as ReferenceStatement,Tr as ResolvedResourceType,se as ResourceNamingRule,V as ResourceResolver,w as ResourceTypeClassifier,T as ScalarStatement,K as Statement,q as StringStatement,de as SubClassOfReferenceRule,ge as SubPropertyOfReferenceRule,H as SubjectKanonak,ie as SubjectKanonakTypeRequiredRule,ue as TypeAmbiguityRule,X as TypeResolver,le as UnresolvedReferenceRule,Be as ValidationContext,v as ValidationSeverity,Re as XsdImportRule,st as browserServerSupportsDPoP,F as compareVersions,ot as createBrowserDPoPProof,dt as createVersion,Kt as findInstancesByType,ft as formatVersion,rt as generateBrowserDPoPKeyPair,Gt as generateBrowserDPoPKeys,Wt as hasValidToken,nt as importDPoPKeys,Ge as isCompatibleVersion,Rt as isExpired,ze as isMajorCompatible,B as normalizeHost,xt as parseVersionString,At as parseWithPositions,Ct as pickHighestDocument,qe as versionsEqual};