@kanonak-protocol/sdk 1.9.0 → 2.1.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.
@@ -0,0 +1,24 @@
1
+ import { Kanonak } from './Kanonak.js';
2
+ /**
3
+ * A literal value (string, number, or boolean) that appears in the
4
+ * object position of a list-valued DatatypeProperty.
5
+ *
6
+ * Background: a list value on a DatatypeProperty
7
+ * (e.g. `metadataKeys: ["name", "description"]`) was previously parsed
8
+ * by treating each list item as a bare URI reference. That is correct
9
+ * for ObjectProperty lists (where the items denote other entities) but
10
+ * wrong for DatatypeProperty lists (where the items are RDF literals).
11
+ * The misparse caused downstream consumers — most visibly the reasoner
12
+ * via `rdfs3` (range entailment) — to derive type triples that the
13
+ * authored data never intended. `LiteralKanonak` gives the parser a
14
+ * way to keep the literal in `ListStatement.object` without inventing
15
+ * a fake `ReferenceKanonak`.
16
+ *
17
+ * Single-valued DatatypeProperty assignments continue to use
18
+ * `StringStatement` / `NumberStatement` / `BooleanStatement` directly
19
+ * — `LiteralKanonak` exists only for the list-position case where
20
+ * `ListStatement.object: Kanonak[]` requires a `Kanonak` subclass.
21
+ */
22
+ export declare class LiteralKanonak extends Kanonak {
23
+ value: string | number | boolean;
24
+ }
@@ -3,3 +3,4 @@ export { DefinedKanonak } from './DefinedKanonak.js';
3
3
  export { SubjectKanonak } from './SubjectKanonak.js';
4
4
  export { EmbeddedKanonak } from './EmbeddedKanonak.js';
5
5
  export { ReferenceKanonak } from './ReferenceKanonak.js';
6
+ export { LiteralKanonak } from './LiteralKanonak.js';
@@ -1 +1 @@
1
- var F=Object.defineProperty;var q=(l,e)=>()=>(l&&(e=l(l=0)),e);var U=(l,e)=>{for(var t in e)F(l,t,{get:e[t],enumerable:!0})};var L={};U(L,{KanonakUri:()=>b});var b,x=q(()=>{"use strict";b=class l{constructor(e,t,n,a){this.publisher=e;this.package_=t;this.name=n;this.version=a}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let n=t[0],a=t[1],r=n.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${n}. Expected format: publisher/package/name`);let o=a.split(".").map(Number),i={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(o[0]||0)&&s.minor===(o[1]||0)&&s.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:s=>(o[0]||0)!==s.major?(o[0]||0)-s.major:(o[1]||0)!==s.minor?(o[1]||0)-s.minor:(o[2]||0)-s.patch};return new l(r[0],r[1],r[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as O from"js-yaml";var $=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let a=O.load(e);if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let r=this.extractMetadata(a),o=this.extractBody(a,r);return n={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(a){let r=a,o={message:r.message||"Unknown parse error",line:r.mark?.line??0,column:r.mark?.column??0,errorType:r.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${r.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${r.mark?.line??0}: ${r.message||"Unknown parse error"}`};return t.push(o),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=a}return Object.assign(t,e.body),O.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let a of Object.values(t))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===t&&r.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:r=>e!==r.major?e-r.major:t!==r.minor?t-r.minor:n-r.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){t.type_="Package";let r=n,o=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return o&&r&&(t.namespace_={publisher:o,package_:r,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===o&&s.package_===r&&(!i||!s.version||i.equals(s.version)),getHashCode:()=>{let s=0;for(let c=0;c<o.length;c++)s=(s<<5)-s+o.charCodeAt(c);for(let c=0;c<r.length;c++)s=(s<<5)-s+r.charCodeAt(c);return s|0}}),a.imports&&Array.isArray(a.imports)&&(t.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},a;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){a=r;break}for(let[r,o]of Object.entries(e))r!==a&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(n[r]=o);return n}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===r[1]&&i.package_===r[2]&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let s=0;s<r[1].length;s++)i=(i<<5)-i+r[1].charCodeAt(s);for(let s=0;s<r[2].length;s++)i=(i<<5)-i+r[2].charCodeAt(s);return i|0}}}}let t=e.publisher||"",n=e.package||"",a=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:r=>!r||typeof r!="object"?!1:r.publisher===t&&r.package_===n&&(!a||!r.version||a.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);return r|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");t[a]||(t[a]=[]);for(let r of n.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,a);t[a].push(o)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),r=a.publisher||"";t[r]||(t[r]=[]),t[r].push(a)}return t}parseImportsLegacy(e){let t={};for(let[n,a]of Object.entries(e))Array.isArray(a)&&(t[n]=a.map(r=>this.parseImport(r,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let o=this.parseVersion(r),i=this.parseVersionOperator(a),s=this.calculateMaxVersion(a,o),c=e.alias;return{package_:`${n} ${a} ${o.toString()}`,publisher:t,packageName:n,versionOperator:i,version:o,alias:c,minVersion:o,maxVersion:s,toEmbeddedObject:()=>{let p={package:n,match:a,version:o.toString()};return c&&(p.alias=c),p},toString:()=>c?`${n} ${a} ${o.toString()} as ${c}`:`${n} ${a} ${o.toString()}`}}parseImport(e,t){if(typeof e=="string"){let s=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(s){let p=s[1].trim(),m=s[2],u=this.parseVersion(s[3].trim()),d=s[4].trim(),y=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,u);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:u,alias:d,minVersion:u,maxVersion:h,toEmbeddedObject:()=>{let k={package:p,match:m,version:u.toString()};return d&&(k.alias=d),k},toString:()=>`${p} ${m} ${u.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],u=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(m),y=this.calculateMaxVersion(m,u);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:u,alias:void 0,minVersion:u,maxVersion:y,toEmbeddedObject:()=>({package:p,match:m,version:u.toString()}),toString:()=>`${p} ${m} ${u.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),a=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",a);return{package_:e.package||"",publisher:t,packageName:r,versionOperator:n,version:a,alias:e.alias,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let s={package:r,match:o,version:a.toString()};return e.alias&&(s.alias=e.alias),s},toString:()=>`${r} ${o} ${a.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,a]of Object.entries(e)){let r={publisher:n,packages:a.map(o=>{let i=["=","~","^","*"][o.versionOperator],s={package:o.packageName,match:i,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(s.alias=o.alias),s})};t.push(r)}return t}};var R=class{};var S=class extends R{statement=[]};var P=class extends S{namespace;name;icon};var K=class extends S{};x();var f=class l extends R{subject;static parse(e){let t=new l;return t.subject=b.parse(e),t}};var g=class{predicate;object};var v=class extends g{};var j=class l extends v{static parse(e,t){let n=new l;return n.predicate=f.parse(e),n.object=t,n}};var A=class l extends v{static parse(e,t){let n=new l;return n.predicate=f.parse(e),n.object=t,n}};var E=class extends v{};var V=class l extends g{static parse(e,t){let n=new l;return n.predicate=f.parse(e),n.object=f.parse(t),n}};var I=class extends g{};var w=class extends g{};x();function T(l){if(Array.isArray(l))return l.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=l?.toString();return e?[e]:[]}var D=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",a=this.cache.get(n);if(a){let o=a.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let a=e.split("."),r=a[0],o=a[1],i=await this.findDocumentForAlias(t,r);return i?await this.resolveAllEntitiesAsync(o,i):[]}return n.filter(a=>a.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let a=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`;for(let[i,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.push({entityName:i,uri:new b(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:s,definedInNamespace:r,isImported:n.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${a.length} entities from ${r}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(s,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let u=await this.buildAllEntitiesIndexAsync(m,t,o);a.push(...u),this.logger?.debug?.(`Added ${u.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(m){let u=m;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${u.message}`,u),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return a}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let a=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`,i=0;for(let[s,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!a.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(s,{entityName:s,uri:new b(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:c,definedInNamespace:r,isImported:n.length>0,importPath:o}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(c,m);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(u,t,o),y=0;for(let[h,k]of d.entries())if(a.has(h)||(a.set(h,k),y++),m.alias&&!h.includes(".")){let M=`${m.alias}.${h}`;a.has(M)||(a.set(M,k),y++)}this.logger?.debug?.(`Merged ${y} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(u){let d=u;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${r}. See inner exception for details.`,{cause:u})}}return a}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,a]of Object.entries(e.metadata.imports))for(let r of a){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,a)}async isSubclassOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let i=T(o);for(let s of i)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,n,a))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,a)}async isSubpropertyOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let i=T(o);for(let s of i)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,n,a))return!0}return!1}};var _=class l{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&l.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return l.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let a=n.entity.type;if(a){let r=String(a);return r==="Class"||r==="rdfs.Class"||r.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var N=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),a=new D(e),r=new _(a);for(let o of n)for(let[i,s]of Object.entries(o.body)){let c=new P;c.namespace=o.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(s,o,a,r,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,n,a,r){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[i,s]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,r,a);if(!c)continue;let p=await this.parsePropertyValue(i,s,c,t,n,a);p&&o.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return o}async getPropertyMetadata(e,t,n,a,r){let o=await n.resolveEntityAsync(e,t);if(!o)return;let i=o.entity,s=i.type?.toString()??"",c=s.includes(".")?s.substring(s.lastIndexOf(".")+1):s;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=r.getPropertyTypeClassification(s),u=i.range?.toString(),d;if(m==="ObjectProperty")d="ObjectProperty";else if(m==="DatatypeProperty")d="DatatypeProperty";else{let h=u&&u.includes(".")?u.substring(u.lastIndexOf(".")+1):u??"";(u?r.isKnownXsdDatatypeName(u):!1)||h==="Literal"?d="DatatypeProperty":d="ObjectProperty"}return{propertyUri:o.uri.toString(),propertyType:d,range:u,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,n,a,r,o){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,a,r,o);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,a,r,o)}}parseDatatypeValue(e,t,n){if(typeof t=="string")return j.parse(e,t);if(typeof t=="number")return A.parse(e,t);if(typeof t=="boolean"){let a=new E;return a.predicate=f.parse(e),a.object=t,a}}async parseObjectValue(e,t,n,a,r,o){if(typeof t=="string"){let i=await this.resolveReference(t,a,r);if(!i)return;let s=new V;return s.predicate=f.parse(e),s.object=i,s}if(typeof t=="object"&&!Array.isArray(t)){let i=new K;if(i.statement=await this.parseStatements(t,a,r,o,{}),i.statement.length>0){let p=new I;return p.predicate=f.parse(e),p.object=i,p}let s=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new K;m.statement=await this.parseStatements(p,a,r,o,{}),s.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&s.push(m)}if(s.length>0){let p=new w;return p.predicate=f.parse(e),p.object=s,p}let c=new I;return c.predicate=f.parse(e),c.object=i,c}}async parseListValue(e,t,n,a,r,o){let i=[];for(let c of t)if(typeof c=="string"){let p=await this.resolveReference(c,a,r);p&&i.push(p)}else if(typeof c=="object"&&!Array.isArray(c)){let p=new K;p.statement=await this.parseStatements(c,a,r,o,{}),i.push(p)}let s=new w;return s.predicate=f.parse(e),s.object=i,s}async resolveReference(e,t,n){let a=await n.resolveEntityAsync(e,t);if(a){let o=new f;return o.subject=a.uri,o}let r=t.metadata?.namespace_;if(r){let{KanonakUri:o}=await Promise.resolve().then(()=>(x(),L)),i=r.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[u,d]of Object.entries(t.metadata.imports))for(let y of d)if((y.alias??y.packageName)===p){let k=new f;return k.subject=new o(u,y.packageName,m,y.version),k}}}let s=new f;return s.subject=new o(r.publisher,r.package_,e,i),s}return null}async saveKanonaks(e,t){let n=new Map;for(let a of e)a instanceof P&&a.namespace&&(n.has(a.namespace)||n.set(a.namespace,[]),n.get(a.namespace).push(a));for(let[a,r]of n){let o=await this.convertKanonaksToDocument(a,r),i=`${a.split("@")[0]}.yml`;await t.saveDocumentAsync(o,i)}}async serializeToYaml(e,t){let n=e.filter(o=>o instanceof P&&o.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let a=await this.convertKanonaksToDocument(t,n);return new $().save(a)}async convertKanonaksToDocument(e,t){let a={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let i of Object.values(this.imports))o.push(...i);return o}},body:{}},r=new Map;for(let o of t){let i={};for(let s of o.statement){let[c,p]=this.convertStatementToProperty(s);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(s,e,r)}a.body[o.name]=i}return a}convertStatementToProperty(e){if(e instanceof j)return[e.predicate.subject.name,e.object];if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof V)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof w){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof I){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof f?t.push(n.subject.name):n instanceof K&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[a,r]=this.convertStatementToProperty(n);a&&r!==null&&r!==void 0&&(t[a]=r)}return t}collectImportsFromStatement(e,t,n){}};var C=class{propertyUri;propertyType;range;isImported;definedInNamespace};export{N as KanonakObjectParser,$ as KanonakParser,C as PropertyMetadata};
1
+ var q=Object.defineProperty;var H=(u,e)=>()=>(u&&(e=u(u=0)),e);var U=(u,e)=>{for(var t in e)q(u,t,{get:e[t],enumerable:!0})};var F={};U(F,{KanonakUri:()=>v});var v,x=H(()=>{"use strict";v=class u{constructor(e,t,n,a){this.publisher=e;this.package_=t;this.name=n;this.version=a}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let n=t[0],a=t[1],r=n.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${n}. Expected format: publisher/package/name`);let o=a.split(".").map(Number),i={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(o[0]||0)&&s.minor===(o[1]||0)&&s.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:s=>(o[0]||0)!==s.major?(o[0]||0)-s.major:(o[1]||0)!==s.minor?(o[1]||0)-s.minor:(o[2]||0)-s.patch};return new u(r[0],r[1],r[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as D from"js-yaml";var j=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let a=D.load(e);if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let r=this.extractMetadata(a),o=this.extractBody(a,r);return n={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(a){let r=a,o={message:r.message||"Unknown parse error",line:r.mark?.line??0,column:r.mark?.column??0,errorType:r.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${r.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${r.mark?.line??0}: ${r.message||"Unknown parse error"}`};return t.push(o),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=a}return Object.assign(t,e.body),D.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let a of Object.values(t))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===t&&r.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:r=>e!==r.major?e-r.major:t!==r.minor?t-r.minor:n-r.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){t.type_="Package";let r=n,o=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return o&&r&&(t.namespace_={publisher:o,package_:r,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===o&&s.package_===r&&(!i||!s.version||i.equals(s.version)),getHashCode:()=>{let s=0;for(let c=0;c<o.length;c++)s=(s<<5)-s+o.charCodeAt(c);for(let c=0;c<r.length;c++)s=(s<<5)-s+r.charCodeAt(c);return s|0}}),a.imports&&Array.isArray(a.imports)&&(t.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},a;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){a=r;break}for(let[r,o]of Object.entries(e))r!==a&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(n[r]=o);return n}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===r[1]&&i.package_===r[2]&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let s=0;s<r[1].length;s++)i=(i<<5)-i+r[1].charCodeAt(s);for(let s=0;s<r[2].length;s++)i=(i<<5)-i+r[2].charCodeAt(s);return i|0}}}}let t=e.publisher||"",n=e.package||"",a=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:r=>!r||typeof r!="object"?!1:r.publisher===t&&r.package_===n&&(!a||!r.version||a.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);return r|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");t[a]||(t[a]=[]);for(let r of n.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,a);t[a].push(o)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),r=a.publisher||"";t[r]||(t[r]=[]),t[r].push(a)}return t}parseImportsLegacy(e){let t={};for(let[n,a]of Object.entries(e))Array.isArray(a)&&(t[n]=a.map(r=>this.parseImport(r,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let o=this.parseVersion(r),i=this.parseVersionOperator(a),s=this.calculateMaxVersion(a,o),c=e.alias;return{package_:`${n} ${a} ${o.toString()}`,publisher:t,packageName:n,versionOperator:i,version:o,alias:c,minVersion:o,maxVersion:s,toEmbeddedObject:()=>{let p={package:n,match:a,version:o.toString()};return c&&(p.alias=c),p},toString:()=>c?`${n} ${a} ${o.toString()} as ${c}`:`${n} ${a} ${o.toString()}`}}parseImport(e,t){if(typeof e=="string"){let s=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(s){let p=s[1].trim(),m=s[2],l=this.parseVersion(s[3].trim()),d=s[4].trim(),y=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:l,alias:d,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let k={package:p,match:m,version:l.toString()};return d&&(k.alias=d),k},toString:()=>`${p} ${m} ${l.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(m),y=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:l,alias:void 0,minVersion:l,maxVersion:y,toEmbeddedObject:()=>({package:p,match:m,version:l.toString()}),toString:()=>`${p} ${m} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),a=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",a);return{package_:e.package||"",publisher:t,packageName:r,versionOperator:n,version:a,alias:e.alias,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let s={package:r,match:o,version:a.toString()};return e.alias&&(s.alias=e.alias),s},toString:()=>`${r} ${o} ${a.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,a]of Object.entries(e)){let r={publisher:n,packages:a.map(o=>{let i=["=","~","^","*"][o.versionOperator],s={package:o.packageName,match:i,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(s.alias=o.alias),s})};t.push(r)}return t}};var b=class{};var R=class extends b{statement=[]};var I=class extends R{namespace;name;icon};var S=class extends R{};x();var f=class u extends b{subject;static parse(e){let t=new u;return t.subject=v.parse(e),t}};var A=class extends b{value};var g=class{predicate;object};var K=class extends g{};var P=class u extends K{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var E=class u extends K{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var O=class extends K{};var V=class u extends g{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=f.parse(t),n}};var w=class extends g{};var $=class extends g{};x();function N(u){if(Array.isArray(u))return u.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=u?.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 n=t.metadata?.namespace_?.toString()??"unknown",a=this.cache.get(n);if(a){let o=a.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let a=e.split("."),r=a[0],o=a[1],i=await this.findDocumentForAlias(t,r);return i?await this.resolveAllEntitiesAsync(o,i):[]}return n.filter(a=>a.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let a=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`;for(let[i,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.push({entityName:i,uri:new v(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:s,definedInNamespace:r,isImported:n.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${a.length} entities from ${r}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(s,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,o);a.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${l.message}`,l),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return a}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let a=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`,i=0;for(let[s,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!a.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(s,{entityName:s,uri:new v(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:c,definedInNamespace:r,isImported:n.length>0,importPath:o}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(l,t,o),y=0;for(let[h,k]of d.entries())if(a.has(h)||(a.set(h,k),y++),m.alias&&!h.includes(".")){let T=`${m.alias}.${h}`;a.has(T)||(a.set(T,k),y++)}this.logger?.debug?.(`Merged ${y} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let d=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return a}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,a]of Object.entries(e.metadata.imports))for(let r of a){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,a)}async isSubclassOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let i=N(o);for(let s of i)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,n,a))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,a)}async isSubpropertyOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let i=N(o);for(let s of i)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,n,a))return!0}return!1}};var M=class u{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&u.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return u.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let a=n.entity.type;if(a){let r=String(a);return r==="Class"||r==="rdfs.Class"||r.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var C=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),a=new _(e),r=new M(a);for(let o of n)for(let[i,s]of Object.entries(o.body)){let c=new I;c.namespace=o.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(s,o,a,r,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,n,a,r){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[i,s]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,r,a);if(!c)continue;let p=await this.parsePropertyValue(i,s,c,t,n,a);p&&o.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return o}async getPropertyMetadata(e,t,n,a,r){let o=await n.resolveEntityAsync(e,t);if(!o)return;let i=o.entity,s=i.type?.toString()??"",c=s.includes(".")?s.substring(s.lastIndexOf(".")+1):s;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=r.getPropertyTypeClassification(s),l=i.range?.toString(),d;if(m==="ObjectProperty")d="ObjectProperty";else if(m==="DatatypeProperty")d="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?r.isKnownXsdDatatypeName(l):!1)||h==="Literal"?d="DatatypeProperty":d="ObjectProperty"}return{propertyUri:o.uri.toString(),propertyType:d,range:l,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,n,a,r,o){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,a,r,o);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,a,r,o)}}parseDatatypeValue(e,t,n){if(t instanceof Date)return P.parse(e,t.toISOString());if(typeof t=="string")return P.parse(e,t);if(typeof t=="number")return E.parse(e,t);if(typeof t=="boolean"){let a=new O;return a.predicate=f.parse(e),a.object=t,a}}async parseObjectValue(e,t,n,a,r,o){if(typeof t=="string"){let i=await this.resolveReference(t,a,r);if(!i)return;let s=new V;return s.predicate=f.parse(e),s.object=i,s}if(typeof t=="object"&&!Array.isArray(t)){let i=new S;if(i.statement=await this.parseStatements(t,a,r,o,{}),i.statement.length>0){let p=new w;return p.predicate=f.parse(e),p.object=i,p}let s=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new S;m.statement=await this.parseStatements(p,a,r,o,{}),s.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&s.push(m)}if(s.length>0){let p=new $;return p.predicate=f.parse(e),p.object=s,p}let c=new w;return c.predicate=f.parse(e),c.object=i,c}}async parseListValue(e,t,n,a,r,o){let i=[],s=n.propertyType==="DatatypeProperty";for(let p of t){if(s&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let m=new A;m.value=p,i.push(m);continue}if(s&&p instanceof Date){let m=new A;m.value=p.toISOString(),i.push(m);continue}if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&i.push(m)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new S;m.statement=await this.parseStatements(p,a,r,o,{}),i.push(m)}}let c=new $;return c.predicate=f.parse(e),c.object=i,c}async resolveReference(e,t,n){let a=await n.resolveEntityAsync(e,t);if(a){let o=new f;return o.subject=a.uri,o}let r=t.metadata?.namespace_;if(r){let{KanonakUri:o}=await Promise.resolve().then(()=>(x(),F)),i=r.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,d]of Object.entries(t.metadata.imports))for(let y of d)if((y.alias??y.packageName)===p){let k=new f;return k.subject=new o(l,y.packageName,m,y.version),k}}}let s=new f;return s.subject=new o(r.publisher,r.package_,e,i),s}return null}async saveKanonaks(e,t){let n=new Map;for(let a of e)a instanceof I&&a.namespace&&(n.has(a.namespace)||n.set(a.namespace,[]),n.get(a.namespace).push(a));for(let[a,r]of n){let o=await this.convertKanonaksToDocument(a,r),i=`${a.split("@")[0]}.yml`;await t.saveDocumentAsync(o,i)}}async serializeToYaml(e,t){let n=e.filter(o=>o instanceof I&&o.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let a=await this.convertKanonaksToDocument(t,n);return new j().save(a)}async convertKanonaksToDocument(e,t){let a={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let i of Object.values(this.imports))o.push(...i);return o}},body:{}},r=new Map;for(let o of t){let i={};for(let s of o.statement){let[c,p]=this.convertStatementToProperty(s);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(s,e,r)}a.body[o.name]=i}return a}convertStatementToProperty(e){if(e instanceof P)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof O)return[e.predicate.subject.name,e.object];if(e instanceof V)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof $){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof f?t.push(n.subject.name):n instanceof S&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[a,r]=this.convertStatementToProperty(n);a&&r!==null&&r!==void 0&&(t[a]=r)}return t}collectImportsFromStatement(e,t,n){}};var L=class{propertyUri;propertyType;range;isImported;definedInNamespace};export{C as KanonakObjectParser,j as KanonakParser,L as PropertyMetadata};
@@ -0,0 +1,26 @@
1
+ import type { Vocabulary } from './Vocabulary.js';
2
+ /**
3
+ * Default `Vocabulary` for the Kanonak ontology.
4
+ *
5
+ * Binds the W3C semantic roles to the URIs published in
6
+ * `kanonak.org/core-rdf` (RDF + RDFS terms) and
7
+ * `kanonak.org/core-owl` (OWL 2 terms).
8
+ *
9
+ * URIs are version-stripped; the reasoner matches identity by
10
+ * `{publisher}/{package}/{name}` so any compatible release of the
11
+ * core ontologies (e.g. a future `core-owl@2.1.0`) is recognised
12
+ * without a code change here.
13
+ */
14
+ export declare class KanonakVocabulary implements Vocabulary {
15
+ readonly type: string;
16
+ readonly subClassOf: string;
17
+ readonly subPropertyOf: string;
18
+ readonly domain: string;
19
+ readonly range: string;
20
+ readonly equivalentClass: string;
21
+ readonly equivalentProperty: string;
22
+ readonly inverseOf: string;
23
+ readonly sameAs: string;
24
+ readonly transitiveProperty: string;
25
+ readonly symmetricProperty: string;
26
+ }
@@ -0,0 +1,66 @@
1
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
+ import type { Vocabulary } from './Vocabulary.js';
3
+ import { ReasoningResult } from './ReasoningResult.js';
4
+ /**
5
+ * Which set of inference rules to apply during reasoning.
6
+ *
7
+ * `rdfs` — only the RDFS entailment rules (rdfs2/3/5/7/9/11). Use
8
+ * when the ontology relies solely on subClassOf / subPropertyOf /
9
+ * domain / range, with no OWL property characteristics.
10
+ *
11
+ * `owl-rl-classification` (default) — RDFS rules plus the OWL 2 RL
12
+ * subset relevant to instance classification: TransitiveProperty,
13
+ * SymmetricProperty, inverseOf, equivalentClass, equivalentProperty,
14
+ * sameAs.
15
+ */
16
+ export type ReasoningProfile = 'rdfs' | 'owl-rl-classification';
17
+ export interface ReasonerOptions {
18
+ vocabulary?: Vocabulary;
19
+ profile?: ReasoningProfile;
20
+ /**
21
+ * Hard cap on rule-application iterations. The reasoner halts at
22
+ * fixpoint normally; this guard catches pathological ontologies
23
+ * that fail to terminate (which would indicate a bug in the rule
24
+ * set, since OWL 2 RL is decidable in polynomial time).
25
+ *
26
+ * Defaults to 100. Increase if you have a deeply layered hierarchy.
27
+ */
28
+ maxIterations?: number;
29
+ }
30
+ /**
31
+ * Forward-chaining OWL 2 RL / RDFS reasoner.
32
+ *
33
+ * Loads the parsed object model from a repository via the SDK's
34
+ * `KanonakObjectParser`, materialises every statement as an RDF triple,
35
+ * and applies the configured rule set repeatedly until no new triples
36
+ * are derived. The saturated triple store is exposed as a
37
+ * `ReasoningResult` for queries like "instances of class C" (which
38
+ * naturally include subclass and equivalent-class members because the
39
+ * saturation has already propagated `rdf:type` upward through the
40
+ * class hierarchy).
41
+ *
42
+ * The reasoner never reads `.kan.yml` files directly — it works on
43
+ * the parsed `SubjectKanonak.statement[]` model so that aliases,
44
+ * imports, and version resolution are already handled by the SDK.
45
+ */
46
+ export declare class Reasoner {
47
+ private readonly vocabulary;
48
+ private readonly profile;
49
+ private readonly maxIterations;
50
+ constructor(options?: ReasonerOptions);
51
+ reason(repository: IKanonakDocumentRepository): Promise<ReasoningResult>;
52
+ /**
53
+ * Emit triples from a single statement on a subject.
54
+ *
55
+ * - String/Number/Boolean → one literal triple
56
+ * - Reference → one URI triple
57
+ * - List → one triple per item (URI or blank)
58
+ * - Embedded → one blank triple, plus recursive emission
59
+ * of the embedded kanonak's statements
60
+ * keyed by that blank id
61
+ */
62
+ private emitStatement;
63
+ private emitListItem;
64
+ private emitEmbedded;
65
+ }
66
+ export type { Triple, UriKey } from './Triple.js';
@@ -0,0 +1,58 @@
1
+ import type { TripleStore } from './TripleStore.js';
2
+ import type { Triple, UriKey } from './Triple.js';
3
+ import type { Vocabulary } from './Vocabulary.js';
4
+ import type { KanonakUri } from '../resolution/KanonakUri.js';
5
+ /**
6
+ * Read-only query API over the saturated triple store produced by
7
+ * {@link Reasoner.reason}.
8
+ *
9
+ * All queries operate on the post-saturation graph, so transitive
10
+ * subClassOf, declared property characteristics, and equivalentClass
11
+ * collapse have already been materialised. A call like
12
+ * `getInstancesOfClass(C)` returns every individual that the
13
+ * reasoner can prove belongs to C — including via subclass chains
14
+ * and `owl:equivalentClass` declarations.
15
+ *
16
+ * URI-typed inputs accept either a {@link UriKey} string
17
+ * (`{publisher}/{package}/{name}`) or a {@link KanonakUri} object;
18
+ * version is ignored in either case.
19
+ */
20
+ export declare class ReasoningResult {
21
+ private readonly store;
22
+ readonly vocabulary: Vocabulary;
23
+ constructor(store: TripleStore, vocabulary: Vocabulary);
24
+ /**
25
+ * Every individual `x` with `(x, rdf:type, classUri)` in the
26
+ * saturated store. Includes individuals reached via subclass
27
+ * propagation and equivalentClass collapse.
28
+ */
29
+ getInstancesOfClass(classUri: UriKey | KanonakUri): UriKey[];
30
+ /**
31
+ * Every class `C` with `(C, rdfs:subClassOf, classUri)` in the
32
+ * saturated store — i.e. every direct or transitive subclass.
33
+ * Excludes the class itself.
34
+ */
35
+ getSubclasses(classUri: UriKey | KanonakUri): UriKey[];
36
+ /**
37
+ * Every class `D` with `(classUri, rdfs:subClassOf, D)` in the
38
+ * saturated store — i.e. every direct or transitive superclass.
39
+ * Excludes the class itself.
40
+ */
41
+ getSuperclasses(classUri: UriKey | KanonakUri): UriKey[];
42
+ /**
43
+ * Every type `C` such that `(individual, rdf:type, C)` after
44
+ * saturation.
45
+ */
46
+ getTypesOfIndividual(individual: UriKey | KanonakUri): UriKey[];
47
+ /**
48
+ * Membership query: does the individual belong to the class after
49
+ * reasoning?
50
+ */
51
+ isInstanceOf(individual: UriKey | KanonakUri, classUri: UriKey | KanonakUri): boolean;
52
+ /**
53
+ * The full set of saturated triples. Useful for debugging and tests.
54
+ */
55
+ triples(): Triple[];
56
+ /** Total triple count after saturation. */
57
+ size(): number;
58
+ }
@@ -0,0 +1,63 @@
1
+ import type { KanonakUri } from '../resolution/KanonakUri.js';
2
+ /**
3
+ * A version-independent identity key for a Kanonak resource.
4
+ *
5
+ * Format: `{publisher}/{package}/{name}` — the version is intentionally
6
+ * omitted so that documents importing different patch/minor versions of
7
+ * the same property (e.g. `core-rdf/subClassOf`) participate in the same
8
+ * inferences. This matches the convention established in
9
+ * `cli/src/capabilities/UriHelpers.ts`.
10
+ */
11
+ export type UriKey = string;
12
+ /**
13
+ * Convert a `KanonakUri` to its version-stripped identity key.
14
+ */
15
+ export declare function uriKey(uri: KanonakUri): UriKey;
16
+ /**
17
+ * Build a `UriKey` directly from publisher/package/name strings.
18
+ * Useful when the caller has the parts but no `KanonakUri` instance,
19
+ * e.g. when constructing a `Vocabulary`.
20
+ */
21
+ export declare function makeUriKey(publisher: string, package_: string, name: string): UriKey;
22
+ /**
23
+ * The object position of a triple. Either:
24
+ * - `uri` — a reference to another resource (URI identity)
25
+ * - `literal` — an RDF literal value (string, number, or boolean)
26
+ * - `blank` — an anonymous resource (embedded kanonak)
27
+ *
28
+ * The blank-node ID is internal to a single reasoning run; do not rely
29
+ * on it being stable across runs or across invocations.
30
+ */
31
+ export type TripleObject = {
32
+ kind: 'uri';
33
+ key: UriKey;
34
+ } | {
35
+ kind: 'literal';
36
+ lexical: string;
37
+ datatype: 'string' | 'number' | 'boolean';
38
+ } | {
39
+ kind: 'blank';
40
+ id: string;
41
+ };
42
+ /**
43
+ * An RDF triple (subject, predicate, object). The subject and predicate
44
+ * are always identified by `UriKey`; the object can additionally be a
45
+ * literal or a blank node.
46
+ */
47
+ export interface Triple {
48
+ s: UriKey;
49
+ p: UriKey;
50
+ o: TripleObject;
51
+ }
52
+ /**
53
+ * Canonical string form of a triple, used as a Set key for dedup.
54
+ */
55
+ export declare function tripleKey(t: Triple): string;
56
+ /**
57
+ * Canonical string form of an object value.
58
+ */
59
+ export declare function objectKey(o: TripleObject): string;
60
+ /**
61
+ * Construct a triple with a URI object.
62
+ */
63
+ export declare function uriTriple(s: UriKey, p: UriKey, oKey: UriKey): Triple;
@@ -0,0 +1,63 @@
1
+ import type { Triple, TripleObject, UriKey } from './Triple.js';
2
+ /**
3
+ * In-memory triple store with the indexes the reasoner rules need:
4
+ *
5
+ * - membership Set keyed by canonical triple string (for dedup)
6
+ * - byP : predicate → triples
7
+ * - bySP : (subject, predicate) → triples
8
+ * - byPO : (predicate, objectKey)→ triples (URI objects only)
9
+ *
10
+ * The store is monotonic: triples are only added, never removed.
11
+ * Forward chaining relies on this — once an entailment is derived,
12
+ * it stays derived for the rest of the run.
13
+ */
14
+ export declare class TripleStore {
15
+ private readonly all;
16
+ private readonly byPIdx;
17
+ private readonly bySPIdx;
18
+ private readonly byPOIdx;
19
+ private readonly tripleList;
20
+ /**
21
+ * Add a triple. Returns true if it was newly added, false if it
22
+ * was already present.
23
+ */
24
+ add(t: Triple): boolean;
25
+ has(t: Triple): boolean;
26
+ size(): number;
27
+ /**
28
+ * Snapshot of the triples currently in the store. Returns a new
29
+ * array — safe to iterate while adding new triples.
30
+ */
31
+ snapshot(): Triple[];
32
+ /**
33
+ * All triples with predicate `p`. Returns a snapshot — safe to
34
+ * iterate while the store is being mutated by rule application.
35
+ */
36
+ byPredicate(p: UriKey): Triple[];
37
+ /**
38
+ * All triples with subject `s` AND predicate `p`. Snapshot.
39
+ */
40
+ bySubjectPredicate(s: UriKey, p: UriKey): Triple[];
41
+ /**
42
+ * All triples with predicate `p` AND a URI object whose key is
43
+ * `oKey`. Snapshot.
44
+ */
45
+ byPredicateObject(p: UriKey, oKey: UriKey): Triple[];
46
+ /**
47
+ * Set of all distinct subjects `s` such that `(s, p, oKey)` exists.
48
+ */
49
+ subjectsWithPredicateObject(p: UriKey, oKey: UriKey): UriKey[];
50
+ /**
51
+ * Set of all distinct URI objects `o` such that `(s, p, o)` exists,
52
+ * with the given subject `s` and predicate `p`.
53
+ */
54
+ uriObjectsOf(s: UriKey, p: UriKey): UriKey[];
55
+ /**
56
+ * Membership check on (s, p, o-as-uri).
57
+ */
58
+ hasUri(s: UriKey, p: UriKey, oKey: UriKey): boolean;
59
+ /**
60
+ * Membership check on (s, p, any object).
61
+ */
62
+ hasTriple(s: UriKey, p: UriKey, o: TripleObject): boolean;
63
+ }
@@ -0,0 +1,42 @@
1
+ import type { UriKey } from './Triple.js';
2
+ /**
3
+ * Maps URIs in a particular ontology to the W3C semantic roles the
4
+ * reasoner understands. The reasoner is parameterised by a
5
+ * `Vocabulary` so it can run against any ontology that mirrors the
6
+ * RDFS / OWL 2 vocabulary, without baking publisher-specific URIs
7
+ * into the rule engine.
8
+ *
9
+ * Every field is a `UriKey` (`{publisher}/{package}/{name}`, version
10
+ * stripped) so that documents importing different compatible versions
11
+ * of the underlying ontology still trigger the same inferences.
12
+ *
13
+ * The default binding for the Kanonak ontology is in
14
+ * `KanonakVocabulary`; users with a different core ontology can supply
15
+ * their own implementation.
16
+ *
17
+ * Roles correspond to the canonical W3C IRIs:
18
+ * type → rdf:type
19
+ * subClassOf → rdfs:subClassOf
20
+ * subPropertyOf → rdfs:subPropertyOf
21
+ * domain → rdfs:domain
22
+ * range → rdfs:range
23
+ * equivalentClass → owl:equivalentClass
24
+ * equivalentProperty → owl:equivalentProperty
25
+ * inverseOf → owl:inverseOf
26
+ * sameAs → owl:sameAs
27
+ * transitiveProperty → owl:TransitiveProperty (the *class*)
28
+ * symmetricProperty → owl:SymmetricProperty (the *class*)
29
+ */
30
+ export interface Vocabulary {
31
+ type: UriKey;
32
+ subClassOf: UriKey;
33
+ subPropertyOf: UriKey;
34
+ domain: UriKey;
35
+ range: UriKey;
36
+ equivalentClass: UriKey;
37
+ equivalentProperty: UriKey;
38
+ inverseOf: UriKey;
39
+ sameAs: UriKey;
40
+ transitiveProperty: UriKey;
41
+ symmetricProperty: UriKey;
42
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Forward-chaining OWL 2 RL / RDFS reasoner for Kanonak ontologies.
3
+ *
4
+ * Implements the W3C-standard inference rules from:
5
+ * - RDF 1.1 Semantics (https://www.w3.org/TR/rdf11-mt/, §9.2.1)
6
+ * - OWL 2 Web Ontology Language Profiles (https://www.w3.org/TR/owl2-profiles/, §4.3)
7
+ *
8
+ * Entry point: construct a `Reasoner`, call `.reason(repository)`,
9
+ * then query the returned `ReasoningResult`.
10
+ *
11
+ * Example:
12
+ * const reasoner = new Reasoner();
13
+ * const result = await reasoner.reason(repo);
14
+ * const instances = result.getInstancesOfClass({
15
+ * publisher: 'kanonak.org',
16
+ * package_: 'capabilities',
17
+ * name: 'Capability',
18
+ * version: { major: 1, minor: 0, patch: 0, ... },
19
+ * });
20
+ */
21
+ export { Reasoner } from './Reasoner.js';
22
+ export type { ReasonerOptions, ReasoningProfile } from './Reasoner.js';
23
+ export { ReasoningResult } from './ReasoningResult.js';
24
+ export { TripleStore } from './TripleStore.js';
25
+ export { KanonakVocabulary } from './KanonakVocabulary.js';
26
+ export type { Vocabulary } from './Vocabulary.js';
27
+ export type { Triple, TripleObject, UriKey } from './Triple.js';
28
+ export { uriKey, makeUriKey, tripleKey, uriTriple } from './Triple.js';
29
+ export type { Rule } from './rules/Rule.js';
30
+ export { RDFS_RULES, OWL_RL_CLASSIFICATION_RULES } from './rules/index.js';
@@ -0,0 +1 @@
1
+ var te=Object.defineProperty;var re=(s,e)=>()=>(s&&(e=s(s=0)),e);var ne=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:!0})};var ee={};ne(ee,{KanonakUri:()=>P});var P,C=re(()=>{"use strict";P=class s{constructor(e,t,r,o){this.publisher=e;this.package_=t;this.name=r;this.version=o}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],o=t[1],n=r.split("/");if(n.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let a=o.split(".").map(Number),c={major:a[0]||0,minor:a[1]||0,patch:a[2]||0,toString:()=>`${a[0]||0}.${a[1]||0}.${a[2]||0}`,equals:i=>!i||typeof i!="object"?!1:i.major===(a[0]||0)&&i.minor===(a[1]||0)&&i.patch===(a[2]||0),getHashCode:()=>(a[0]||0)<<20|(a[1]||0)<<10|(a[2]||0),compareTo:i=>(a[0]||0)!==i.major?(a[0]||0)-i.major:(a[1]||0)!==i.minor?(a[1]||0)-i.minor:(a[2]||0)-i.patch};return new s(n[0],n[1],n[2],c)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});var S=class{};var V=class extends S{statement=[]};var v=class extends V{namespace;name;icon};var R=class extends V{};C();var m=class s extends S{subject;static parse(e){let t=new s;return t.subject=P.parse(e),t}};var w=class extends S{value};var k=class{predicate;object};var j=class extends k{};var I=class s extends j{static parse(e,t){let r=new s;return r.predicate=m.parse(e),r.object=t,r}};var x=class s extends j{static parse(e,t){let r=new s;return r.predicate=m.parse(e),r.object=t,r}};var A=class extends j{};var E=class s extends k{static parse(e,t){let r=new s;return r.predicate=m.parse(e),r.object=m.parse(t),r}};var $=class extends k{};var O=class extends k{};C();function B(s){if(Array.isArray(s))return s.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=s?.toString();return e?[e]:[]}var M=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",o=this.cache.get(r);if(o){let a=o.get(e);if(a)return a}let n=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,n),n.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let o=e.split("."),n=o[0],a=o[1],c=await this.findDocumentForAlias(t,n);return c?await this.resolveAllEntitiesAsync(a,c):[]}return r.filter(o=>o.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let o=[],n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let a=r.length===0?n:`${r} \u2192 ${n}`;for(let[c,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.push({entityName:c,uri:new P(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,p),entity:i,definedInNamespace:n,isImported:r.length>0,importPath:a})}if(this.logger?.debug?.(`Collected ${o.length} entities from ${n}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((i,p)=>i+p.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${n}`);for(let[i,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${i}/${l.packageName}`);let u=await this.repository.getHighestCompatibleVersionAsync(i,l);if(u){this.logger?.debug?.(`Successfully loaded import: ${u.metadata?.namespace_?.toString()}`);let f=await this.buildAllEntitiesIndexAsync(u,t,a);o.push(...f),this.logger?.debug?.(`Added ${f.length} entities from import ${u.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${l.packageName}`)}catch(u){let f=u;throw this.logger?.error?.(`Failed to process import ${i}/${l.packageName} for namespace ${n}. Error: ${f.message}`,f),new Error(`Failed to process import ${i}/${l.packageName} for namespace ${n}. See inner exception for details.`,{cause:u})}}return o}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let o=new Map,n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let a=r.length===0?n:`${r} \u2192 ${n}`,c=0;for(let[i,p]of Object.entries(e.body))if(p&&typeof p=="object"&&!Array.isArray(p)&&!o.has(i)){let l=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.set(i,{entityName:i,uri:new P(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,l),entity:p,definedInNamespace:n,isImported:r.length>0,importPath:a}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${n}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((p,l)=>p+l.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${n}`);for(let[p,l]of Object.entries(e.metadata.imports))for(let u of l)try{this.logger?.debug?.(`Resolving import: ${p}/${u.packageName}`);let f=await this.repository.getHighestCompatibleVersionAsync(p,u);if(f){this.logger?.debug?.(`Successfully loaded import: ${f.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(f,t,a),b=0;for(let[h,K]of d.entries())if(o.has(h)||(o.set(h,K),b++),u.alias&&!h.includes(".")){let z=`${u.alias}.${h}`;o.has(z)||(o.set(z,K),b++)}this.logger?.debug?.(`Merged ${b} entities from import ${f.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${u.packageName}`)}catch(f){let d=f;throw this.logger?.error?.(`Failed to process import ${p}/${u.packageName} for namespace ${n}. Error: ${d.message}`,d),new Error(`Failed to process import ${p}/${u.packageName} for namespace ${n}. See inner exception for details.`,{cause:f})}}return o}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,o]of Object.entries(e.metadata.imports))for(let n of o){if(n.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,n);if(!n.alias&&n.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,n)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,o)}async isSubclassOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let a=n.entity.subClassOf;if(a){let c=B(a);for(let i of c)if(i===t||await this.isSubclassOfRecursiveAsync(i,t,r,o))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,o)}async isSubpropertyOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let a=n.entity.subPropertyOf;if(a){let c=B(a);for(let i of c)if(i===t||await this.isSubpropertyOfRecursiveAsync(i,t,r,o))return!0}return!1}};var N=class s{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"&&s.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 s.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 o=r.entity.type;if(o){let n=String(o);return n==="Class"||n==="rdfs.Class"||n.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))}};import*as F from"js-yaml";var q=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 o=F.load(e);if(!o||typeof o!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let n=this.extractMetadata(o),a=this.extractBody(o,n);return r={metadata:n,body:a,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(o){let n=o,a={message:n.message||"Unknown parse error",line:n.mark?.line??0,column:n.mark?.column??0,errorType:n.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${n.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${n.mark?.line??0}: ${n.message||"Unknown parse error"}`};return t.push(a),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,o={type:"Package",publisher:r.publisher};r.version&&(o.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(o.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=o}return Object.assign(t,e.body),F.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 o of Object.values(t))r.push(...o);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===e&&n.minor===t&&n.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:n=>e!==n.major?e-n.major:t!==n.minor?t-n.minor:r-n.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){t.type_="Package";let n=r,a=o.publisher,c=o.version?this.parseVersion(o.version):void 0;return a&&n&&(t.namespace_={publisher:a,package_:n,version:c,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===a&&i.package_===n&&(!c||!i.version||c.equals(i.version)),getHashCode:()=>{let i=0;for(let p=0;p<a.length;p++)i=(i<<5)-i+a.charCodeAt(p);for(let p=0;p<n.length;p++)i=(i<<5)-i+n.charCodeAt(p);return i|0}}),o.imports&&Array.isArray(o.imports)&&(t.imports=this.parseImportsV3(o.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={},o;for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){o=n;break}for(let[n,a]of Object.entries(e))n!==o&&n!=="kanonak"&&n!=="namespace"&&n!=="imports"&&(r[n]=a);return r}parseNamespace(e){if(typeof e=="string"){let n=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(n){let a=n[3]?this.parseVersion(n[3]):this.createVersion(1,0,0);return{publisher:n[1],package_:n[2],version:a,toString:()=>e,equals:c=>!c||typeof c!="object"?!1:c.publisher===n[1]&&c.package_===n[2]&&(!a||!c.version||a.equals(c.version)),getHashCode:()=>{let c=0;for(let i=0;i<n[1].length;i++)c=(c<<5)-c+n[1].charCodeAt(i);for(let i=0;i<n[2].length;i++)c=(c<<5)-c+n[2].charCodeAt(i);return c|0}}}}let t=e.publisher||"",r=e.package||"",o=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:o,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:n=>!n||typeof n!="object"?!1:n.publisher===t&&n.package_===r&&(!o||!n.version||o.equals(n.version)),getHashCode:()=>{let n=0;for(let a=0;a<t.length;a++)n=(n<<5)-n+t.charCodeAt(a);for(let a=0;a<r.length;a++)n=(n<<5)-n+r.charCodeAt(a);return n|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 o=r.publisher;if(!o)throw new Error("PublisherImport requires 'publisher' property");t[o]||(t[o]=[]);for(let n of r.packages){if(!n||typeof n!="object")continue;let a=this.parseImportFromEmbeddedObject(n,o);t[o].push(a)}}else{let o=this.parseImportFromEmbeddedObject(r,r.publisher),n=o.publisher||"";t[n]||(t[n]=[]),t[n].push(o)}return t}parseImportsLegacy(e){let t={};for(let[r,o]of Object.entries(e))Array.isArray(o)&&(t[r]=o.map(n=>this.parseImport(n,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let o=e.match;if(!o)throw new Error("Import requires 'match' property");let n=e.version;if(!n)throw new Error("Import requires 'version' property");let a=this.parseVersion(n),c=this.parseVersionOperator(o),i=this.calculateMaxVersion(o,a),p=e.alias;return{package_:`${r} ${o} ${a.toString()}`,publisher:t,packageName:r,versionOperator:c,version:a,alias:p,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let l={package:r,match:o,version:a.toString()};return p&&(l.alias=p),l},toString:()=>p?`${r} ${o} ${a.toString()} as ${p}`:`${r} ${o} ${a.toString()}`}}parseImport(e,t){if(typeof e=="string"){let i=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(i){let l=i[1].trim(),u=i[2],f=this.parseVersion(i[3].trim()),d=i[4].trim(),b=this.parseVersionOperator(u),h=this.calculateMaxVersion(u,f);return{package_:e,publisher:t,packageName:l,versionOperator:b,version:f,alias:d,minVersion:f,maxVersion:h,toEmbeddedObject:()=>{let K={package:l,match:u,version:f.toString()};return d&&(K.alias=d),K},toString:()=>`${l} ${u} ${f.toString()} as ${d}`}}let p=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(p){let l=p[1].trim(),u=p[2],f=this.parseVersion(p[3].trim()),d=this.parseVersionOperator(u),b=this.calculateMaxVersion(u,f);return{package_:e,publisher:t,packageName:l,versionOperator:d,version:f,alias:void 0,minVersion:f,maxVersion:b,toEmbeddedObject:()=>({package:l,match:u,version:f.toString()}),toString:()=>`${l} ${u} ${f.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),o=this.parseVersion(e.version||"1.0.0"),n=e.packageName||e.package||"",a=["=","~","^","*"][r],c=this.calculateMaxVersion(e.operator||"~",o);return{package_:e.package||"",publisher:t,packageName:n,versionOperator:r,version:o,alias:e.alias,minVersion:o,maxVersion:c,toEmbeddedObject:()=>{let i={package:n,match:a,version:o.toString()};return e.alias&&(i.alias=e.alias),i},toString:()=>`${n} ${a} ${o.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,o]of Object.entries(e)){let n={publisher:r,packages:o.map(a=>{let c=["=","~","^","*"][a.versionOperator],i={package:a.packageName,match:c,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(i.alias=a.alias),i})};t.push(n)}return t}};var W=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),o=new M(e),n=new N(o);for(let a of r)for(let[c,i]of Object.entries(a.body)){let p=new v;p.namespace=a.metadata.namespace_?.toString()??"",p.name=c,p.statement=[];let l=await this.parseStatements(i,a,o,n,e);p.statement.push(...l),t.push(p)}return t}async parseStatements(e,t,r,o,n){let a=[];if(typeof e!="object"||e===null||Array.isArray(e))return a;for(let[c,i]of Object.entries(e))try{let p=await this.getPropertyMetadata(c,t,r,n,o);if(!p)continue;let l=await this.parsePropertyValue(c,i,p,t,r,o);l&&a.push(l)}catch(p){console.error(`Error parsing property ${c}:`,p)}return a}async getPropertyMetadata(e,t,r,o,n){let a=await r.resolveEntityAsync(e,t);if(!a)return;let c=a.entity,i=c.type?.toString()??"",p=i.includes(".")?i.substring(i.lastIndexOf(".")+1):i;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let u=n.getPropertyTypeClassification(i),f=c.range?.toString(),d;if(u==="ObjectProperty")d="ObjectProperty";else if(u==="DatatypeProperty")d="DatatypeProperty";else{let h=f&&f.includes(".")?f.substring(f.lastIndexOf(".")+1):f??"";(f?n.isKnownXsdDatatypeName(f):!1)||h==="Literal"?d="DatatypeProperty":d="ObjectProperty"}return{propertyUri:a.uri.toString(),propertyType:d,range:f,isImported:a.isImported,definedInNamespace:a.definedInNamespace}}async parsePropertyValue(e,t,r,o,n,a){let c=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(c,t,r,o,n,a);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(c,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(c,t,r,o,n,a)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return I.parse(e,t.toISOString());if(typeof t=="string")return I.parse(e,t);if(typeof t=="number")return x.parse(e,t);if(typeof t=="boolean"){let o=new A;return o.predicate=m.parse(e),o.object=t,o}}async parseObjectValue(e,t,r,o,n,a){if(typeof t=="string"){let c=await this.resolveReference(t,o,n);if(!c)return;let i=new E;return i.predicate=m.parse(e),i.object=c,i}if(typeof t=="object"&&!Array.isArray(t)){let c=new R;if(c.statement=await this.parseStatements(t,o,n,a,{}),c.statement.length>0){let l=new $;return l.predicate=m.parse(e),l.object=c,l}let i=[];for(let[,l]of Object.entries(t))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new R;u.statement=await this.parseStatements(l,o,n,a,{}),i.push(u)}else if(typeof l=="string"){let u=await this.resolveReference(l,o,n);u&&i.push(u)}if(i.length>0){let l=new O;return l.predicate=m.parse(e),l.object=i,l}let p=new $;return p.predicate=m.parse(e),p.object=c,p}}async parseListValue(e,t,r,o,n,a){let c=[],i=r.propertyType==="DatatypeProperty";for(let l of t){if(i&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")){let u=new w;u.value=l,c.push(u);continue}if(i&&l instanceof Date){let u=new w;u.value=l.toISOString(),c.push(u);continue}if(typeof l=="string"){let u=await this.resolveReference(l,o,n);u&&c.push(u)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let u=new R;u.statement=await this.parseStatements(l,o,n,a,{}),c.push(u)}}let p=new O;return p.predicate=m.parse(e),p.object=c,p}async resolveReference(e,t,r){let o=await r.resolveEntityAsync(e,t);if(o){let a=new m;return a.subject=o.uri,a}let n=t.metadata?.namespace_;if(n){let{KanonakUri:a}=await Promise.resolve().then(()=>(C(),ee)),c=n.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),l=e.substring(0,p),u=e.substring(p+1);if(t.metadata?.imports){for(let[f,d]of Object.entries(t.metadata.imports))for(let b of d)if((b.alias??b.packageName)===l){let K=new m;return K.subject=new a(f,b.packageName,u,b.version),K}}}let i=new m;return i.subject=new a(n.publisher,n.package_,e,c),i}return null}async saveKanonaks(e,t){let r=new Map;for(let o of e)o instanceof v&&o.namespace&&(r.has(o.namespace)||r.set(o.namespace,[]),r.get(o.namespace).push(o));for(let[o,n]of r){let a=await this.convertKanonaksToDocument(o,n),c=`${o.split("@")[0]}.yml`;await t.saveDocumentAsync(a,c)}}async serializeToYaml(e,t){let r=e.filter(a=>a instanceof v&&a.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let o=await this.convertKanonaksToDocument(t,r);return new q().save(o)}async convertKanonaksToDocument(e,t){let o={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let a=[];for(let c of Object.values(this.imports))a.push(...c);return a}},body:{}},n=new Map;for(let a of t){let c={};for(let i of a.statement){let[p,l]=this.convertStatementToProperty(i);p&&l!==null&&l!==void 0&&(c[p]=l),this.collectImportsFromStatement(i,e,n)}o.body[a.name]=c}return o}convertStatementToProperty(e){if(e instanceof I)return[e.predicate.subject.name,e.object];if(e instanceof x)return[e.predicate.subject.name,e.object];if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof O){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof $){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof m?t.push(r.subject.name):r instanceof R&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[o,n]=this.convertStatementToProperty(r);o&&n!==null&&n!==void 0&&(t[o]=n)}return t}collectImportsFromStatement(e,t,r){}};function U(s){return`${s.publisher}/${s.package_}/${s.name}`}function g(s,e,t){return`${s}/${e}/${t}`}function H(s){return`${s.s}|${s.p}|${G(s.o)}`}function G(s){switch(s.kind){case"uri":return`u:${s.key}`;case"literal":return`l:${s.datatype}:${s.lexical}`;case"blank":return`b:${s.id}`}}function y(s,e,t){return{s,p:e,o:{kind:"uri",key:t}}}var D=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=H(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),J(this.byPIdx,e.p,e),J(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&J(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(H(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let o=new Set;for(let n of r)o.add(n.s);return Array.from(o)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let o=new Set;for(let n of r)n.o.kind==="uri"&&o.add(n.o.key);return Array.from(o)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${G(r)}`)}};function J(s,e,t){let r=s.get(e);r?r.push(t):s.set(e,[t])}var _=class{type=g("kanonak.org","core-rdf","type");subClassOf=g("kanonak.org","core-rdf","subClassOf");subPropertyOf=g("kanonak.org","core-rdf","subPropertyOf");domain=g("kanonak.org","core-rdf","domain");range=g("kanonak.org","core-rdf","range");equivalentClass=g("kanonak.org","core-owl","equivalentClass");equivalentProperty=g("kanonak.org","core-owl","equivalentProperty");inverseOf=g("kanonak.org","core-owl","inverseOf");sameAs=g("kanonak.org","core-owl","sameAs");transitiveProperty=g("kanonak.org","core-owl","TransitiveProperty");symmetricProperty=g("kanonak.org","core-owl","SymmetricProperty")};var oe={name:"rdfs2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},ae={name:"rdfs3",apply(s,e){let t=!1;for(let r of s.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))a.o.kind==="uri"&&s.add(y(a.o.key,e.type,n))&&(t=!0)}return t}},se={name:"rdfs5",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.bySubjectPredicate(n,e.subPropertyOf))a.o.kind==="uri"&&s.add(y(o,e.subPropertyOf,a.o.key))&&(t=!0)}return t}},ie={name:"rdfs7",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(o)){let c={s:a.s,p:n,o:a.o};s.add(c)&&(t=!0)}}return t}},ce={name:"rdfs9",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},pe={name:"rdfs11",apply(s,e){let t=!1;for(let r of s.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.bySubjectPredicate(n,e.subClassOf))a.o.kind==="uri"&&s.add(y(o,e.subClassOf,a.o.key))&&(t=!0)}return t}},X=[oe,ae,se,ie,ce,pe];var le={name:"prp-trp",apply(s,e){let t=!1,r=s.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let o of r){let n=s.byPredicate(o);for(let a of n){if(a.o.kind!=="uri")continue;let c=a.o.key;for(let i of s.bySubjectPredicate(c,o))i.o.kind==="uri"&&a.s!==i.o.key&&s.add(y(a.s,o,i.o.key))&&(t=!0)}}return t}},ue={name:"prp-symp",apply(s,e){let t=!1,r=s.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let o of r)for(let n of s.byPredicate(o))n.o.kind==="uri"&&s.add(y(n.o.key,o,n.s))&&(t=!0);return t}},fe={name:"prp-inv1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(o))a.o.kind==="uri"&&s.add(y(a.o.key,n,a.s))&&(t=!0)}return t}},me={name:"prp-inv2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;for(let a of s.byPredicate(n))a.o.kind==="uri"&&s.add(y(a.o.key,o,a.s))&&(t=!0)}return t}},de={name:"prp-eqp1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(o))s.add({s:a.s,p:n,o:a.o})&&(t=!0)}return t}},ye={name:"prp-eqp2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicate(n))s.add({s:a.s,p:o,o:a.o})&&(t=!0)}return t}},ge={name:"cax-eqc1",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,o))s.add(y(a.s,e.type,n))&&(t=!0)}return t}},be={name:"cax-eqc2",apply(s,e){let t=!1;for(let r of s.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.byPredicateObject(e.type,n))s.add(y(a.s,e.type,o))&&(t=!0)}return t}},ke={name:"eq-rep-s",apply(s,e){let t=!1;for(let r of s.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n){for(let a of s.snapshot())a.s===o&&s.add({s:n,p:a.p,o:a.o})&&(t=!0);for(let a of s.snapshot())a.s===n&&s.add({s:o,p:a.p,o:a.o})&&(t=!0)}}return t}},he={name:"eq-rep-o",apply(s,e){let t=!1;for(let r of s.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let o=r.s,n=r.o.key;if(o!==n)for(let a of s.snapshot())a.o.kind==="uri"&&(a.o.key===o?s.add(y(a.s,a.p,n))&&(t=!0):a.o.key===n&&s.add(y(a.s,a.p,o))&&(t=!0))}return t}},Y=[le,ue,fe,me,de,ye,ge,be,ke,he];var L=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=T(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=T(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(o=>o!==t)}getSuperclasses(e){let t=T(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(T(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(T(e),this.vocabulary.type,T(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function T(s){return typeof s=="string"?s:g(s.publisher,s.package_,s.name)}var Q=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new _,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new D,o=await new W().parseKanonaks(e),n=new Z;for(let i of o)if(i instanceof v){let p=Ke(i);if(!p)continue;for(let l of i.statement)this.emitStatement(p,l,t,n)}let a=[...X];this.profile==="owl-rl-classification"&&a.push(...Y);let c=0;for(;c<this.maxIterations;){let i=!1;for(let p of a)p.apply(t,this.vocabulary)&&(i=!0);if(!i)break;c++}return new L(t,this.vocabulary)}emitStatement(e,t,r,o){let n=Re(t);if(n){if(t instanceof I){r.add({s:e,p:n,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof x){r.add({s:e,p:n,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof A){r.add({s:e,p:n,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof E){let a=U(t.object.subject);r.add(y(e,n,a));return}if(t instanceof $){let a=o.next();r.add({s:e,p:n,o:{kind:"blank",id:a}}),this.emitEmbedded(a,t.object,r,o);return}if(t instanceof O){for(let a of t.object??[])this.emitListItem(e,n,a,r,o);return}}}emitListItem(e,t,r,o,n){if(r instanceof m)o.add(y(e,t,U(r.subject)));else if(r instanceof R){let a=n.next();o.add({s:e,p:t,o:{kind:"blank",id:a}}),this.emitEmbedded(a,r,o,n)}else if(r instanceof w){let a=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";o.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:a}})}}emitEmbedded(e,t,r,o){let n=`_:${e}`;for(let a of t.statement)this.emitStatement(n,a,r,o)}},Z=class{counter=0;next(){return`b${this.counter++}`}};function Ke(s){let e=s.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),o=r.indexOf("/");if(o===-1)return null;let n=r.substring(0,o),a=r.substring(o+1);return!n||!a||!s.name?null:g(n,a,s.name)}function Re(s){let e=s.predicate;return e?.subject?U(e.subject):null}export{_ as KanonakVocabulary,Y as OWL_RL_CLASSIFICATION_RULES,X as RDFS_RULES,Q as Reasoner,L as ReasoningResult,D as TripleStore,g as makeUriKey,H as tripleKey,U as uriKey,y as uriTriple};
@@ -0,0 +1,2 @@
1
+ import type { Rule } from './Rule.js';
2
+ export declare const OWL_RL_CLASSIFICATION_RULES: Rule[];
@@ -0,0 +1,2 @@
1
+ import type { Rule } from './Rule.js';
2
+ export declare const RDFS_RULES: Rule[];
@@ -0,0 +1,19 @@
1
+ import type { TripleStore } from '../TripleStore.js';
2
+ import type { Vocabulary } from '../Vocabulary.js';
3
+ /**
4
+ * A single forward-chaining inference rule.
5
+ *
6
+ * `apply()` derives any new triples from the current contents of the
7
+ * store and adds them via `store.add()`. Returns `true` if at least
8
+ * one new triple was added in this pass — the engine keeps applying
9
+ * rules until every rule reports `false`, i.e. fixpoint is reached.
10
+ *
11
+ * Rule names follow the W3C OWL 2 Profiles spec
12
+ * (https://www.w3.org/TR/owl2-profiles/, §4.3) where applicable, so
13
+ * implementations can be cross-referenced with the standard.
14
+ */
15
+ export interface Rule {
16
+ /** Standard rule name, e.g. `"rdfs9"`, `"prp-trp"`. */
17
+ name: string;
18
+ apply(store: TripleStore, vocab: Vocabulary): boolean;
19
+ }
@@ -0,0 +1,3 @@
1
+ export type { Rule } from './Rule.js';
2
+ export { RDFS_RULES } from './RdfsRules.js';
3
+ export { OWL_RL_CLASSIFICATION_RULES } from './OwlRlRules.js';
@@ -11,6 +11,18 @@ export declare class PublisherIndex {
11
11
  });
12
12
  resolveVersion(publisher: string, import_: Import): Promise<string | null>;
13
13
  getHighestVersion(publisher: string, packageName: string): Promise<string | null>;
14
+ /**
15
+ * Returns the highest published version of every package in the
16
+ * publisher's index.
17
+ *
18
+ * Used by tooling that wants to enumerate a publisher's catalogue —
19
+ * e.g. building a per-publisher reasoning corpus, or implementing a
20
+ * `kanonak search <publisher>` browse command.
21
+ */
22
+ listLatestPackages(publisher: string): Promise<{
23
+ packageName: string;
24
+ version: string;
25
+ }[]>;
14
26
  getPackageUrl(publisher: string, packageName: string, version: string): Promise<string>;
15
27
  private getPackageVersions;
16
28
  private fetchIndex;