@kanonak-protocol/sdk 2.2.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +17 -17
- package/dist/index.d.ts +3 -3
- package/dist/index.js +50 -50
- package/dist/kanonaks/EmbeddedKanonak.d.ts +16 -0
- package/dist/parsing/KanonakDocumentPositions.d.ts +59 -0
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/resolution/KanonakAddress.d.ts +58 -0
- package/dist/resolution/KanonakUri.d.ts +49 -2
- package/dist/resolution/index.d.ts +2 -0
- package/dist/resolution/index.js +1 -1
- package/dist/validation/index.js +15 -15
- package/dist/validation/rules/repository/AmbiguousReferenceRule.d.ts +11 -0
- package/package.json +2 -2
|
@@ -1,3 +1,19 @@
|
|
|
1
1
|
import { DefinedKanonak } from './DefinedKanonak.js';
|
|
2
2
|
export declare class EmbeddedKanonak extends DefinedKanonak {
|
|
3
|
+
/**
|
|
4
|
+
* Optional source label for this embedded kanonak. Populated when
|
|
5
|
+
* the embedded was authored as the value of a dict-keyed list entry
|
|
6
|
+
* — e.g. `hasConvention: { file-location: { ... } }` produces an
|
|
7
|
+
* EmbeddedKanonak with `name = "file-location"`. Empty for embeddeds
|
|
8
|
+
* authored as positional list items (`- ...`) or as the single
|
|
9
|
+
* value of a property (`hasConvention: { summary: ... }`).
|
|
10
|
+
*
|
|
11
|
+
* Carries no semantic identity — the dict key isn't a URI, isn't
|
|
12
|
+
* resolved against imports, and isn't part of any RDF triple. It's
|
|
13
|
+
* purely a presentation hint for human-facing tools (Outline, tree
|
|
14
|
+
* views, error messages) so the dict-keyed authoring form doesn't
|
|
15
|
+
* lose its author-given labels when the parser flattens the dict
|
|
16
|
+
* into a positional list of anonymous embeddeds.
|
|
17
|
+
*/
|
|
18
|
+
name?: string;
|
|
3
19
|
}
|
|
@@ -80,6 +80,31 @@ export declare class KanonakDocumentPositions {
|
|
|
80
80
|
private readonly valueListItems;
|
|
81
81
|
/** entity name → list of import-package entries with source positions. */
|
|
82
82
|
private readonly importPackages;
|
|
83
|
+
/**
|
|
84
|
+
* Path-keyed positions for ARBITRARILY nested keys/values. Built by
|
|
85
|
+
* a recursive YAML CST walk that records, at every depth, the
|
|
86
|
+
* position of each map key and the position of each map/sequence
|
|
87
|
+
* value. The path is a `(string | number)[]` — string segments for
|
|
88
|
+
* dict keys, number segments for sequence indices — serialized as
|
|
89
|
+
* JSON for use as a Map key.
|
|
90
|
+
*
|
|
91
|
+
* Example for `foo: { bar: { baz: x } }`:
|
|
92
|
+
* - nestedKeys[`["foo","bar","baz"]`] = position of `baz:` token
|
|
93
|
+
* - nestedValues[`["foo","bar","baz"]`] = position of `x`
|
|
94
|
+
*
|
|
95
|
+
* Example for `foo: [{a: 1}, {b: 2}]`:
|
|
96
|
+
* - nestedValues[`["foo",0]`] = position of `{a: 1}` block
|
|
97
|
+
* - nestedKeys[`["foo",0,"a"]`] = position of `a:` token
|
|
98
|
+
* - nestedValues[`["foo",0,"a"]`] = position of `1`
|
|
99
|
+
*
|
|
100
|
+
* Used by symbol-intelligence providers (Outline) that need to
|
|
101
|
+
* navigate to a precise location within a deeply-nested embedded
|
|
102
|
+
* value. The shallower entity-level / property-level / list-item
|
|
103
|
+
* maps above continue to back the existing single-level lookups
|
|
104
|
+
* for backward compatibility and call-site clarity.
|
|
105
|
+
*/
|
|
106
|
+
private readonly nestedKeys;
|
|
107
|
+
private readonly nestedValues;
|
|
83
108
|
/**
|
|
84
109
|
* Parse `content` as YAML and build the position index.
|
|
85
110
|
*
|
|
@@ -175,6 +200,40 @@ export declare class KanonakDocumentPositions {
|
|
|
175
200
|
* `subClassOf: [GoodA, BadB, GoodC]` list).
|
|
176
201
|
*/
|
|
177
202
|
getListItemPosition(entityName: string, propertyName: string, listIndex: number): SourcePosition | undefined;
|
|
203
|
+
/**
|
|
204
|
+
* Position of the KEY at an arbitrary nested path. The path is a
|
|
205
|
+
* `(string | number)[]` — string for dict keys, number for sequence
|
|
206
|
+
* indices. For path `[entity, property, key]`, returns the position
|
|
207
|
+
* of `key:` within `entity.property`. For path `[entity]`, returns
|
|
208
|
+
* the entity's key (same as `getEntityPosition`).
|
|
209
|
+
*
|
|
210
|
+
* Sequence items don't have a "key" — for path that ends in a
|
|
211
|
+
* number, returns `undefined` (use `getNodeValuePosition` instead).
|
|
212
|
+
*
|
|
213
|
+
* Returns `undefined` when the path doesn't resolve to a key in the
|
|
214
|
+
* source document (e.g. statement was synthesized by the SDK rather
|
|
215
|
+
* than authored, or the path is malformed).
|
|
216
|
+
*/
|
|
217
|
+
getNodeKeyPosition(path: ReadonlyArray<string | number>): SourcePosition | undefined;
|
|
218
|
+
/**
|
|
219
|
+
* Position of the VALUE at an arbitrary nested path. For map values,
|
|
220
|
+
* the value's range (e.g. the inner block of an embedded object).
|
|
221
|
+
* For sequence items, the item's range (same as
|
|
222
|
+
* `getListItemPosition` for top-level list items, but works at any
|
|
223
|
+
* depth). For path `[entity]`, returns the entity's body range
|
|
224
|
+
* (the value after the entity's `:`); for path `[entity, prop]`,
|
|
225
|
+
* the property's value range (same as `getPropertyValuePosition`).
|
|
226
|
+
*/
|
|
227
|
+
getNodeValuePosition(path: ReadonlyArray<string | number>): SourcePosition | undefined;
|
|
228
|
+
/**
|
|
229
|
+
* Internal: setters used by the recursive walker. Public-on-the-
|
|
230
|
+
* class but not part of the documented API — exposed only because
|
|
231
|
+
* the walker is a free function (operates on the yaml CST directly,
|
|
232
|
+
* which the class itself doesn't import beyond `fromContent`'s
|
|
233
|
+
* scope).
|
|
234
|
+
*/
|
|
235
|
+
setNestedKeyPosition(pathKey: string, pos: SourcePosition): void;
|
|
236
|
+
setNestedValuePosition(pathKey: string, pos: SourcePosition): void;
|
|
178
237
|
/**
|
|
179
238
|
* Most-specific available position for a diagnostic, falling
|
|
180
239
|
* through from list-item → property-value → property-key → entity.
|
package/dist/parsing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Q=Object.defineProperty;var Z=(u,e)=>()=>(u&&(e=u(u=0)),e);var ee=(u,e)=>{for(var t in e)Q(u,t,{get:e[t],enumerable:!0})};var G={};ee(G,{KanonakUri:()=>K});var K,q=Z(()=>{"use strict";K=class u{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 s=o.split(".").map(Number),i={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:a=>!a||typeof a!="object"?!1:a.major===(s[0]||0)&&a.minor===(s[1]||0)&&a.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:a=>(s[0]||0)!==a.major?(s[0]||0)-a.major:(s[1]||0)!==a.minor?(s[1]||0)-a.minor:(s[2]||0)-a.patch};return new u(n[0],n[1],n[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as F from"js-yaml";var w=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),s=this.extractBody(o,n);return r={metadata:n,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(o){let n=o,s={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(s),{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,s=o.publisher,i=o.version?this.parseVersion(o.version):void 0;return s&&n&&(t.namespace_={publisher:s,package_:n,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===s&&a.package_===n&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c);for(let c=0;c<n.length;c++)a=(a<<5)-a+n.charCodeAt(c);return a|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,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){o=n;break}for(let[n,s]of Object.entries(e))n!==o&&n!=="kanonak"&&n!=="namespace"&&n!=="imports"&&(r[n]=s);return r}parseNamespace(e){if(typeof e=="string"){let n=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(n){let s=n[3]?this.parseVersion(n[3]):this.createVersion(1,0,0);return{publisher:n[1],package_:n[2],version:s,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===n[1]&&i.package_===n[2]&&(!s||!i.version||s.equals(i.version)),getHashCode:()=>{let i=0;for(let a=0;a<n[1].length;a++)i=(i<<5)-i+n[1].charCodeAt(a);for(let a=0;a<n[2].length;a++)i=(i<<5)-i+n[2].charCodeAt(a);return i|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 s=0;s<t.length;s++)n=(n<<5)-n+t.charCodeAt(s);for(let s=0;s<r.length;s++)n=(n<<5)-n+r.charCodeAt(s);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 s=this.parseImportFromEmbeddedObject(n,o);t[o].push(s)}}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 s=this.parseVersion(n),i=this.parseVersionOperator(o),a=this.calculateMaxVersion(o,s),c=e.alias;return{package_:`${r} ${o} ${s.toString()}`,publisher:t,packageName:r,versionOperator:i,version:s,alias:c,minVersion:s,maxVersion:a,toEmbeddedObject:()=>{let p={package:r,match:o,version:s.toString()};return c&&(p.alias=c),p},toString:()=>c?`${r} ${o} ${s.toString()} as ${c}`:`${r} ${o} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let p=a[1].trim(),m=a[2],l=this.parseVersion(a[3].trim()),f=a[4].trim(),d=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:l,alias:f,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let g={package:p,match:m,version:l.toString()};return f&&(g.alias=f),g},toString:()=>`${p} ${m} ${l.toString()} as ${f}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),f=this.parseVersionOperator(m),d=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:l,alias:void 0,minVersion:l,maxVersion:d,toEmbeddedObject:()=>({package:p,match:m,version:l.toString()}),toString:()=>`${p} ${m} ${l.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),o=this.parseVersion(e.version||"1.0.0"),n=e.packageName||e.package||"",s=["=","~","^","*"][r],i=this.calculateMaxVersion(e.operator||"~",o);return{package_:e.package||"",publisher:t,packageName:n,versionOperator:r,version:o,alias:e.alias,minVersion:o,maxVersion:i,toEmbeddedObject:()=>{let a={package:n,match:s,version:o.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${n} ${s} ${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(s=>{let i=["=","~","^","*"][s.versionOperator],a={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(a.alias=s.alias),a})};t.push(n)}return t}};var S=class{};var E=class extends S{statement=[]};var j=class extends E{namespace;name;icon};var $=class extends E{};q();var y=class u extends S{subject;static parse(e){let t=new u;return t.subject=K.parse(e),t}};var M=class extends S{value};var v=class{predicate;object};var I=class extends v{};var A=class u extends I{static parse(e,t){let r=new u;return r.predicate=y.parse(e),r.object=t,r}};var _=class u extends I{static parse(e,t){let r=new u;return r.predicate=y.parse(e),r.object=t,r}};var N=class extends I{};var L=class u extends v{static parse(e,t){let r=new u;return r.predicate=y.parse(e),r.object=y.parse(t),r}};var D=class extends v{};var V=class extends v{};q();function H(u){if(Array.isArray(u))return u.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=u?.toString();return e?[e]:[]}var W=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 s=o.get(e);if(s)return s}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],s=o[1],i=await this.findDocumentForAlias(t,n);return i?await this.resolveAllEntitiesAsync(s,i):[]}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 s=r.length===0?n:`${r} \u2192 ${n}`;for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.push({entityName:i,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:a,definedInNamespace:n,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${o.length} entities from ${n}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((a,c)=>a+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${n}`);for(let[a,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${a}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(a,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,s);o.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${p.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${a}/${p.packageName} for namespace ${n}. Error: ${l.message}`,l),new Error(`Failed to process import ${a}/${p.packageName} for namespace ${n}. See inner exception for details.`,{cause:m})}}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 s=r.length===0?n:`${r} \u2192 ${n}`,i=0;for(let[a,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!o.has(a)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.set(a,{entityName:a,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:c,definedInNamespace:n,isImported:r.length>0,importPath:s}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${n}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${n}`);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 f=await this.buildEntityIndexAsyncInternal(l,t,s),d=0;for(let[h,g]of f.entries())if(o.has(h)||(o.set(h,g),d++),m.alias&&!h.includes(".")){let P=`${m.alias}.${h}`;o.has(P)||(o.set(P,g),d++)}this.logger?.debug?.(`Merged ${d} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let f=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${n}. Error: ${f.message}`,f),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${n}. See inner exception for details.`,{cause:l})}}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 s=n.entity.subClassOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubclassOfRecursiveAsync(a,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 s=n.entity.subPropertyOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,r,o))return!0}return!1}};var X=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 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))}};var U=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),o=new W(e),n=new X(o);for(let s of r)for(let[i,a]of Object.entries(s.body)){let c=new j;c.namespace=s.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(a,s,o,n,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,r,o,n){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[i,a]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,r,n,o);if(!c)continue;let p=await this.parsePropertyValue(i,a,c,t,r,o);p&&s.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return s}async getPropertyMetadata(e,t,r,o,n){let s=await r.resolveEntityAsync(e,t);if(!s)return;let i=s.entity,a=i.type?.toString()??"",c=a.includes(".")?a.substring(a.lastIndexOf(".")+1):a;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=n.getPropertyTypeClassification(a),l=i.range?.toString(),f;if(m==="ObjectProperty")f="ObjectProperty";else if(m==="DatatypeProperty")f="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?n.isKnownXsdDatatypeName(l):!1)||h==="Literal"?f="DatatypeProperty":f="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:f,range:l,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,o,n,s){let i=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,r,o,n,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,r,o,n,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return A.parse(e,t.toISOString());if(typeof t=="string")return A.parse(e,t);if(typeof t=="number")return _.parse(e,t);if(typeof t=="boolean"){let o=new N;return o.predicate=y.parse(e),o.object=t,o}}async parseObjectValue(e,t,r,o,n,s){if(typeof t=="string"){let i=await this.resolveReference(t,o,n);if(!i)return;let a=new L;return a.predicate=y.parse(e),a.object=i,a}if(typeof t=="object"&&!Array.isArray(t)){let i=new $;if(i.statement=await this.parseStatements(t,o,n,s,{}),i.statement.length>0){let p=new D;return p.predicate=y.parse(e),p.object=i,p}let a=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new $;m.statement=await this.parseStatements(p,o,n,s,{}),a.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,o,n);m&&a.push(m)}if(a.length>0){let p=new V;return p.predicate=y.parse(e),p.object=a,p}let c=new D;return c.predicate=y.parse(e),c.object=i,c}}async parseListValue(e,t,r,o,n,s){let i=[],a=r.propertyType==="DatatypeProperty";for(let p of t){if(a&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let m=new M;m.value=p,i.push(m);continue}if(a&&p instanceof Date){let m=new M;m.value=p.toISOString(),i.push(m);continue}if(typeof p=="string"){let m=await this.resolveReference(p,o,n);m&&i.push(m)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new $;m.statement=await this.parseStatements(p,o,n,s,{}),i.push(m)}}let c=new V;return c.predicate=y.parse(e),c.object=i,c}async resolveReference(e,t,r){let o=await r.resolveEntityAsync(e,t);if(o){let s=new y;return s.subject=o.uri,s}let n=t.metadata?.namespace_;if(n){let{KanonakUri:s}=await Promise.resolve().then(()=>(q(),G)),i=n.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,f]of Object.entries(t.metadata.imports))for(let d of f)if((d.alias??d.packageName)===p){let g=new y;return g.subject=new s(l,d.packageName,m,d.version),g}}}let a=new y;return a.subject=new s(n.publisher,n.package_,e,i),a}return null}async saveKanonaks(e,t){let r=new Map;for(let o of e)o instanceof j&&o.namespace&&(r.has(o.namespace)||r.set(o.namespace,[]),r.get(o.namespace).push(o));for(let[o,n]of r){let s=await this.convertKanonaksToDocument(o,n),i=`${o.split("@")[0]}.yml`;await t.saveDocumentAsync(s,i)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof j&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let o=await this.convertKanonaksToDocument(t,r);return new w().save(o)}async convertKanonaksToDocument(e,t){let o={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let i of Object.values(this.imports))s.push(...i);return s}},body:{}},n=new Map;for(let s of t){let i={};for(let a of s.statement){let[c,p]=this.convertStatementToProperty(a);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(a,e,n)}o.body[s.name]=i}return o}convertStatementToProperty(e){if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof _)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object];if(e instanceof L)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof V){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof D){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 y?t.push(r.subject.name):r instanceof $&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[o,n]=this.convertStatementToProperty(r);o&&n!==null&&n!==void 0&&(t[o]=n)}return t}collectImportsFromStatement(e,t,r){}};var Y=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as te,LineCounter as re,isMap as T,isPair as k,isScalar as b,isSeq as z}from"yaml";var C=class u{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;static fromContent(e){let t=new u,r=new re,o=te(e,{lineCounter:r});if(o.errors.length>0||!T(o.contents))return t;for(let n of o.contents.items){if(!k(n)||!b(n.key))continue;let s=String(n.key.value),i=n.key.range;if(!i)continue;t.entities.set(s,R(i,r));let a=n.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?t.entityBlocks.set(s,R([i[0],i[1],c[2]],r)):t.entityBlocks.set(s,R(i,r)),T(n.value)){let p=new Map,m=new Map,l=new Map;for(let d of n.value.items){if(!k(d)||!b(d.key))continue;let h=String(d.key.value),g=d.key.range;g&&p.set(h,R(g,r));let P=d.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let x=P.range;m.set(h,R(x,r))}if(z(P)){let x=[];for(let O of P.items)O&&typeof O=="object"&&"range"in O&&Array.isArray(O.range)&&x.push(R(O.range,r));x.length>0&&l.set(h,x)}}p.size>0&&t.properties.set(s,p),m.size>0&&t.propertyValues.set(s,m),l.size>0&&t.valueListItems.set(s,l);let f=ne(n.value,r);f.length>0&&t.importPackages.set(s,f)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,o]of this.entityBlocks)if(B(o,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let o=this.properties.get(r),n=this.propertyValues.get(r);if(!o&&!n)return{entityName:r};let s,i;if(n)for(let[a,c]of n)B(c,e,t)&&(!i||J(c,i))&&(s=a,i=c);if(o)for(let[a,c]of o)B(c,e,t)&&(!i||J(c,i))&&(s=a,i=c);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let o of r)e.push({entityName:t,entry:o});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let o of r.keys()){let n=o.lastIndexOf(".");if((n===-1?o:o.substring(n+1))===t)return o}}}getListItemPosition(e,t,r){let o=this.valueListItems.get(e)?.get(t);if(!(!o||r<0||r>=o.length))return o[r]}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let o=this.getPropertyValuePosition(e,t);if(o)return o;let n=this.getPropertyPosition(e,t);if(n)return n}return this.getEntityPosition(e)}}};function ne(u,e){let t=[];if(!T(u))return t;let r=u.items.find(o=>k(o)&&b(o.key)&&String(o.key.value)==="imports");if(!r||!k(r)||!z(r.value))return t;for(let o of r.value.items){if(!T(o))continue;let n=o.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="publisher");if(!n||!k(n)||!b(n.value))continue;let s=String(n.value.value),i=o.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="packages");if(!(!i||!k(i)||!z(i.value)))for(let a of i.value.items){if(!T(a))continue;let c=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="package");if(!c||!k(c)||!b(c.value)||!c.value.range)continue;let p=String(c.value.value),m=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="version"),l=m&&k(m)&&b(m.value)?String(m.value.value):"",f=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="alias"),d=f&&k(f)&&b(f.value)?String(f.value.value):void 0,h=d!==void 0?{publisher:s,package_:p,version:l,alias:d,position:R(c.value.range,e)}:{publisher:s,package_:p,version:l,position:R(c.value.range,e)};t.push(h)}}return t}function B(u,e,t){return!(e<u.line||e>u.endLine||e===u.line&&t<u.column||e===u.endLine&&t>u.endColumn)}function J(u,e){let t=u.endLine-u.line,r=e.endLine-e.line;if(t!==r)return t<r;let o=u.endLine===u.line?u.endColumn-u.column:Number.MAX_SAFE_INTEGER,n=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return o<n}function R(u,e){let t=e.linePos(u[0]),r=e.linePos(u[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function oe(u,e){let r=(e??new w).parse(u),o=C.fromContent(u);return{document:r,positions:o}}export{C as KanonakDocumentPositions,U as KanonakObjectParser,w as KanonakParser,Y as PropertyMetadata,oe as parseWithPositions};
|
|
1
|
+
var ee=Object.defineProperty;var te=(p,e)=>()=>(p&&(e=p(p=0)),e);var re=(p,e)=>{for(var t in e)ee(p,t,{get:e[t],enumerable:!0})};var J={};re(J,{KanonakUri:()=>R});function ne(p,e,t){return{major:p,minor:e,patch:t,toString:()=>`${p}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===p&&r.minor===e&&r.patch===t,getHashCode:()=>p<<20|e<<10|t,compareTo:r=>p!==r.major?p-r.major:e!==r.minor?e-r.minor:t-r.patch}}var R,q=te(()=>{"use strict";R=class p{constructor(e,t,r,n){this.publisher=e;this.package_=t;this.name=r;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("/");if(t.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let s=n.indexOf("@");if(s===-1)return new p(r,n,o,void 0);let i=n.substring(0,s),a=n.substring(s+1);if(!i||!a)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let c=a.split(".").map(Number),u=ne(c[0]||0,c[1]||0,c[2]||0);return new p(r,i,o,u)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});import*as F from"js-yaml";var w=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=F.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let o=this.extractMetadata(n),s=this.extractBody(n,o);return r={metadata:o,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let o=n,s={message:o.message||"Unknown parse error",line:o.mark?.line??0,column:o.mark?.column??0,errorType:o.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${o.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${o.mark?.line??0}: ${o.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),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 n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:o=>!o||typeof o!="object"?!1:o.major===e&&o.minor===t&&o.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:o=>e!==o.major?e-o.major:t!==o.minor?t-o.minor:r-o.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let o=r,s=n.publisher,i=n.version?this.parseVersion(n.version):void 0;return s&&o&&(t.namespace_={publisher:s,package_:o,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===s&&a.package_===o&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c);for(let c=0;c<o.length;c++)a=(a<<5)-a+o.charCodeAt(c);return a|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[o,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){n=o;break}for(let[o,s]of Object.entries(e))o!==n&&o!=="kanonak"&&o!=="namespace"&&o!=="imports"&&(r[o]=s);return r}parseNamespace(e){if(typeof e=="string"){let o=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(o){let s=o[3]?this.parseVersion(o[3]):this.createVersion(1,0,0);return{publisher:o[1],package_:o[2],version:s,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===o[1]&&i.package_===o[2]&&(!s||!i.version||s.equals(i.version)),getHashCode:()=>{let i=0;for(let a=0;a<o[1].length;a++)i=(i<<5)-i+o[1].charCodeAt(a);for(let a=0;a<o[2].length;a++)i=(i<<5)-i+o[2].charCodeAt(a);return i|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===t&&o.package_===r&&(!n||!o.version||n.equals(o.version)),getHashCode:()=>{let o=0;for(let s=0;s<t.length;s++)o=(o<<5)-o+t.charCodeAt(s);for(let s=0;s<r.length;s++)o=(o<<5)-o+r.charCodeAt(s);return o|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let o of r.packages){if(!o||typeof o!="object")continue;let s=this.parseImportFromEmbeddedObject(o,n);t[n].push(s)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),o=n.publisher||"";t[o]||(t[o]=[]),t[o].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(o=>this.parseImport(o,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let o=e.version;if(!o)throw new Error("Import requires 'version' property");let s=this.parseVersion(o),i=this.parseVersionOperator(n),a=this.calculateMaxVersion(n,s),c=e.alias;return{package_:`${r} ${n} ${s.toString()}`,publisher:t,packageName:r,versionOperator:i,version:s,alias:c,minVersion:s,maxVersion:a,toEmbeddedObject:()=>{let u={package:r,match:n,version:s.toString()};return c&&(u.alias=c),u},toString:()=>c?`${r} ${n} ${s.toString()} as ${c}`:`${r} ${n} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let u=a[1].trim(),m=a[2],l=this.parseVersion(a[3].trim()),f=a[4].trim(),d=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:d,version:l,alias:f,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let g={package:u,match:m,version:l.toString()};return f&&(g.alias=f),g},toString:()=>`${u} ${m} ${l.toString()} as ${f}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let u=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),f=this.parseVersionOperator(m),d=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:u,versionOperator:f,version:l,alias:void 0,minVersion:l,maxVersion:d,toEmbeddedObject:()=>({package:u,match:m,version:l.toString()}),toString:()=>`${u} ${m} ${l.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),o=e.packageName||e.package||"",s=["=","~","^","*"][r],i=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:o,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:i,toEmbeddedObject:()=>{let a={package:o,match:s,version:n.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${o} ${s} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let o={publisher:r,packages:n.map(s=>{let i=["=","~","^","*"][s.versionOperator],a={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(a.alias=s.alias),a})};t.push(o)}return t}};var K=class{};var E=class extends K{statement=[]};var A=class extends E{namespace;name;icon};var $=class extends E{name};q();var y=class p extends K{subject;static parse(e){let t=new p;return t.subject=R.parse(e),t}};var _=class extends K{value};var S=class{predicate;object};var I=class extends S{};var V=class p extends I{static parse(e,t){let r=new p;return r.predicate=y.parse(e),r.object=t,r}};var N=class p extends I{static parse(e,t){let r=new p;return r.predicate=y.parse(e),r.object=t,r}};var L=class extends I{};var T=class p extends S{static parse(e,t){let r=new p;return r.predicate=y.parse(e),r.object=y.parse(t),r}};var j=class extends S{};var D=class extends S{};q();function H(p){if(Array.isArray(p))return p.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=p?.toString();return e?[e]:[]}var W=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(r);if(n){let s=n.get(e);if(s)return s}let o=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,o),o.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),o=n[0],s=n[1],i=await this.findDocumentForAlias(t,o);return i?await this.resolveAllEntitiesAsync(s,i):[]}return r.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let n=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`;for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:i,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:a,definedInNamespace:o,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((a,c)=>a+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[a,c]of Object.entries(e.metadata.imports))for(let u of c)try{this.logger?.debug?.(`Resolving import: ${a}/${u.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(a,u);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,s);n.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${u.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${a}/${u.packageName} for namespace ${o}. Error: ${l.message}`,l),new Error(`Failed to process import ${a}/${u.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let n=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),n;t.add(o);let s=r.length===0?o:`${r} \u2192 ${o}`,i=0;for(let[a,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!n.has(a)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(a,{entityName:a,uri:new R(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,u),entity:c,definedInNamespace:o,isImported:r.length>0,importPath:s}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${o}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,u)=>c+u.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${o}`);for(let[c,u]of Object.entries(e.metadata.imports))for(let m of u)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 f=await this.buildEntityIndexAsyncInternal(l,t,s),d=0;for(let[h,g]of f.entries())if(n.has(h)||(n.set(h,g),d++),m.alias&&!h.includes(".")){let P=`${m.alias}.${h}`;n.has(P)||(n.set(P,g),d++)}this.logger?.debug?.(`Merged ${d} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let f=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${o}. Error: ${f.message}`,f),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,n]of Object.entries(e.metadata.imports))for(let o of n){if(o.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,o);if(!o.alias&&o.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,n)}async isSubclassOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subClassOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,r,n))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,n)}async isSubpropertyOfRecursiveAsync(e,t,r,n){if(n.has(e))return!1;n.add(e);let o=await this.resolveEntityAsync(e,r);if(!o?.entity)return!1;let s=o.entity.subPropertyOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,r,n))return!0}return!1}};var U=class p{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"&&p.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 p.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let n=r.entity.type;if(n){let o=String(n);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var Y=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),n=new W(e),o=new U(n);for(let s of r)for(let[i,a]of Object.entries(s.body)){let c=new A;c.namespace=s.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let u=await this.parseStatements(a,s,n,o,e);c.statement.push(...u),t.push(c)}return t}async parseStatements(e,t,r,n,o){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[i,a]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,r,o,n);if(!c)continue;let u=await this.parsePropertyValue(i,a,c,t,r,n);u&&s.push(u)}catch(c){console.error(`Error parsing property ${i}:`,c)}return s}async getPropertyMetadata(e,t,r,n,o){let s=await r.resolveEntityAsync(e,t);if(!s)return;let i=s.entity,a=i.type?.toString()??"",c=a.includes(".")?a.substring(a.lastIndexOf(".")+1):a;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=o.getPropertyTypeClassification(a),l=i.range?.toString(),f;if(m==="ObjectProperty")f="ObjectProperty";else if(m==="DatatypeProperty")f="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?o.isKnownXsdDatatypeName(l):!1)||h==="Literal"?f="DatatypeProperty":f="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:f,range:l,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,n,o,s){let i=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,r,n,o,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,r,n,o,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return V.parse(e,t.toISOString());if(typeof t=="string")return V.parse(e,t);if(typeof t=="number")return N.parse(e,t);if(typeof t=="boolean"){let n=new L;return n.predicate=y.parse(e),n.object=t,n}}async parseObjectValue(e,t,r,n,o,s){if(typeof t=="string"){let i=await this.resolveReference(t,n,o);if(!i)return;let a=new T;return a.predicate=y.parse(e),a.object=i,a}if(typeof t=="object"&&!Array.isArray(t)){let i=new $;if(i.statement=await this.parseStatements(t,n,o,s,{}),i.statement.length>0){let u=new j;return u.predicate=y.parse(e),u.object=i,u}let a=[];for(let[u,m]of Object.entries(t))if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let l=new $;l.name=u,l.statement=await this.parseStatements(m,n,o,s,{}),a.push(l)}else if(typeof m=="string"){let l=await this.resolveReference(m,n,o);l&&a.push(l)}if(a.length>0){let u=new D;return u.predicate=y.parse(e),u.object=a,u}let c=new j;return c.predicate=y.parse(e),c.object=i,c}}async parseListValue(e,t,r,n,o,s){let i=[],a=r.propertyType==="DatatypeProperty";for(let u of t){if(a&&(typeof u=="string"||typeof u=="number"||typeof u=="boolean")){let m=new _;m.value=u,i.push(m);continue}if(a&&u instanceof Date){let m=new _;m.value=u.toISOString(),i.push(m);continue}if(typeof u=="string"){let m=await this.resolveReference(u,n,o);m&&i.push(m)}else if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let m=new $;m.statement=await this.parseStatements(u,n,o,s,{}),i.push(m)}}let c=new D;return c.predicate=y.parse(e),c.object=i,c}async resolveReference(e,t,r){let n=await r.resolveEntityAsync(e,t);if(n){let s=new y;return s.subject=n.uri,s}let o=t.metadata?.namespace_;if(o){let{KanonakUri:s}=await Promise.resolve().then(()=>(q(),J)),i=o.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),u=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,f]of Object.entries(t.metadata.imports))for(let d of f)if((d.alias??d.packageName)===u){let g=new y;return g.subject=new s(l,d.packageName,m,d.version),g}}}let a=new y;return a.subject=new s(o.publisher,o.package_,e,i),a}return null}async saveKanonaks(e,t){let r=new Map;for(let n of e)n instanceof A&&n.namespace&&(r.has(n.namespace)||r.set(n.namespace,[]),r.get(n.namespace).push(n));for(let[n,o]of r){let s=await this.convertKanonaksToDocument(n,o),i=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(s,i)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof A&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,r);return new w().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let i of Object.values(this.imports))s.push(...i);return s}},body:{}},o=new Map;for(let s of t){let i={};for(let a of s.statement){let[c,u]=this.convertStatementToProperty(a);c&&u!==null&&u!==void 0&&(i[c]=u),this.collectImportsFromStatement(a,e,o)}n.body[s.name]=i}return n}convertStatementToProperty(e){if(e instanceof V)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object];if(e instanceof L)return[e.predicate.subject.name,e.object];if(e instanceof T)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof D){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof j){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 y?t.push(r.subject.name):r instanceof $&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[n,o]=this.convertStatementToProperty(r);n&&o!==null&&o!==void 0&&(t[n]=o)}return t}collectImportsFromStatement(e,t,r){}};var B=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as oe,LineCounter as se,isMap as x,isPair as k,isScalar as b,isSeq as X}from"yaml";var C=class p{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new p,r=new se,n=oe(e,{lineCounter:r});if(n.errors.length>0||!x(n.contents))return t;G(n.contents,[],r,t);for(let o of n.contents.items){if(!k(o)||!b(o.key))continue;let s=String(o.key.value),i=o.key.range;if(!i)continue;t.entities.set(s,v(i,r));let a=o.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?t.entityBlocks.set(s,v([i[0],i[1],c[2]],r)):t.entityBlocks.set(s,v(i,r)),x(o.value)){let u=new Map,m=new Map,l=new Map;for(let d of o.value.items){if(!k(d)||!b(d.key))continue;let h=String(d.key.value),g=d.key.range;g&&u.set(h,v(g,r));let P=d.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let O=P.range;m.set(h,v(O,r))}if(X(P)){let O=[];for(let M of P.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&O.push(v(M.range,r));O.length>0&&l.set(h,O)}}u.size>0&&t.properties.set(s,u),m.size>0&&t.propertyValues.set(s,m),l.size>0&&t.valueListItems.set(s,l);let f=ae(o.value,r);f.length>0&&t.importPackages.set(s,f)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,n]of this.entityBlocks)if(z(n,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let n=this.properties.get(r),o=this.propertyValues.get(r);if(!n&&!o)return{entityName:r};let s,i;if(o)for(let[a,c]of o)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);if(n)for(let[a,c]of n)z(c,e,t)&&(!i||Q(c,i))&&(s=a,i=c);return s?{entityName:r,propertyName:s}:{entityName:r}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,r]of this.importPackages)for(let n of r)e.push({entityName:t,entry:n});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let n of r.keys()){let o=n.lastIndexOf(".");if((o===-1?n:n.substring(o+1))===t)return n}}}getListItemPosition(e,t,r){let n=this.valueListItems.get(e)?.get(t);if(!(!n||r<0||r>=n.length))return n[r]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let n=this.getPropertyValuePosition(e,t);if(n)return n;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function ae(p,e){let t=[];if(!x(p))return t;let r=p.items.find(n=>k(n)&&b(n.key)&&String(n.key.value)==="imports");if(!r||!k(r)||!X(r.value))return t;for(let n of r.value.items){if(!x(n))continue;let o=n.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="publisher");if(!o||!k(o)||!b(o.value))continue;let s=String(o.value.value),i=n.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="packages");if(!(!i||!k(i)||!X(i.value)))for(let a of i.value.items){if(!x(a))continue;let c=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="package");if(!c||!k(c)||!b(c.value)||!c.value.range)continue;let u=String(c.value.value),m=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="version"),l=m&&k(m)&&b(m.value)?String(m.value.value):"",f=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="alias"),d=f&&k(f)&&b(f.value)?String(f.value.value):void 0,h=d!==void 0?{publisher:s,package_:u,version:l,alias:d,position:v(c.value.range,e)}:{publisher:s,package_:u,version:l,position:v(c.value.range,e)};t.push(h)}}return t}function z(p,e,t){return!(e<p.line||e>p.endLine||e===p.line&&t<p.column||e===p.endLine&&t>p.endColumn)}function Q(p,e){let t=p.endLine-p.line,r=e.endLine-e.line;if(t!==r)return t<r;let n=p.endLine===p.line?p.endColumn-p.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return n<o}function G(p,e,t,r){if(x(p)){for(let n of p.items){if(!k(n)||!b(n.key))continue;let o=String(n.key.value),s=[...e,o],i=JSON.stringify(s);n.key.range&&r.setNestedKeyPosition(i,v(n.key.range,t));let a=n.value,c=Z(a);c&&r.setNestedValuePosition(i,v(c,t)),G(a,s,t,r)}return}if(X(p)){for(let n=0;n<p.items.length;n++){let o=p.items[n],s=[...e,n],i=JSON.stringify(s),a=Z(o);a&&r.setNestedValuePosition(i,v(a,t)),G(o,s,t,r)}return}}function Z(p){if(!p||typeof p!="object"||!("range"in p))return;let e=p.range;return Array.isArray(e)&&e.length>=3?e:void 0}function v(p,e){let t=e.linePos(p[0]),r=e.linePos(p[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function ie(p,e){let r=(e??new w).parse(p),n=C.fromContent(p);return{document:r,positions:n}}export{C as KanonakDocumentPositions,Y as KanonakObjectParser,w as KanonakParser,B as PropertyMetadata,ie as parseWithPositions};
|
package/dist/reasoning/index.js
CHANGED
|
@@ -1 +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};
|
|
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});function oe(s,e,t){return{major:s,minor:e,patch:t,toString:()=>`${s}.${e}.${t}`,equals:r=>!r||typeof r!="object"?!1:r.major===s&&r.minor===e&&r.patch===t,getHashCode:()=>s<<20|e<<10|t,compareTo:r=>s!==r.major?s-r.major:e!==r.minor?e-r.minor:t-r.patch}}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!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[r,o,n]=t;if(!r||!o||!n)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let a=o.indexOf("@");if(a===-1)return new s(r,o,n,void 0);let c=o.substring(0,a),i=o.substring(a+1);if(!c||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let p=i.split(".").map(Number),l=oe(p[0]||0,p[1]||0,p[2]||0);return new s(r,c,n,l)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}}});var v=class{};var V=class extends v{statement=[]};var S=class extends V{namespace;name;icon};var R=class extends V{name};C();var m=class s extends v{subject;static parse(e){let t=new s;return t.subject=P.parse(e),t}};var w=class extends v{value};var k=class{predicate;object};var I=class extends k{};var j=class s extends I{static parse(e,t){let r=new s;return r.predicate=m.parse(e),r.object=t,r}};var x=class s extends I{static parse(e,t){let r=new s;return r.predicate=m.parse(e),r.object=t,r}};var A=class extends I{};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 S;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 j.parse(e,t.toISOString());if(typeof t=="string")return j.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,u]of Object.entries(t))if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=new R;f.name=l,f.statement=await this.parseStatements(u,o,n,a,{}),i.push(f)}else if(typeof u=="string"){let f=await this.resolveReference(u,o,n);f&&i.push(f)}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 S&&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 S&&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 j)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 ae={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}},se={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}},ie={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}},ce={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}},pe={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}},le={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=[ae,se,ie,ce,pe,le];var ue={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}},fe={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}},me={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}},de={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}},ye={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}},ge={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}},be={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}},ke={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}},he={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}},Ke={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=[ue,fe,me,de,ye,ge,be,ke,he,Ke];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 S){let p=Re(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=ve(t);if(n){if(t instanceof j){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 Re(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 ve(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,58 @@
|
|
|
1
|
+
import type { Version } from '@kanonak-protocol/types/document/models/types';
|
|
2
|
+
import { KanonakUri } from './KanonakUri.js';
|
|
3
|
+
/**
|
|
4
|
+
* The space of "Kanonak addresses" — anything a user might paste into
|
|
5
|
+
* an address bar or click as a link, at any of the three nested
|
|
6
|
+
* levels of the protocol's hierarchy:
|
|
7
|
+
*
|
|
8
|
+
* 1. publisher (e.g. `kanonak.org`)
|
|
9
|
+
* 2. publisher/package[@version] (e.g. `kanonak.org/core-rdf@1.0.0`)
|
|
10
|
+
* 3. publisher/package[@version]/name (e.g. `kanonak.org/core-rdf@1.0.0/Class`)
|
|
11
|
+
*
|
|
12
|
+
* Each level is a legitimate browse target: a publisher's index page,
|
|
13
|
+
* a package's overview, or a single resource's form view. The shape
|
|
14
|
+
* of the address tells consumers which view to render.
|
|
15
|
+
*
|
|
16
|
+
* `KanonakUri` is a strictly-narrower type — it only addresses level
|
|
17
|
+
* 3 (a named resource). The two coexist: pre-existing call sites that
|
|
18
|
+
* require a resource address keep using `KanonakUri.parse` and are
|
|
19
|
+
* unaffected; consumers that accept any browse target use
|
|
20
|
+
* `parseKanonakAddress` and switch on the discriminator.
|
|
21
|
+
*/
|
|
22
|
+
export type KanonakAddress = {
|
|
23
|
+
readonly kind: 'publisher';
|
|
24
|
+
readonly publisher: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly kind: 'package';
|
|
27
|
+
readonly publisher: string;
|
|
28
|
+
readonly package_: string;
|
|
29
|
+
/** Absent for the unversioned form `publisher/package`. */
|
|
30
|
+
readonly version?: Version;
|
|
31
|
+
} | {
|
|
32
|
+
readonly kind: 'resource';
|
|
33
|
+
readonly uri: KanonakUri;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Parse a Kanonak address string. Recognizes all three levels:
|
|
37
|
+
*
|
|
38
|
+
* - 1 segment → `publisher`
|
|
39
|
+
* - 2 segments → `publisher/package` or `publisher/package@version`
|
|
40
|
+
* - 3 segments → `publisher/package[@version]/name` (delegates to
|
|
41
|
+
* `KanonakUri.parse` so the resource form keeps the
|
|
42
|
+
* single source of truth)
|
|
43
|
+
*
|
|
44
|
+
* Throws on malformed input. The error messages name the form that
|
|
45
|
+
* was expected so address-bar UIs can echo the problem back without
|
|
46
|
+
* inventing their own diagnostics.
|
|
47
|
+
*
|
|
48
|
+
* Note: a raw publisher domain is just an identifier — the parser
|
|
49
|
+
* trusts whatever the user typed and does not validate that the
|
|
50
|
+
* domain actually publishes Kanonak content. Callers that want to
|
|
51
|
+
* confirm reachability resolve against the publisher index.
|
|
52
|
+
*/
|
|
53
|
+
export declare function parseKanonakAddress(input: string): KanonakAddress;
|
|
54
|
+
/**
|
|
55
|
+
* Render a `KanonakAddress` back to its canonical string form.
|
|
56
|
+
* Round-trips with `parseKanonakAddress`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function formatKanonakAddress(address: KanonakAddress): string;
|
|
@@ -1,10 +1,57 @@
|
|
|
1
1
|
import type { Version } from '@kanonak-protocol/types/document/models/types';
|
|
2
|
+
/**
|
|
3
|
+
* Canonical address form for a single Kanonak resource (one entity
|
|
4
|
+
* within a published package).
|
|
5
|
+
*
|
|
6
|
+
* String format (matches the C# source-of-truth in
|
|
7
|
+
* `kanonak-sdk-csharp/Kanonak.Object/Uris/types.cs`):
|
|
8
|
+
*
|
|
9
|
+
* publisher/package@version/name (canonical, versioned)
|
|
10
|
+
* publisher/package/name (latest — version omitted)
|
|
11
|
+
*
|
|
12
|
+
* Examples:
|
|
13
|
+
*
|
|
14
|
+
* kanonak.org/core-rdf@1.0.0/Class
|
|
15
|
+
* stories.org/characters@1.0.0/romeo-montague
|
|
16
|
+
* stories.org/characters/romeo-montague (any reachable version)
|
|
17
|
+
*
|
|
18
|
+
* The `@version` qualifier sits IMMEDIATELY AFTER the package name,
|
|
19
|
+
* because version is a property of the published package — every
|
|
20
|
+
* resource in the package shares it. This matches the cache file
|
|
21
|
+
* layout (`{cache}/{publisher}/{package}@{version}.kan.yml`), the
|
|
22
|
+
* SubjectKanonak.namespace field (`publisher/package@version`), and
|
|
23
|
+
* the CTL template-link scheme (`kanonak://publisher/package@version/resource`).
|
|
24
|
+
*
|
|
25
|
+
* UNVERSIONED FORM. When the version is omitted, the URI addresses
|
|
26
|
+
* "the highest version of `publisher/package` reachable in the
|
|
27
|
+
* consumer's repository." Useful for human input where the user
|
|
28
|
+
* doesn't know or care about specific versions; consumers MUST
|
|
29
|
+
* resolve the unversioned form against a concrete repository before
|
|
30
|
+
* using it for any document lookup.
|
|
31
|
+
*
|
|
32
|
+
* NO URI SCHEME PREFIX. The `KanonakUri` toString form is the bare
|
|
33
|
+
* canonical string above — no `kanonak://` or other scheme prefix.
|
|
34
|
+
* Consumers that need a registered URI scheme (CTL template links,
|
|
35
|
+
* external/OS-level URI handlers) wrap the bare form with their own
|
|
36
|
+
* scheme as needed.
|
|
37
|
+
*/
|
|
2
38
|
export declare class KanonakUri {
|
|
3
39
|
publisher: string;
|
|
4
40
|
package_: string;
|
|
5
41
|
name: string;
|
|
6
|
-
|
|
7
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Absent for the unversioned form. Present for the canonical
|
|
44
|
+
* versioned form. Consumers that look the URI up in a repository
|
|
45
|
+
* must resolve unversioned URIs to a concrete version first.
|
|
46
|
+
*/
|
|
47
|
+
version?: Version | undefined;
|
|
48
|
+
constructor(publisher: string, package_: string, name: string,
|
|
49
|
+
/**
|
|
50
|
+
* Absent for the unversioned form. Present for the canonical
|
|
51
|
+
* versioned form. Consumers that look the URI up in a repository
|
|
52
|
+
* must resolve unversioned URIs to a concrete version first.
|
|
53
|
+
*/
|
|
54
|
+
version?: Version | undefined);
|
|
8
55
|
static parse(kanonakString: string): KanonakUri;
|
|
9
56
|
toString(): string;
|
|
10
57
|
}
|
|
@@ -2,6 +2,8 @@ export { ResourceResolver } from './ResourceResolver.js';
|
|
|
2
2
|
export type { ILogger } from './ResourceResolver.js';
|
|
3
3
|
export { KanonakUri } from './KanonakUri.js';
|
|
4
4
|
export { KanonakUriBuilder } from './KanonakUriBuilder.js';
|
|
5
|
+
export { parseKanonakAddress, formatKanonakAddress, } from './KanonakAddress.js';
|
|
6
|
+
export type { KanonakAddress } from './KanonakAddress.js';
|
|
5
7
|
export type { ResourceResolutionResult } from './ResourceResolutionResult.js';
|
|
6
8
|
export { TypeResolver } from './TypeResolver.js';
|
|
7
9
|
export { findInstancesByType } from './InstanceSearch.js';
|
package/dist/resolution/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=class s{constructor(e,t,o,n){this.publisher=e;this.package_=t;this.name=o;this.version=n}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let o=t[0],n=t[1],r=o.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${o}. Expected format: publisher/package/name`);let i=n.split(".").map(Number),c={major:i[0]||0,minor:i[1]||0,patch:i[2]||0,toString:()=>`${i[0]||0}.${i[1]||0}.${i[2]||0}`,equals:a=>!a||typeof a!="object"?!1:a.major===(i[0]||0)&&a.minor===(i[1]||0)&&a.patch===(i[2]||0),getHashCode:()=>(i[0]||0)<<20|(i[1]||0)<<10|(i[2]||0),compareTo:a=>(i[0]||0)!==a.major?(i[0]||0)-a.major:(i[1]||0)!==a.minor?(i[1]||0)-a.minor:(i[2]||0)-a.patch};return new s(r[0],r[1],r[2],c)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}};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 R=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let o=t.metadata?.namespace_?.toString()??"unknown",n=this.cache.get(o);if(n){let i=n.get(e);if(i)return i}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(o,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let o=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let n=e.split("."),r=n[0],i=n[1],c=await this.findDocumentForAlias(t,r);return c?await this.resolveAllEntitiesAsync(i,c):[]}return o.filter(n=>n.entityName===e)}async buildAllEntitiesIndexAsync(e,t,o){let n=[],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)`),n;t.add(r);let i=o.length===0?r:`${o} \u2192 ${r}`;for(let[c,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.push({entityName:c,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,u),entity:a,definedInNamespace:r,isImported:o.length>0,importPath:i})}if(this.logger?.debug?.(`Collected ${n.length} entities from ${r}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((a,u)=>a+u.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${r}`);for(let[a,u]of Object.entries(e.metadata.imports))for(let p of u)try{this.logger?.debug?.(`Resolving import: ${a}/${p.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(a,p);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,t,i);n.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${p.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${a}/${p.packageName} for namespace ${r}. Error: ${m.message}`,m),new Error(`Failed to process import ${a}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return n}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,o){let n=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)`),n;t.add(r);let i=o.length===0?r:`${o} \u2192 ${r}`,c=0;for(let[a,u]of Object.entries(e.body))if(u&&typeof u=="object"&&!Array.isArray(u)&&!n.has(a)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};n.set(a,{entityName:a,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:u,definedInNamespace:r,isImported:o.length>0,importPath:i}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${r}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((u,p)=>u+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${r}`);for(let[u,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${u}/${l.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(u,l);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(m,t,i),h=0;for(let[y,$]of d.entries())if(n.has(y)||(n.set(y,$),h++),l.alias&&!y.includes(".")){let x=`${l.alias}.${y}`;n.has(x)||(n.set(x,$),h++)}this.logger?.debug?.(`Merged ${h} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${u}/${l.packageName}`)}catch(m){let d=m;throw this.logger?.error?.(`Failed to process import ${u}/${l.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${u}/${l.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return n}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(o,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(o,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,o){if(e===t)return!0;let n=new Set;return await this.isSubclassOfRecursiveAsync(e,t,o,n)}async isSubclassOfRecursiveAsync(e,t,o,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,o);if(!r?.entity)return!1;let i=r.entity.subClassOf;if(i){let c=b(i);for(let a of c)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,o,n))return!0}return!1}async isSubpropertyOfAsync(e,t,o){if(e===t)return!0;let n=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,o,n)}async isSubpropertyOfRecursiveAsync(e,t,o,n){if(n.has(e))return!1;n.add(e);let r=await this.resolveEntityAsync(e,o);if(!r?.entity)return!1;let i=r.entity.subPropertyOf;if(i){let c=b(i);for(let a of c)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,o,n))return!0}return!1}};var k=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,t){return(await this.resourceResolver.resolveEntityAsync(e,t))?.uri??null}buildFromName(e,t,o){if(e.includes(".")){let r=e.split("."),i=r[0],c=r[1],a=this.findPackageNameForAlias(o,i);if(a){for(let u of t.values())if(u.entityName===c&&u.uri.package_===a)return u.uri}return null}let n=t.get(e);return n?n.uri:null}create(e,t,o,n){return new g(e,t,o,n)}findPackageNameForAlias(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(r.alias===t||!r.alias&&r.packageName===t)return r.packageName;return null}};var v=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 o=await this.resourceResolver.resolveEntityAsync(e,t);if(o){let n=o.entity.type;if(n){let r=String(n);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))}};async function P(s,e){let t=[],o=await s.getAllDocumentsAsync();for(let n of o){let r=n.metadata.namespace_;if(!r)continue;let i=r.publisher,c=r.package_,a=r.version?`${r.version.major}.${r.version.minor}.${r.version.patch}`:"0.0.0";for(let[u,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let l=p.type;!l||typeof l!="string"||l!=="Package"&&S(l,e)&&t.push({entityName:u,entity:p,documentNamespace:`${i}/${c}@${a}`,publisher:i,package_:c,version:a})}}return t}function S(s,e){let t=A(s),o=A(e);return t===o}function A(s){let e=s.lastIndexOf(".");if(e!==-1)return s.substring(e+1);let t=s.lastIndexOf("/");return t!==-1?s.substring(t+1):s}function f(s,e){return s.major!==e.major?s.major-e.major:s.minor!==e.minor?s.minor-e.minor:s.patch-e.patch}function K(s,e){return s.major===e.major&&s.minor===e.minor&&s.patch===e.patch}function D(s){return`${s.major}.${s.minor}.${s.patch}`}function w(s,e,t){let o=`${s}.${e}.${t}`;return{major:s,minor:e,patch:t,toString:()=>o,equals:n=>n?.major===s&&n?.minor===e&&n?.patch===t,getHashCode:()=>s<<20|e<<10|t,compareTo:n=>s!==n.major?s-n.major:e!==n.minor?e-n.minor:t-n.patch}}function I(s){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(s);return e?w(Number(e[1]),Number(e[2]),Number(e[3])):null}function V(s,e){return f(s,e)>=0&&s.major===e.major&&s.minor===e.minor}function j(s,e){return e.major===0?f(s,e)>=0&&s.major===0&&s.minor===e.minor:f(s,e)>=0&&s.major===e.major}function E(s,e={}){let{requestedVersion:t}=e;if(s.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let n=s.find(r=>{let i=r.metadata.namespace_?.version;return!!i&&D(i)===t});return n?{chosen:n,alternatives:s.filter(r=>r!==n),multipleVersionsPresent:s.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:s,multipleVersionsPresent:s.length>1,exactRequestedVersionMissing:!0}}if(s.length===1)return{chosen:s[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let o=[...s].sort((n,r)=>{let i=n.metadata.namespace_?.version,c=r.metadata.namespace_?.version;return!i&&!c?0:i?c?f(c,i):-1:1});return{chosen:o[0],alternatives:o.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{g as KanonakUri,k as KanonakUriBuilder,R as ResourceResolver,v as TypeResolver,f as compareVersions,w as createVersion,P as findInstancesByType,D as formatVersion,V as isCompatibleVersion,j as isMajorCompatible,I as parseVersionString,E as pickHighestDocument,K as versionsEqual};
|
|
1
|
+
var g=class t{constructor(e,r,n,s){this.publisher=e;this.package_=r;this.name=n;this.version=s}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 r=e.split("/");if(r.length!==3)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let[n,s,o]=r;if(!n||!s||!o)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let a=s.indexOf("@");if(a===-1)return new t(n,s,o,void 0);let c=s.substring(0,a),i=s.substring(a+1);if(!c||!i)throw new Error(`Invalid Kanonak URI: ${e}. Expected format: publisher/package[@version]/name`);let u=i.split(".").map(Number),p=D(u[0]||0,u[1]||0,u[2]||0);return new t(n,c,o,p)}toString(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}/${this.name}`:`${this.publisher}/${this.package_}/${this.name}`}};function D(t,e,r){return{major:t,minor:e,patch:r,toString:()=>`${t}.${e}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===t&&n.minor===e&&n.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:n=>t!==n.major?t-n.major:e!==n.minor?e-n.minor:r-n.patch}}function b(t){if(Array.isArray(t))return t.map(r=>r?.toString()??"").filter(r=>r.length>0);let e=t?.toString();return e?[e]:[]}var k=class{cache=new Map;repository;logger;constructor(e,r){this.repository=e,this.logger=r}async resolveEntityAsync(e,r){let n=r.metadata?.namespace_?.toString()??"unknown",s=this.cache.get(n);if(s){let a=s.get(e);if(a)return a}let o=await this.buildEntityIndexAsyncInternal(r,new Set,"");return this.cache.set(n,o),o.get(e)??null}async resolveAllEntitiesAsync(e,r){let n=await this.buildAllEntitiesIndexAsync(r,new Set,"");if(e.includes(".")){let s=e.split("."),o=s[0],a=s[1],c=await this.findDocumentForAlias(r,o);return c?await this.resolveAllEntitiesAsync(a,c):[]}return n.filter(s=>s.entityName===e)}async buildAllEntitiesIndexAsync(e,r,n){let s=[],o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${o}`),r.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),s;r.add(o);let a=n.length===0?o:`${n} \u2192 ${o}`;for(let[c,i]of Object.entries(e.body))if(i&&typeof i=="object"&&!Array.isArray(i)){let u=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.push({entityName:c,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,c,u),entity:i,definedInNamespace:o,isImported:n.length>0,importPath:a})}if(this.logger?.debug?.(`Collected ${s.length} entities from ${o}`),e.metadata?.imports){let c=Object.values(e.metadata.imports).reduce((i,u)=>i+u.length,0);this.logger?.debug?.(`Processing ${c} import(s) for ${o}`);for(let[i,u]of Object.entries(e.metadata.imports))for(let p of u)try{this.logger?.debug?.(`Resolving import: ${i}/${p.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(i,p);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(l,r,a);s.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${i}/${p.packageName}`)}catch(l){let m=l;throw this.logger?.error?.(`Failed to process import ${i}/${p.packageName} for namespace ${o}. Error: ${m.message}`,m),new Error(`Failed to process import ${i}/${p.packageName} for namespace ${o}. See inner exception for details.`,{cause:l})}}return s}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,r,n){let s=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),r.has(o))return this.logger?.debug?.(`Skipping ${o} - already visited (circular import prevention)`),s;r.add(o);let a=n.length===0?o:`${n} \u2192 ${o}`,c=0;for(let[i,u]of Object.entries(e.body))if(u&&typeof u=="object"&&!Array.isArray(u)&&!s.has(i)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.set(i,{entityName:i,uri:new g(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,p),entity:u,definedInNamespace:o,isImported:n.length>0,importPath:a}),c++}if(this.logger?.debug?.(`Indexed ${c} entities from ${o}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((u,p)=>u+p.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${o}`);for(let[u,p]of Object.entries(e.metadata.imports))for(let l of p)try{this.logger?.debug?.(`Resolving import: ${u}/${l.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(u,l);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(m,r,a),h=0;for(let[y,$]of d.entries())if(s.has(y)||(s.set(y,$),h++),l.alias&&!y.includes(".")){let x=`${l.alias}.${y}`;s.has(x)||(s.set(x,$),h++)}this.logger?.debug?.(`Merged ${h} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${u}/${l.packageName}`)}catch(m){let d=m;throw this.logger?.error?.(`Failed to process import ${u}/${l.packageName} for namespace ${o}. Error: ${d.message}`,d),new Error(`Failed to process import ${u}/${l.packageName} for namespace ${o}. See inner exception for details.`,{cause:m})}}return s}async findDocumentForAlias(e,r){if(!e.metadata?.imports)return null;for(let[n,s]of Object.entries(e.metadata.imports))for(let o of s){if(o.alias===r)return await this.repository.getHighestCompatibleVersionAsync(n,o);if(!o.alias&&o.packageName===r)return await this.repository.getHighestCompatibleVersionAsync(n,o)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,r,n){if(e===r)return!0;let s=new Set;return await this.isSubclassOfRecursiveAsync(e,r,n,s)}async isSubclassOfRecursiveAsync(e,r,n,s){if(s.has(e))return!1;s.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let a=o.entity.subClassOf;if(a){let c=b(a);for(let i of c)if(i===r||await this.isSubclassOfRecursiveAsync(i,r,n,s))return!0}return!1}async isSubpropertyOfAsync(e,r,n){if(e===r)return!0;let s=new Set;return await this.isSubpropertyOfRecursiveAsync(e,r,n,s)}async isSubpropertyOfRecursiveAsync(e,r,n,s){if(s.has(e))return!1;s.add(e);let o=await this.resolveEntityAsync(e,n);if(!o?.entity)return!1;let a=o.entity.subPropertyOf;if(a){let c=b(a);for(let i of c)if(i===r||await this.isSubpropertyOfRecursiveAsync(i,r,n,s))return!0}return!1}};var v=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,r){return(await this.resourceResolver.resolveEntityAsync(e,r))?.uri??null}buildFromName(e,r,n){if(e.includes(".")){let o=e.split("."),a=o[0],c=o[1],i=this.findPackageNameForAlias(n,a);if(i){for(let u of r.values())if(u.entityName===c&&u.uri.package_===i)return u.uri}return null}let s=r.get(e);return s?s.uri:null}create(e,r,n,s){return new g(e,r,n,s)}findPackageNameForAlias(e,r){if(!e.metadata.imports)return null;for(let[n,s]of Object.entries(e.metadata.imports))for(let o of s)if(o.alias===r||!o.alias&&o.packageName===r)return o.packageName;return null}};function V(t){if(!t||t.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let e=t.trim(),r=e.split("/");if(r.length===1){let n=r[0];if(!n)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(n.includes("@"))throw new Error(`Invalid Kanonak address: "${t}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:n}}if(r.length===2){let[n,s]=r;if(!n||!s)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher/package[@version].`);let o=s.indexOf("@");if(o===-1)return{kind:"package",publisher:n,package_:s};let a=s.substring(0,o),c=s.substring(o+1);if(!a||!c)throw new Error(`Invalid Kanonak address: "${t}". Expected publisher/package[@version].`);let i=S(c);return{kind:"package",publisher:n,package_:a,version:i}}return{kind:"resource",uri:g.parse(e)}}function P(t){switch(t.kind){case"publisher":return t.publisher;case"package":return t.version?`${t.publisher}/${t.package_}@${t.version.major}.${t.version.minor}.${t.version.patch}`:`${t.publisher}/${t.package_}`;case"resource":return t.uri.toString()}}function S(t){let e=t.split(".").map(Number);return I(e[0]||0,e[1]||0,e[2]||0)}function I(t,e,r){return{major:t,minor:e,patch:r,toString:()=>`${t}.${e}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===t&&n.minor===e&&n.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:n=>t!==n.major?t-n.major:e!==n.minor?e-n.minor:r-n.patch}}var R=class t{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"&&t.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 r=e.includes(".")?e.split(".")[1]:e;return t.KNOWN_XSD_DATATYPES.has(r.toLowerCase())}async isClassTypeAsync(e,r){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,r);if(n){let s=n.entity.type;if(s){let o=String(s);return o==="Class"||o==="rdfs.Class"||o.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,r){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(r)||e==="Property"&&this.isLiteralType(r))}isEffectiveObjectProperty(e,r){return!!(e==="ObjectProperty"||e==="Property"&&r&&!this.isXsdDatatype(r)&&!this.isLiteralType(r))}};async function E(t,e){let r=[],n=await t.getAllDocumentsAsync();for(let s of n){let o=s.metadata.namespace_;if(!o)continue;let a=o.publisher,c=o.package_,i=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[u,p]of Object.entries(s.body)){if(!p||typeof p!="object")continue;let l=p.type;!l||typeof l!="string"||l!=="Package"&&_(l,e)&&r.push({entityName:u,entity:p,documentNamespace:`${a}/${c}@${i}`,publisher:a,package_:c,version:i})}}return r}function _(t,e){let r=w(t),n=w(e);return r===n}function w(t){let e=t.lastIndexOf(".");if(e!==-1)return t.substring(e+1);let r=t.lastIndexOf("/");return r!==-1?t.substring(r+1):t}function f(t,e){return t.major!==e.major?t.major-e.major:t.minor!==e.minor?t.minor-e.minor:t.patch-e.patch}function j(t,e){return t.major===e.major&&t.minor===e.minor&&t.patch===e.patch}function A(t){return`${t.major}.${t.minor}.${t.patch}`}function K(t,e,r){let n=`${t}.${e}.${r}`;return{major:t,minor:e,patch:r,toString:()=>n,equals:s=>s?.major===t&&s?.minor===e&&s?.patch===r,getHashCode:()=>t<<20|e<<10|r,compareTo:s=>t!==s.major?t-s.major:e!==s.minor?e-s.minor:r-s.patch}}function O(t){let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(t);return e?K(Number(e[1]),Number(e[2]),Number(e[3])):null}function C(t,e){return f(t,e)>=0&&t.major===e.major&&t.minor===e.minor}function N(t,e){return e.major===0?f(t,e)>=0&&t.major===0&&t.minor===e.minor:f(t,e)>=0&&t.major===e.major}function M(t,e={}){let{requestedVersion:r}=e;if(t.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!r};if(r){let s=t.find(o=>{let a=o.metadata.namespace_?.version;return!!a&&A(a)===r});return s?{chosen:s,alternatives:t.filter(o=>o!==s),multipleVersionsPresent:t.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:t,multipleVersionsPresent:t.length>1,exactRequestedVersionMissing:!0}}if(t.length===1)return{chosen:t[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let n=[...t].sort((s,o)=>{let a=s.metadata.namespace_?.version,c=o.metadata.namespace_?.version;return!a&&!c?0:a?c?f(c,a):-1:1});return{chosen:n[0],alternatives:n.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{g as KanonakUri,v as KanonakUriBuilder,k as ResourceResolver,R as TypeResolver,f as compareVersions,K as createVersion,E as findInstancesByType,P as formatKanonakAddress,A as formatVersion,C as isCompatibleVersion,N as isMajorCompatible,V as parseKanonakAddress,O as parseVersionString,M as pickHighestDocument,j as versionsEqual};
|