@kanonak-protocol/sdk 3.34.0 → 3.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,54 @@
1
+ import{a as me}from"./chunk-FJ35VIV6.js";import{a as se,c as le,d as ye,f as Z}from"./chunk-SQDXESNM.js";import{c as J,k as ae,l as ce}from"./chunk-W6T7MOKY.js";import{a as ie}from"./chunk-7CUTGGH3.js";import{c as A}from"./chunk-FQHALFRR.js";import{a as P,b as V,c as pe}from"./chunk-5ILSX24H.js";var D=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var R=(r=>(r.Warning="Warning",r.Error="Error",r))(R||{});var g=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var Q=class d{resolvedDocuments=[];currentEntityPath;withPath(e){let r=new d;return r.resolvedDocuments=this.resolvedDocuments,r.currentEntityPath=e,r}};var te=class{constructor(e){this.underlying=e;this.repository=new re(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new Z().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let r=this.importClosureCache.get(e);return r||(r=this.computeImportClosure(e),this.importClosureCache.set(e,r),r)}async getClassDeclarations(e){let r=this.classDeclarationsCache.get(e);return r||(r=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,r),r)}async getPropertyNames(e){let r=this.propertyNamesCache.get(e);return r||(r=this.computePropertyNames(e),this.propertyNamesCache.set(e,r),r)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let r=new Set([e]),t=[e],o=await this.buildDocsByIdIndex();for(;t.length>0;){let a=t.shift(),i=o.get(a);if(i?.metadata.imports)for(let[n,c]of Object.entries(i.metadata.imports))for(let s of c){let l=await this.repository.getHighestCompatibleVersionAsync(n,s);if(!l)continue;let p=ee(l);!p||r.has(p)||(r.add(p),t.push(p))}}return r}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),r=new Map;for(let t of e){let o=ee(t);o&&r.set(o,t)}return r}async computeClassDeclarations(e){let r=await this.findDocById(e),t=new Map;if(!r)return t;for(let[o,a]of Object.entries(r.body)){if(!ue(a))continue;let i=a,n=fe(i,"type");if(n==="Class"||n?.endsWith(".Class")){let c=he(i);t.set(o,c)}}return t}async computePropertyNames(e){let r=await this.findDocById(e),t=new Set;if(!r)return t;for(let[o,a]of Object.entries(r.body)){if(!ue(a))continue;let n=fe(a,"type");(n==="ObjectProperty"||n?.endsWith(".ObjectProperty")||n==="DatatypeProperty"||n?.endsWith(".DatatypeProperty")||n==="AnnotationProperty"||n?.endsWith(".AnnotationProperty")||n==="Property"||n?.endsWith(".Property"))&&t.add(o)}return t}async findDocById(e){let r=await this.getAllDocuments();for(let t of r)if(ee(t)===e)return t}};function ee(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${A(e.version)}`}function ue(d){return typeof d=="object"&&d!==null&&!Array.isArray(d)}function fe(d,e){if(e in d)return de(d[e]);for(let r of Object.keys(d))if(r.endsWith(`.${e}`))return de(d[r])}function de(d){return Array.isArray(d)?d.length>0?String(d[0]):void 0:d==null?void 0:String(d)}function he(d){let e=d.subClassOf;if(e===void 0){for(let r of Object.keys(d))if(r.endsWith(".subClassOf")){e=d[r];break}}return P(e)}var re=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,r){let t=`${e}/${r}`,o=this.byNamespaceCache.get(t);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,r),this.byNamespaceCache.set(t,o),o)}getHighestCompatibleVersionAsync(e,r){let t=r.version,o=t?`${t.major}.${t.minor}.${t.patch}`:"",a=`${e}/${r.packageName}@${r.versionOperator}:${o}`,i=this.highestVersionCache.get(a);return i||(i=this.inner.getHighestCompatibleVersionAsync(e,r),this.highestVersionCache.set(a,i),i)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var v=class d{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let r=[];for(let[t,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(t,o,r);return r}validateEntity(e,r,t){for(let[o,a]of Object.entries(r)){let i=a?.toString()??"";if(i&&d.NAMESPACE_PREFIX_PATTERN.test(i)){let n=this.getSuggestionForPrefixedValue(i),c=e.split(".")[0],s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=c,s.propertyName=e,s.actualValue=o,s.expectedValue=n,s.message=`Invalid namespace prefix '${i}'. Use '${n}' without prefix.`,s.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,t)}}getSuggestionForPrefixedValue(e){let r=e.toLowerCase();if(r==="rdfs:class"||r==="owl:class")return"Class";if(r==="rdfs:property"||r==="rdf:property")return"DatatypeProperty or ObjectProperty";if(r.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var I=class d{static RESERVED_WORDS=new Set(["kanonak","imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let r=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let i=d.VALID_AUGMENTATION_PATTERN.test(o);if(!i&&!t&&d.RESERVED_WORDS.has(o.toLowerCase())){let n=new g;n.ruleType=this.ruleName,n.severity="Error",n.entityName=o,n.message=`Entity name '${o}' is a reserved word and cannot be used.`,n.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",r.push(n);continue}if(!i&&!d.VALID_NAME_PATTERN.test(o)){let n;/^\d/.test(o)?n="Entity names must start with a letter, not a number.":o.includes(" ")?n="Entity names cannot contain spaces. Use camelCase or underscores instead.":n="Entity names must start with a letter and contain only letters, numbers, and underscores.";let c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=o,c.message=`Invalid entity name '${o}'. ${n}`,c.suggestion=n,r.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,r)}return r}validatePropertyNames(e,r,t){for(let o of Object.keys(r))if(!d.VALID_PROPERTIES.has(o)&&!d.VALID_PROPERTY_NAME_PATTERN.test(o)){let a=new g;a.ruleType=this.ruleName,a.severity="Warning",a.entityName=e,a.propertyName=o,a.message=`Property name '${o}' in entity '${e}' doesn't follow naming conventions.`,a.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(a)}}};var O=class d{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let r=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return r;let t=this.isPropertyDefinedAsClass(e);for(let[o,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let i=a,n=i.type;if(n){let c=[];if(Array.isArray(n))for(let s of n){let l=s?.toString();l&&l==="Property"&&!t&&c.push(l)}else{let s=n?.toString();s&&s==="Property"&&!t&&c.push(s)}for(let s of c){let l=this.getPropertyValue(i,"range"),p=this.determinePropertyType(l),y=new g;y.ruleType=this.ruleName,y.severity="Error",y.entityName=o,y.propertyName="type",y.actualValue=s,y.expectedValue=p,y.message=`Invalid property type '${s}'. Use '${p}' instead.`,y.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",r.push(y)}}}return r}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":d.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,r){let t=e[r];return t?t.toString():null}isPropertyDefinedAsClass(e){let r=e.body.Property;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.type;if(o){let a=o.toString();return a==="Class"||a.endsWith(".Class")}}return!1}};var w=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let r=[];for(let[t,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||t.includes("."))continue;let a=o,i="type"in a,n=a.type?.toString().trim();if(!i||!n){let c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=t,c.propertyName="type",c.message=`Subject Kanonak '${t}' must have a 'type' property.`,c.suggestion=`Add a type statement like:
2
+ type: Scene
3
+
4
+ Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,c.expectedValue="A valid class name (Scene, Character, Story, etc.)",r.push(c)}}return r}};var j=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,r){let t=[],o=new V(r),a=await this.buildPropertyRangeMap(e,o);for(let[i,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&await this.checkEmbeddedTypes(i,n,void 0,a,o,e,t,0);return t}pickRange(e,r,t){if(e.length===0)return;if(e.length===1)return e[0].range;let o=r.indexOf(".");if(o>0){let a=r.substring(0,o),i=e.find(n=>n.declaringAlias===a);if(i)return i.range}if(t){let a=this.localName(t),i=e.find(n=>this.localName(n.domain)===a);if(i)return i.range}return e[0].range}async checkEmbeddedTypes(e,r,t,o,a,i,n,c){if(c>0){let l=r.type;if(l!=null){let p=await this.validateEmbeddedType(e,String(l),t,a,i);p&&n.push(p)}}let s=r.type!==void 0&&r.type!==null?String(r.type):void 0;for(let[l,p]of Object.entries(r)){let y=this.localName(l),m=o.get(y),f=(m!==void 0?this.pickRange(m,l,s):void 0)??t;if(typeof p=="object"&&p!==null)if(Array.isArray(p))for(let b=0;b<p.length;b++){let h=p[b];typeof h=="object"&&h!==null&&!Array.isArray(h)&&await this.checkEmbeddedTypes(`${e}.${l}[${b}]`,h,f,o,a,i,n,c+1)}else await this.checkEmbeddedTypes(`${e}.${l}`,p,f,o,a,i,n,c+1)}}async validateEmbeddedType(e,r,t,o,a){if(r.length===0||!t)return null;let i=this.localName(r),n=this.localName(t);if(n==="Resource"||n==="Class")return null;let c=e.split(".")[0];if(i===n){let l=new g;return l.ruleType=this.ruleName,l.severity="Warning",l.entityName=c,l.propertyName=e,l.actualValue=r,l.expectedValue=t,l.message=`Embedded object at '${e}' declares 'type: ${r}', which equals the parent property's range '${t}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,l.suggestion=`Remove the 'type: ${r}' line, or keep it if explicitness is preferred over concision.`,l}if(await o.isSubclassOfAsync(r,t,a)||(i!==r||n!==t)&&await o.isSubclassOfAsync(i,n,a))return null;let s=new g;return s.ruleType=this.ruleName,s.severity="Error",s.entityName=c,s.propertyName=e,s.actualValue=r,s.expectedValue=t,s.message=`Embedded object at '${e}' has 'type: ${r}', which is not a subclass of the parent property's range '${t}'.`,s.suggestion=`Either remove the 'type: ${r}' line (so the type is inferred from the property's range '${t}'), or add 'subClassOf: ${t}' to the '${r}' class definition so the relationship holds.`,s}localName(e){let r=e.lastIndexOf(".");return r<0||r===e.length-1?e:e.substring(r+1)}async buildPropertyRangeMap(e,r){let t=new Map,o=await r.buildEntityIndexAsync(e),a=new Map;for(let[i,n]of o){let c=n.entity.type;if(c==null)continue;let s=String(c),l=this.localName(s);if(!(l==="Property"||l==="DatatypeProperty"||l==="ObjectProperty"||l==="AnnotationProperty"))continue;let y=n.entity.range;if(y==null)continue;let m=String(y);if(m.length===0)continue;let u=n.entity.domain,f=u!=null?String(u):"",b=n.uri.toString(),h=a.get(b),k=i.includes(".");(!h||k&&!h.entityName.includes("."))&&a.set(b,{entityName:i,domain:f,range:m})}for(let i of a.values()){let n=this.localName(i.entityName),c=i.entityName.indexOf("."),s=c>0?i.entityName.substring(0,c):void 0,l=t.get(n)??[];l.push({domain:i.domain,range:i.range,declaringAlias:s}),t.set(n,l)}return t}};var E=class{ruleName="ImportExistence";async validateAsync(e,r){let t=[];if(!e.metadata?.imports)return t;let o=await r.getAllDocumentsAsync();for(let[a,i]of Object.entries(e.metadata.imports))for(let n of i)if(!await r.getHighestCompatibleVersionAsync(a,n)){let s=await this.determineImportErrorAsync(r,a,n,o),l=new g;l.ruleType=this.ruleName,l.severity="Error",l.message=s.message,l.suggestion=s.suggestion,l.entityName=`Import: ${a}/${n.packageName}`,l.actualValue=n.toString(),l.expectedValue=s.expectedValue,t.push(l)}return t}async determineImportErrorAsync(e,r,t,o){let a=await e.getDocumentsByNamespaceAsync(r,t.packageName);if(a.length===0){let s=o.filter(m=>m.metadata.namespace_?.publisher===r).map(m=>m.metadata.namespace_.package_).filter((m,u,f)=>f.indexOf(m)===u),l=this.findSimilarPackages(t.packageName,s),p=`Import '${r}/${t.package_}' not found - package does not exist`,y=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:s.length>0?`Available packages in ${r}: ${s.slice(0,5).join(", ")}`:`No packages found for publisher '${r}'. Verify the publisher name is correct.`;return{message:p,suggestion:y,expectedValue:"Existing package"}}let n=a.filter(s=>s.metadata.namespace_?.version).map(s=>s.metadata.namespace_.version.toString()).sort().join(", "),c=this.getAcceptableVersionRange(t);return{message:`Import '${r}/${t.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${n}. Required: ${c}`,expectedValue:c}}getAcceptableVersionRange(e){switch(e.versionOperator){case 0:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case 1:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case 2:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case 3:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,r){if(r.length===0)return[];let t=r.filter(i=>i.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(i.toLowerCase()));if(t.length>0)return t.sort((i,n)=>i.length-n.length);let o=r.map(i=>({package:i,distance:this.levenshteinDistance(e.toLowerCase(),i.toLowerCase())})).sort((i,n)=>i.distance-n.distance),a=Math.max(3,Math.floor(e.length*.4));return o.filter(i=>i.distance<=a).map(i=>i.package)}levenshteinDistance(e,r){if(!e||e.length===0)return r?.length??0;if(!r||r.length===0)return e.length;let t=e.length,o=r.length,a=Array(t+1).fill(null).map(()=>Array(o+1).fill(0));for(let i=0;i<=t;i++)a[i][0]=i;for(let i=0;i<=o;i++)a[0][i]=i;for(let i=1;i<=t;i++)for(let n=1;n<=o;n++){let c=e[i-1]===r[n-1]?0:1;a[i][n]=Math.min(Math.min(a[i-1][n]+1,a[i][n-1]+1),a[i-1][n-1]+c)}return a[t][o]}};var N=class{ruleName="UnresolvedReference";async validateAsync(e,r){let t=[],o=new V(r),a=await o.buildEntityIndexAsync(e),i=new Set;for(let[n,c]of a.entries()){let s=c.entity.type;if(s){let l=s.toString();(l==="ObjectProperty"||l.endsWith(".ObjectProperty"))&&i.add(n)}}for(let[n,c]of Object.entries(e.body)){if(!c||typeof c!="object"||Array.isArray(c))continue;let s=c,l=this.getPropertyValue(s,"type");if(!(!l||l==="Class"||l.endsWith("Property")||l==="AnnotationProperty"))for(let[p,y]of Object.entries(s))p==="type"||p==="label"||p==="comment"||!(i.has(p)||Array.from(i).some(u=>u.endsWith(`.${p}`)))||await this.validateReferenceValue(n,p,y,e,o,t)}return t}async validateReferenceValue(e,r,t,o,a,i){if(t!=null){if(typeof t=="string")await a.resolveEntityAsync(t,o)||i.push(this.createUnresolvedReferenceError(e,r,t));else if(Array.isArray(t))for(let n=0;n<t.length;n++){let c=t[n];typeof c=="string"&&(await a.resolveEntityAsync(c,o)||i.push(this.createUnresolvedReferenceError(e,`${r}[${n}]`,c)))}}}createUnresolvedReferenceError(e,r,t){let o=`The entity '${t}' cannot be found in the current document or any imported namespaces.
5
+
6
+ Possible solutions:
7
+ \u2022 Add import if the entity is defined in another namespace:
8
+ kanonak namespace add-import <publisher>/<package>@<version>
9
+ \u2022 Check for typos in the reference name '${t}'
10
+ \u2022 Define '${t}' in the current namespace or an appropriate namespace
11
+ \u2022 Use 'kanonak search type ${t} --include-imports' to locate the entity`,a=new g;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=r,a.actualValue=t,a.message=`Reference to '${t}' could not be resolved`,a.suggestion=o,a.expectedValue="A valid entity reference that exists in the current document or imported namespaces",a}getPropertyValue(e,r){let t=e[r];return t?t.toString():null}};var $=class{ruleName="TypeAmbiguity";async validateAsync(e,r){let t=[],o=new Map,a=[];if(e.metadata?.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){a.push({doc:s,import:c,publisher:i});let l=await this.getTransitiveImportsAsync(r,s,new Set);a.push(...l.map(p=>({doc:p,import:null,publisher:i})))}}for(let{doc:i,import:n}of a){let c=i.metadata?.namespace_?.toString()??"unknown";for(let s of Object.keys(i.body))o.has(s)||o.set(s,[]),o.get(s).push({namespace:c,import:n})}for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n;this.checkAmbiguousReference(c,"type",o,i,t),this.checkAmbiguousReference(c,"subClassOf",o,i,t),this.checkAmbiguousReference(c,"subPropertyOf",o,i,t),this.checkAmbiguousReference(c,"domain",o,i,t),this.checkAmbiguousReference(c,"range",o,i,t)}return t}checkAmbiguousReference(e,r,t,o,a){let i=e[r];if(!i)return;let n=P(i);for(let c of n){if(c.includes("."))continue;let s=t.get(c);if(s&&s.length>1){let l=s.map(u=>u.namespace).join(", "),p=[];for(let{namespace:u,import:f}of s)if(f?.alias)p.push(`${f.alias}.${c}`);else{let b=u.split("/"),k=b[b.length-1]?.split("@")[0]??"alias";p.push(`${k}.${c}`)}let y=p.length>0?`Use one of: ${p.join(", ")}`:"Consider adding namespace aliases to your imports",m=new g;m.ruleType=this.ruleName,m.severity="Warning",m.entityName=o,m.propertyName=r,m.actualValue=c,m.message=`Type '${c}' is ambiguous. It's defined in: ${l}`,m.suggestion=y,a.push(m)}}}async getTransitiveImportsAsync(e,r,t){let o=[],a=r.metadata?.namespace_?.toString()??"";if(t.has(a))return o;if(t.add(a),r.metadata?.imports)for(let[i,n]of Object.entries(r.metadata.imports))for(let c of n){let s=await e.getHighestCompatibleVersionAsync(i,c);if(s){o.push(s);let l=await this.getTransitiveImportsAsync(e,s,t);o.push(...l)}}return o}};var S=class{ruleName="ClassHierarchyCycle";async validateAsync(e,r){let t=[],o=new Map,a=new Set;await this.buildClassHierarchy(e,r,o,a);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n,s=c.type,l=c.subClassOf;if(s?.toString()==="Class"&&l){let p=i,y=this.detectCycle(p,o);if(y){let m=y.join(" \u2192 "),u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Circular class hierarchy detected: ${m}`,u.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",u.entityName=p,u.propertyName="subClassOf",u.actualValue=m,t.push(u);break}}}return t}async buildClassHierarchy(e,r,t,o){let a=e.metadata?.namespace_?.toString()??"";if(!(a&&o.has(a))){a&&o.add(a);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n,s=c.type,l=c.subClassOf;if(s?.toString()==="Class"&&l){let p=P(l);p.length>0&&t.set(i,p)}}if(e.metadata?.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);s&&await this.buildClassHierarchy(s,r,t,o)}}}detectCycle(e,r){let t=[],o=new Set;return this.detectCycleRecursive(e,r,t,o)}detectCycleRecursive(e,r,t,o){if(t.includes(e)){let i=t.indexOf(e),n=t.slice(i);return n.push(e),n}if(o.has(e))return null;t.push(e),o.add(e);let a=r.get(e);if(a)for(let i of a){let n=this.detectCycleRecursive(i,r,t,o);if(n)return n}return t.pop(),null}};var C=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,r){let t=[],o=new Map,a=new Set;await this.buildPropertyHierarchy(e,r,o,a);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.subPropertyOf){let l=i,p=this.detectCycle(l,o);if(p){let y=p.join(" \u2192 "),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${y}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=l,m.propertyName="subPropertyOf",m.actualValue=y,t.push(m);break}}return t}async buildPropertyHierarchy(e,r,t,o){let a=e.metadata?.namespace_?.toString()??"";if(!(a&&o.has(a))){a&&o.add(a);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n,s=c.type;if(s){let l=s.toString();if(l==="DatatypeProperty"||l==="ObjectProperty"||l==="AnnotationProperty"){let p=c.subPropertyOf;if(p){let y=P(p);y.length>0&&t.set(i,y)}}}}if(e.metadata?.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);s&&await this.buildPropertyHierarchy(s,r,t,o)}}}detectCycle(e,r){let t=[],o=new Set;return this.detectCycleRecursive(e,r,t,o)}detectCycleRecursive(e,r,t,o){if(t.includes(e)){let i=t.indexOf(e),n=t.slice(i);return n.push(e),n}if(o.has(e))return null;t.push(e),o.add(e);let a=r.get(e);if(a)for(let i of a){let n=this.detectCycleRecursive(i,r,t,o);if(n)return n}return t.pop(),null}};var K=class{get ruleName(){return"PropertyRangeRequired"}async validateAsync(e,r){let t=[];for(let[o,a]of Object.entries(e.body)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let i=a,n=i.type?.toString();if(n==="DatatypeProperty"||n==="ObjectProperty"||n?.endsWith(".DatatypeProperty")||n?.endsWith(".ObjectProperty")){let c="range"in i,s=i.range?.toString().trim();if(!c||!s){let l=new g;l.ruleType=this.ruleName,l.severity="Error",l.entityName=o,l.propertyName="range",l.message=`Property '${o}' must have a 'range' defined.`,l.suggestion=n==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",l.expectedValue=n==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",t.push(l)}}}return t}};var T=class{builtInClasses=new Set(["Resource","Class","Datatype","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty"]);get ruleName(){return"SubClassOfReference"}isClassLikeType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}async validateAsync(e,r){let t=[],o=new Set;for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=i.type?.toString();this.isClassLikeType(c)&&o.add(a)}for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=P(i.subClassOf);for(let s=0;s<c.length;s++){let l=c[s];if(this.builtInClasses.has(l)||o.has(l))continue;if(!await this.isClassAvailableInImports(e,r,l)){let y=c.length>1?`[${s}]`:"",m=new g;m.ruleType=this.ruleName,m.severity="Error",m.message=`Class '${l}' referenced in subClassOf${y} is not defined or imported`,m.suggestion=`Define '${l}' as a Class, or import a namespace that contains it`,m.entityName=a,m.propertyName="subClassOf",m.actualValue=l,m.expectedValue="Defined or imported class",t.push(m)}}}return t}async isClassAvailableInImports(e,r,t){if(!e.metadata.imports)return!1;let o=null,a=t;if(t.includes(".")){let i=t.split(".",2);o=i[0],a=i[1]}for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){if(o!==null&&c.alias!==o)continue;let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=o!==null?a:t,p=s.body[l];if(p&&typeof p=="object"&&!Array.isArray(p)){let u=p.type?.toString();if(this.isClassLikeType(u))return!0}let y=new Set;if(await this.isClassAvailableInImportsRecursive(s,r,l,y))return!0}}return!1}async isClassAvailableInImportsRecursive(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(a&&o.has(a)||(a&&o.add(a),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=s.body[t];if(l&&typeof l=="object"&&!Array.isArray(l)){let y=l.type?.toString();if(this.isClassLikeType(y))return!0}if(await this.isClassAvailableInImportsRecursive(s,r,t,o))return!0}}return!1}};var x=class{builtInProperties=new Set(["type","label","comment","domain","range","subPropertyOf","subClassOf","inverseOf","sameAs","seeAlso","isDefinedBy","functional","required"]);get ruleName(){return"SubPropertyOfReference"}async validateAsync(e,r){let t=[],o=new Set;for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=i.type?.toString();(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty")&&o.add(a)}for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=P(i.subPropertyOf);for(let s=0;s<c.length;s++){let l=c[s];if(this.builtInProperties.has(l)||o.has(l))continue;if(!await this.isPropertyAvailableInImports(e,r,l)){let y=c.length>1?`[${s}]`:"",m=new g;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${l}' referenced in subPropertyOf${y} is not defined or imported`,m.suggestion=`Define '${l}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,m.entityName=a,m.propertyName="subPropertyOf",m.actualValue=l,m.expectedValue="Defined or imported property",t.push(m)}}}return t}async isPropertyAvailableInImports(e,r,t){if(!e.metadata.imports)return!1;let o=null,a=t;if(t.includes(".")){let i=t.split(".",2);o=i[0],a=i[1]}for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){if(o!==null&&c.alias!==o)continue;let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=o!==null?a:t,p=s.body[l];if(p&&typeof p=="object"&&!Array.isArray(p)){let u=p.type?.toString();if(u==="DatatypeProperty"||u==="ObjectProperty"||u==="AnnotationProperty")return!0}let y=new Set;if(await this.isPropertyAvailableInImportsRecursive(s,r,l,y))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(a&&o.has(a)||(a&&o.add(a),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=s.body[t];if(l&&typeof l=="object"&&!Array.isArray(l)){let y=l.type?.toString();if(y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(s,r,t,o))return!0}}return!1}};var M=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,r){let t=[],o=e.metadata.namespace_?.toString();if(!o)return t;let a=new Map,i=new Set;await this.buildImportGraph(e,r,a,i);let n=this.detectCycle(o,a);if(n){let c=n.join(" \u2192 "),s=new g;s.ruleType=this.ruleName,s.severity="Error",s.message=`Circular namespace import detected: ${c}`,s.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",s.entityName="imports",s.propertyName="imports",s.actualValue=c,t.push(s)}return t}async buildImportGraph(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(!(!a||o.has(a))&&(o.add(a),e.metadata.imports)){let i=[];for(let[n,c]of Object.entries(e.metadata.imports))for(let s of c){let l=`${n}/${s.packageName}@${s.version}`;i.push(l);let p=await r.getHighestCompatibleVersionAsync(n,s);p&&await this.buildImportGraph(p,r,t,o)}i.length>0&&t.set(a,i)}}detectCycle(e,r){let t=[],o=new Set;return this.detectCycleRecursive(e,r,t,o)}detectCycleRecursive(e,r,t,o){let a=t.indexOf(e);if(a>=0){let n=t.slice(a);return n.push(e),n}if(o.has(e))return null;t.push(e),o.add(e);let i=r.get(e);if(i)for(let n of i){let c=this.detectCycleRecursive(n,r,t,o);if(c)return c}return t.pop(),null}};var W=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"InstancePropertyReference"}async validateAsync(e,r,t){let o=[],a=new Set,i=t?await this.closurePropertyNamesViaCache(e,t):void 0,n=t?await this.aliasClosurePropertyNamesViaCache(e,t):void 0;for(let[c,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let p=s.type?.toString();this.isPropertyType(p)&&a.add(c)}for(let[c,s]of Object.entries(e.body))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let l=s,p=l.type?.toString();if(this.isPropertyType(p)||this.isClassType(p))continue;for(let[y,m]of Object.entries(l)){if(!y||this.metadataKeys.has(y))continue;let u=y,f=null;if(y.includes(".")){let h=y.lastIndexOf(".");f=y.substring(0,h),u=y.substring(h+1)}if(a.has(u))continue;if(!await this.isPropertyAvailable(e,r,u,f,i,n)){let h=new g;h.ruleType=this.ruleName,h.severity="Error",h.message=`Property '${y}' is not defined or imported`,h.suggestion=f?`The property '${u}' is not found in the imported namespace with alias '${f}'.
12
+ 1. Verify the namespace is imported with the correct alias
13
+ 2. Check if the property name is spelled correctly
14
+ 3. Ensure the imported namespace version contains this property`:`The property '${y}' is not defined in this namespace or any imported namespace.
15
+ 1. Define '${y}' as an ObjectProperty or DatatypeProperty in this namespace, OR
16
+ 2. Import the namespace that contains '${y}', OR
17
+ 3. Use a qualified reference like 'alias.${y}' if already imported with an alias`,h.entityName=c,h.propertyName=y,h.actualValue=m?.toString(),h.expectedValue="A defined or imported property",o.push(h)}}}return o}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailable(e,r,t,o,a,i){if(a!==void 0&&i!==void 0){if(o===null)return a.has(t);let n=i.get(o);return n?n.has(t):!1}return await this.isPropertyAvailableInImports(e,r,t,o)}async closurePropertyNamesViaCache(e,r){let t=new Set,o=ge(e);if(!o)return t;let a=await r.getImportClosure(o);for(let i of a)if(i!==o)for(let n of await r.getPropertyNames(i))t.add(n);return t}async aliasClosurePropertyNamesViaCache(e,r){let t=new Map;if(!e.metadata.imports)return t;for(let[o,a]of Object.entries(e.metadata.imports))for(let i of a){if(!i.alias)continue;let n=await r.repository.getHighestCompatibleVersionAsync(o,i);if(!n)continue;let c=ge(n);if(!c)continue;let s=await r.getImportClosure(c),l=t.get(i.alias)??new Set;for(let p of s)for(let y of await r.getPropertyNames(p))l.add(y);t.set(i.alias,l)}return t}async isPropertyAvailableInImports(e,r,t,o){if(!e.metadata.imports)return!1;for(let[a,i]of Object.entries(e.metadata.imports))for(let n of i){if(o!==null&&n.alias!==o)continue;let c=await r.getHighestCompatibleVersionAsync(a,n);if(c){let s=c.body[t];if(s&&typeof s=="object"&&!Array.isArray(s)){let y=s.type?.toString();if(this.isPropertyType(y))return!0}let l=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,r,t,l))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(a&&o.has(a)||(a&&o.add(a),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=s.body[t];if(l&&typeof l=="object"&&!Array.isArray(l)){let y=l.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(s,r,t,o))return!0}}return!1}};function ge(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${A(e.version)}`}var L=class{metadataKeys=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","inverseOf","transitive","symmetric","functional","inverseFunctional"]);get ruleName(){return"DefinitionPropertyReference"}async validateAsync(e,r){let t=[],o=new Set;for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=i.type?.toString();this.isPropertyType(c)&&o.add(a)}for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let n=i,c=n.type?.toString();if(!this.isPropertyType(c)&&!this.isClassType(c))continue;for(let[s,l]of Object.entries(n)){if(!s||this.metadataKeys.has(s))continue;let p=s,y=null;if(s.includes(".")){let u=s.lastIndexOf(".");y=s.substring(0,u),p=s.substring(u+1)}if(o.has(p))continue;if(!await this.isPropertyAvailableInImports(e,r,p,y)){let u=this.isClassType(c)?"class":"property",f=new g;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${s}' used on ${u} '${a}' is not defined or imported`,f.suggestion=y?`The property '${p}' is not found in the imported namespace with alias '${y}'.
18
+ 1. Verify the namespace is imported with the correct alias
19
+ 2. Check if the property name is spelled correctly
20
+ 3. Ensure the imported namespace version contains this property`:`The property '${s}' is not defined in this namespace or any imported namespace.
21
+ 1. Define '${s}' as an ObjectProperty or DatatypeProperty in this namespace, OR
22
+ 2. Import the namespace that contains '${s}', OR
23
+ 3. Use a qualified reference like 'alias.${s}' if already imported with an alias`,f.entityName=a,f.propertyName=s,f.actualValue=l?.toString(),f.expectedValue="A defined or imported property",t.push(f)}}}return t}isPropertyType(e){return e?e==="ObjectProperty"||e==="DatatypeProperty"||e==="AnnotationProperty"||e==="Property"||e.endsWith(".ObjectProperty")||e.endsWith(".DatatypeProperty")||e.endsWith(".AnnotationProperty")||e.endsWith(".Property"):!1}isClassType(e){return e?e==="Class"||e.endsWith(".Class"):!1}async isPropertyAvailableInImports(e,r,t,o){if(!e.metadata.imports)return!1;for(let[a,i]of Object.entries(e.metadata.imports))for(let n of i){if(o!==null&&n.alias!==o)continue;let c=await r.getHighestCompatibleVersionAsync(a,n);if(c){let s=c.body[t];if(s&&typeof s=="object"&&!Array.isArray(s)){let y=s.type?.toString();if(this.isPropertyType(y))return!0}let l=new Set;if(await this.isPropertyAvailableInImportsRecursive(c,r,t,l))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(a&&o.has(a)||(a&&o.add(a),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=s.body[t];if(l&&typeof l=="object"&&!Array.isArray(l)){let y=l.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(s,r,t,o))return!0}}return!1}};var _=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"XsdImport"}async validateAsync(e,r){let t=[],o=new Set,a=[];for(let[i,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let c=n,s=!1,l=c.type;if(Array.isArray(l)){for(let p of l)if(p?.toString()==="DatatypeProperty"){s=!0;break}}else l?.toString()==="DatatypeProperty"&&(s=!0);if(s){a.push(i);let p=this.getPropertyValue(c,"range");p&&this.xsdTypes.has(p)&&o.add(p)}}if(o.size>0&&!await this.checkXsdImportAsync(e.metadata,r)){let n=Array.from(o).sort().join(", "),c=a.sort().join(", "),s=new g;s.ruleType=this.ruleName,s.severity="Error",s.message=`XSD namespace not imported but XSD types are used: ${n}`,s.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${c}`,s.entityName="imports",t.push(s)}return t}async checkXsdImportAsync(e,r,t=new Set){if(!e?.imports)return!1;let o=e.namespace_?.toString()??"";if(o&&t.has(o))return!1;o&&t.add(o);for(let[,a]of Object.entries(e.imports))for(let i of a)if(i.packageName==="xsd"||i.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[a,i]of Object.entries(e.imports))for(let n of i){let c=await r.getHighestCompatibleVersionAsync(a,n);if(c?.metadata&&await this.checkXsdImportAsync(c.metadata,r,t))return!0}return!1}getPropertyValue(e,r){return e[r]?.toString()}};var H=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,r){let t=[],o=await this.buildEntitySourceMapAsync(e,r),a=await this.buildDatatypePropertyNamesAsync(e,r);for(let[i,n]of Object.entries(e.body))typeof n=="object"&&n!==null&&!Array.isArray(n)&&this.validateEntityReferences(i,n,o,a,e,t);return t}async buildEntitySourceMapAsync(e,r){let t=new Map,o=new Set;for(let a of Object.keys(e.body)){let i=e.metadata.namespace_?.toString()??"";t.has(a)||t.set(a,[]),t.get(a).push(`(local:${i})`)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let n of i){let c=await r.getHighestCompatibleVersionAsync(a,n);c&&await this.collectEntitiesRecursivelyAsync(c,t,o,r)}return t}async collectEntitiesRecursivelyAsync(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(!t.has(a)){t.add(a);for(let i of Object.keys(e.body)){r.has(i)||r.set(i,[]);let n=r.get(i);n.includes(a)||n.push(a)}if(e.metadata.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await o.getHighestCompatibleVersionAsync(i,c);s&&await this.collectEntitiesRecursivelyAsync(s,r,t,o)}}}async buildDatatypePropertyNamesAsync(e,r){let t=new Set,o=new Set;if(await this.collectDatatypePropertiesAsync(e,t,o,r),e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let n of i){let c=await r.getHighestCompatibleVersionAsync(a,n);c&&await this.collectDatatypePropertiesAsync(c,t,o,r)}return t}async collectDatatypePropertiesAsync(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(!t.has(a)){t.add(a);for(let[i,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let c=n.type;if(typeof c!="string")continue;(c.includes(".")?c.substring(c.lastIndexOf(".")+1):c)==="DatatypeProperty"&&r.add(i)}if(e.metadata.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await o.getHighestCompatibleVersionAsync(i,c);s&&await this.collectDatatypePropertiesAsync(s,r,t,o)}}}validateEntityReferences(e,r,t,o,a,i){for(let[n,c]of Object.entries(r)){let s=n;if(s&&!s.includes(".")){let l=t.get(s);if(l&&l.length>1&&!l.some(y=>y.startsWith("(local:"))){let y=l.filter(m=>!m.startsWith("(local:"));y.length>1&&i.push(this.createAmbiguityError(e,s,`Property '${s}'`,y,a,!0,s))}}this.validatePropertyValue(e,s,c,t,o,a,i)}}validatePropertyValue(e,r,t,o,a,i,n){if(t==null)return;let c=r&&r.includes(".")?r.substring(r.lastIndexOf(".")+1):r,s=!!c&&a.has(c);if(typeof t=="string"&&!t.includes(".")&&!s){let l=o.get(t);if(l&&l.length>1&&!l.some(y=>y.startsWith("(local:"))){let y=l.filter(m=>!m.startsWith("(local:"));y.length>1&&n.push(this.createAmbiguityError(e,r,`Reference '${t}'`,y,i,!1,t))}}else if(Array.isArray(t))for(let l=0;l<t.length;l++){let p=`${e}.${r}[${l}]`;this.validatePropertyValue(p,r,t[l],o,a,i,n)}else if(typeof t=="object"&&!Array.isArray(t)){let l=r?`${e}.${r}`:e;this.validateEntityReferences(l,t,o,a,i,n)}}createAmbiguityError(e,r,t,o,a,i,n){let c=[];for(let f of o){let b=this.findAliasForNamespace(a,f);if(b){let h=r?.split(".").pop()??r;c.push(`${b}.${h}`)}}let s=c.length>0?`Use one of: ${c.map(f=>`'${f}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${r}')`,l=o.map(f=>` \u2022 ${f}`).join(`
24
+ `),p=e.split(".")[0],y=e.includes(".")?e:r,m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=p,y&&(m.propertyName=y);let u=n??r;return u&&(m.actualValue=u),m.message=`${t} is ambiguous - defined in multiple imported namespaces`,m.suggestion=`${s}
25
+
26
+ Defined in:
27
+ ${l}`,m.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",m}findAliasForNamespace(e,r){if(!e.metadata.imports)return null;for(let[t,o]of Object.entries(e.metadata.imports))for(let a of o)if(`${t}/${a.packageName}@${a.version}`===r&&a.alias)return a.alias;return null}};var U=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]);primitiveTypes=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","dateTime","date","time","duration","anyURI","anySimpleType","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte","base64Binary","hexBinary","Literal","Resource"]);get ruleName(){return"PropertyRangeReference"}async validateAsync(e,r){let t=[],o=new Set;for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let c=i.type?.toString();this.isValidRangeTargetType(c)&&o.add(a)}for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let n=i,c=n.type?.toString();if(c!=="DatatypeProperty"&&c!=="ObjectProperty"&&!c?.endsWith(".DatatypeProperty")&&!c?.endsWith(".ObjectProperty"))continue;let s=n.range;if(!s)continue;let l=[];if(Array.isArray(s))for(let p of s){let y=p?.toString();y&&l.push(y)}else{let p=s?.toString();p&&l.push(p)}if(l.length===0)continue;for(let p of l){if(this.primitiveTypes.has(p)||this.builtInClasses.has(p)||o.has(p))continue;if(!await this.isTypeAvailableInImports(e,r,p)){let m=c?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Property '${a}' has range '${p}' which is not defined or imported`,u.suggestion=m==="ObjectProperty"?`For ObjectProperty:
28
+ 1. Define '${p}' as a Class in this namespace, OR
29
+ 2. Import the namespace that contains '${p}', OR
30
+ 3. Use a qualified reference like 'alias.${p}' if already imported with an alias`:`For DatatypeProperty:
31
+ 1. Use a primitive type (string, integer, boolean, dateTime, etc.), OR
32
+ 2. If '${p}' should be a class, change property type to ObjectProperty`,u.entityName=a,u.propertyName="range",u.actualValue=p,u.expectedValue=m==="ObjectProperty"?"A defined or imported class name":"A primitive type or defined class",t.push(u)}}}return t}async isTypeAvailableInImports(e,r,t){if(!e.metadata.imports)return!1;let o=null,a=t;if(t.includes(".")){let i=t.split(".",2);o=i[0],a=i[1]}for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){if(o!==null&&c.alias!==o)continue;let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=o!==null?a:t,p=s.body[l];if(p&&typeof p=="object"&&!Array.isArray(p)){let u=p.type?.toString();if(this.isValidRangeTargetType(u))return!0}let y=new Set;if(await this.isTypeAvailableInImportsRecursive(s,r,l,y))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,r,t,o){let a=e.metadata.namespace_?.toString()??"";if(a&&o.has(a)||(a&&o.add(a),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let c of n){let s=await r.getHighestCompatibleVersionAsync(i,c);if(s){let l=s.body[t];if(l&&typeof l=="object"&&!Array.isArray(l)){let y=l.type?.toString();if(this.isValidRangeTargetType(y))return!0}if(await this.isTypeAvailableInImportsRecursive(s,r,t,o))return!0}}return!1}isValidRangeTargetType(e){return e?e==="Class"||e.endsWith(".Class")||e==="Datatype"||e.endsWith(".Datatype"):!1}};var F=class{xsdTypes=new Set(["string","integer","boolean","decimal","float","double","date","dateTime","time","duration","anyURI","base64Binary","hexBinary","long","int","short","byte","unsignedLong","unsignedInt","unsignedShort","unsignedByte","positiveInteger","nonPositiveInteger","negativeInteger","nonNegativeInteger","normalizedString","token","language","Name","NCName","ENTITY","ENTITIES","IDREF","IDREFS","NMTOKEN","NMTOKENS"]);get ruleName(){return"ObjectPropertyImport"}async validateAsync(e,r){let t=[],o=new Map,a=new V(r);await a.buildEntityIndexAsync(e);for(let[i,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let c=n,s=!1,l=c.type;if(Array.isArray(l)){for(let p of l)if(p?.toString()==="ObjectProperty"){s=!0;break}}else l?.toString()==="ObjectProperty"&&(s=!0);if(s){let p=c.range,y=[];if(Array.isArray(p))for(let m of p){let u=m?.toString();u&&y.push(u)}else{let m=p?.toString();m&&y.push(m)}for(let m of y)this.xsdTypes.has(m)||(o.has(m)||o.set(m,[]),o.get(m).push(i))}}for(let[i,n]of o)if(!await a.resolveEntityAsync(i,e))for(let s of n){let l=new g;l.ruleType=this.ruleName,l.severity="Warning",l.message=`ObjectProperty references class '${i}' which may not be imported`,l.suggestion=`Ensure the namespace containing '${i}' is imported, or define '${i}' in this document`,l.entityName=s,l.propertyName="range",l.actualValue=i,t.push(l)}return t}};var B=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"ObjectPropertyValue"}async validateAsync(e,r){let t=[],o=new V(r),a=new pe(o),i=await o.buildEntityIndexAsync(e),n=await this.buildPropertyMetadataAsync(e,r,o,i);for(let[c,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&await this.scanEntityForObjectProperties(s,c,"",n,o,a,e,t);return t}async scanEntityForObjectProperties(e,r,t,o,a,i,n,c){for(let[s,l]of Object.entries(e)){if(this.standardProperties.has(s))continue;let p,y=await a.resolveEntityAsync(s,n);if(y?.uri){let m=`${y.uri.publisher}/${y.uri.package_}/${y.uri.name}`;p=o.get(m)}if(!p){let m=s,u=s.lastIndexOf(".");u>0&&u<s.length-1&&(m=s.substring(u+1)),p=o.get(m)}if(p&&i.isEffectiveObjectProperty(p.propertyType,p.rangeUri)){let u=t?`${t}.${s}`:s;if(typeof l=="string"&&l.trim().length>0){let f=l.trim();if(f.includes(",")){let h=f.split(",").map(k=>k.trim()).filter(k=>k.length>0);c.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
33
+ ${s}:
34
+ - ${h[0]}
35
+ ${h.slice(1).map(k=>` - ${k}`).join(`
36
+ `)}`,entityName:r,propertyName:s,propertyPath:u,actualValue:f,expectedValue:`A single reference to ${p.range??"an entity"} OR a YAML list`});continue}let b=await a.resolveEntityAsync(f,n);if(b)p.range&&(await this.validateRangeType(b,p.range,a,n)||c.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${p.range}, but '${f}' may not be a ${p.range}`,suggestion:`Ensure '${f}' is defined with appropriate type`,entityName:r,propertyName:s,propertyPath:u,actualValue:f,expectedValue:p.range}));else{let h=p.range??"entity";c.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${f}' which is not defined or imported`,suggestion:`Define '${f}' or import a namespace that contains it. Expected range: ${h}`,entityName:r,propertyName:s,propertyPath:u,actualValue:f,expectedValue:"Defined or imported entity"})}}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let f=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(l,r,f,o,a,i,n,c)}else if(Array.isArray(l))for(let f=0;f<l.length;f++){let b=l[f];if(typeof b=="string"&&b.trim().length>0){let h=b.trim(),k=await a.resolveEntityAsync(h,n);if(k){if(p.range&&!await this.validateRangeType(k,p.range,a,n)){let G=t?`${t}.${s}[${f}]`:`${s}[${f}]`;c.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${s}' expects a ${p.range}, but '${h}' may not be a ${p.range}`,suggestion:`Ensure '${h}' is defined with appropriate type`,entityName:r,propertyName:`${s}[${f}]`,propertyPath:G,actualValue:h,expectedValue:p.range})}}else{let ne=p.range??"entity",G=t?`${t}.${s}[${f}]`:`${s}[${f}]`;c.push({ruleType:this.ruleName,severity:"Error",message:`Property '${s}' references '${h}' which is not defined or imported`,suggestion:`Define '${h}' or import a namespace that contains it. Expected range: ${ne}`,entityName:r,propertyName:`${s}[${f}]`,propertyPath:G,actualValue:h,expectedValue:"Defined or imported entity"})}}else if(typeof b=="object"&&b!==null&&!Array.isArray(b)){let h=t?`${t}.${s}[${f}]`:`${s}[${f}]`;await this.scanEntityForObjectProperties(b,r,h,o,a,i,n,c)}}}if(typeof l=="object"&&l!==null&&!Array.isArray(l)&&!o.has(s)){let m=t?`${t}.${s}`:s;await this.scanEntityForObjectProperties(l,r,m,o,a,i,n,c)}else if(Array.isArray(l))for(let m=0;m<l.length;m++){let u=l[m];if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=t?`${t}.${s}[${m}]`:`${s}[${m}]`;await this.scanEntityForObjectProperties(u,r,f,o,a,i,n,c)}}}}async validateRangeType(e,r,t,o){if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty","Class","Resource"]).has(r))return!0;let i=e.entity.type;if(i){let n=[];if(Array.isArray(i))for(let c of i){let s=c?.toString();s&&s.trim().length>0&&n.push(s)}else{let c=i?.toString();c&&c.trim().length>0&&n.push(c)}for(let c of n){let s=c.includes(".")?c.split(".")[1]:c;if(s===r||r==="Property"&&(s==="DatatypeProperty"||s==="ObjectProperty"||s==="AnnotationProperty")||r==="Class"&&s==="Class"||await t.isSubclassOfAsync(c,r,o))return!0}}return!1}async buildPropertyMetadataAsync(e,r,t,o){let a=new Map;for(let[i,n]of o){let c=n.entity.type;if(c){let s=[];if(Array.isArray(c))for(let y of c){let m=y?.toString();m&&m.trim().length>0&&s.push(m)}else{let y=c?.toString();y&&y.trim().length>0&&s.push(y)}let l=!1,p="Property";for(let y of s){let m=y.includes(".")?y.split(".")[1]:y;if(m==="Property"||m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty"){l=!0,p=y;break}}if(l){let y={propertyType:p},m=n.entity.range;if(m){let u=m?.toString();if(u&&u.trim().length>0){y.range=u;let f=await t.resolveEntityAsync(u,e);f&&(y.rangeUri=f.uri)}}if(a.set(i,y),n.uri){let u=`${n.uri.publisher}/${n.uri.package_}/${n.uri.name}`;a.set(u,y)}}}}return a}};var q=class{standardProperties=new Set(["type","label","comment","subClassOf","domain","range","subPropertyOf","inverseOf","sameAs","seeAlso","isDefinedBy"]);get ruleName(){return"PropertyDomain"}async validateAsync(e,r,t){let o=[],a=new Map;for(let[n,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let s=c,l=this.getPropertyValue(s,"type");(l==="DatatypeProperty"||l?.endsWith(".DatatypeProperty")||l==="ObjectProperty"||l?.endsWith(".ObjectProperty")||l==="AnnotationProperty"||l?.endsWith(".AnnotationProperty"))&&a.set(n,s)}let i=t?await this.buildClassHierarchyViaCache(e,t):await this.buildCompleteClassHierarchyAsync(e,r);for(let[n,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let s=c,l=this.getPropertyValue(s,"type");if(!l||l==="Class"||l.endsWith(".Class")||l.endsWith("Property")||l==="AnnotationProperty")continue;this.validateEntityProperties(s,n,l,a,i,o)}return o}async buildClassHierarchyViaCache(e,r){let t=new Map,o=be(e);if(!o)return t;let a=await r.getImportClosure(o);for(let i of a){let n=await r.getClassDeclarations(i);for(let[c,s]of n)s.length>0&&t.set(c,s)}return t}async buildCompleteClassHierarchyAsync(e,r){let t=new Map,o=new Set,a=async(n,c)=>{if(!o.has(c)){o.add(c);for(let[s,l]of Object.entries(n.body))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let p=l,y=this.getPropertyValue(p,"type");if(y==="Class"||y?.endsWith(".Class")){let m=p.subClassOf;if(m===void 0){for(let f of Object.keys(p))if(f.endsWith(".subClassOf")){m=p[f];break}}let u=P(m);u.length>0&&t.set(s,u)}}if(n.metadata.imports)for(let[s,l]of Object.entries(n.metadata.imports))for(let p of l)try{let y=await r.getHighestCompatibleVersionAsync(s,p);if(y){let m=`${s}/${p.packageName}@${p.version}`;await a(y,m)}}catch{}}},i=e.metadata.namespace_?.toString()??"unknown";return await a(e,i),t}validateEntityProperties(e,r,t,o,a,i){for(let[n,c]of Object.entries(e)){if(this.standardProperties.has(n))continue;let s=n,l=n.lastIndexOf(".");l>0&&l<n.length-1&&(s=n.substring(l+1));let p=o.get(s);if(!p)continue;let y=this.getPropertyValue(p,"domain");if(y){if(!this.isTypeCompatibleWithDomain(t,y,a)){let m=r.split(".")[0];i.push({ruleType:this.ruleName,severity:"Error",entityName:m,propertyName:r,actualValue:n,message:`Property '${n}' has domain '${y}' but is used on '${t}' at '${r}'`,suggestion:`Either:
37
+ 1. Use this property only on '${y}' instances
38
+ 2. Change the property domain to include '${t}'
39
+ 3. Create a different property for '${t}'`,expectedValue:`Property used on ${y} or its subclasses`})}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let m=c,u=this.getPropertyValue(m,"type");if(u){let f=`${r}.${n}`;this.validateEntityProperties(m,f,u,o,a,i)}else{let f=this.getPropertyValue(p,"range");if(f){let b=`${r}.${n}`;this.validateEntityProperties(m,b,f,o,a,i)}}}else if(Array.isArray(c))for(let m=0;m<c.length;m++){let u=c[m];if(typeof u=="object"&&u!==null&&!Array.isArray(u)){let f=u,b=this.getPropertyValue(f,"type");if(b){let h=`${r}.${n}[${m}]`;this.validateEntityProperties(f,h,b,o,a,i)}else{let h=this.getPropertyValue(p,"range");if(h){let k=`${r}.${n}[${m}]`;this.validateEntityProperties(f,k,h,o,a,i)}}}}}}}isTypeCompatibleWithDomain(e,r,t){if(e===r)return!0;let o=new Set,a=[e];for(;a.length>0;){let i=a.shift();if(o.has(i))continue;o.add(i);let n=t.get(i);if(n)for(let c of n){if(c===r)return!0;a.push(c)}}return!1}getPropertyValue(e,r){if(r in e){let t=e[r];return this.extractFirstValue(t)}for(let t of Object.keys(e))if(t.endsWith(`.${r}`)){let o=e[t];return this.extractFirstValue(o)}}extractFirstValue(e){if(Array.isArray(e)){let r=[];for(let t of e)r.push(t?.toString()??"");return r.length>0?r[0]:void 0}return e?.toString()}};function be(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${A(e.version)}`}var X=class{get ruleName(){return"PropertyValueType"}async validateAsync(e,r){let t=[],o=new Map;for(let[a,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let n=i,c=this.getPropertyValue(n,"type");(c==="DatatypeProperty"||c==="ObjectProperty")&&o.set(a,n)}for(let[a,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let n=i,c=this.getPropertyValue(n,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[s,l]of Object.entries(n)){if(s==="type"||s==="label"||s==="comment")continue;let p=s,y=s.lastIndexOf(".");y>0&&y<s.length-1&&(p=s.substring(y+1));let m=o.get(p);if(!m)continue;let u=this.getPropertyValue(m,"type"),f=this.getPropertyValue(m,"range");if(u==="DatatypeProperty"){if(typeof l=="object"&&l!==null&&!Array.isArray(l)||Array.isArray(l))t.push({ruleType:this.ruleName,severity:"Error",entityName:a,propertyName:s,message:`Property '${s}' is a DatatypeProperty with range '${f}' but instance '${a}' has a complex object value`,suggestion:`Either:
40
+ 1. Create a class for this data and change '${s}' to an ObjectProperty
41
+ 2. Store as a JSON string to keep it as DatatypeProperty
42
+ 3. Use separate properties instead of nesting`,expectedValue:`A simple value of type '${f}'`});else if(!this.validateDatatypeValue(f,l)){let b={ruleType:this.ruleName,severity:"Error",entityName:a,propertyName:s,message:`Property '${s}' expects type '${f}' but instance '${a}' has value of type '${this.getValueTypeName(l)}'`,suggestion:`Provide a value of type '${f}'`,toString:()=>""};f&&(b.expectedValue=f),t.push(b)}}else if(u==="ObjectProperty")if(Array.isArray(l))for(let b=0;b<l.length;b++){let h=l[b];typeof h!="string"&&(typeof h!="object"||h===null||Array.isArray(h))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:a,propertyName:`${s}[${b}]`,message:`ObjectProperty '${s}' array item ${b} in instance '${a}' has invalid type '${this.getValueTypeName(h)}'`,suggestion:"Array items must be references (strings) or embedded objects (dictionaries)",expectedValue:"string or object"})}else typeof l!="string"&&(typeof l!="object"||l===null||Array.isArray(l))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:a,propertyName:s,message:`ObjectProperty '${s}' in instance '${a}' has invalid value type '${this.getValueTypeName(l)}'`,suggestion:"Value must be a reference (string), embedded object (dictionary), or array of these",expectedValue:`Reference to ${f} or embedded ${f} object`})}}return t}validateDatatypeValue(e,r){switch(e?.toLowerCase()){case"string":return typeof r=="string";case"integer":case"int":return typeof r=="number"&&Number.isInteger(r);case"decimal":return typeof r=="number";case"boolean":return typeof r=="boolean";case"float":case"double":return typeof r=="number";default:return!0}}getValueTypeName(e){return typeof e=="string"?"string":typeof e=="number"?Number.isInteger(e)?"integer":"decimal":typeof e=="boolean"?"boolean":Array.isArray(e)?"array":typeof e=="object"&&e!==null?"object":e===null?"null":e===void 0?"undefined":typeof e}getPropertyValue(e,r){if(r in e){let t=e[r];if(Array.isArray(t)){let o=[];for(let a of t)o.push(a?.toString()??"");return o.length>0?o[0]:void 0}return t?.toString()}}};var z=class{builtInClasses=new Set(["Resource","Class","Literal","Thing","Nothing","Property","DatatypeProperty","ObjectProperty","AnnotationProperty","FunctionalProperty","InverseFunctionalProperty","TransitiveProperty","SymmetricProperty","Package"]);get ruleName(){return"ClassDefinition"}async validateAsync(e,r){let t=[],o=new Map,a=new Set;for(let[n,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=c.type;if(l)if(Array.isArray(l))for(let p of l){let y=p?.toString();if(y==="Class"||y&&y.endsWith(".Class")){a.add(n);break}}else{let p=l?.toString();(p==="Class"||p&&p.endsWith(".Class"))&&a.add(n)}}for(let[n,c]of Object.entries(e.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let s=c,l=s.type;if(l)if(Array.isArray(l)){let p=!1;for(let y of l){let m=y?.toString();if(m&&this.isDefinitionType(m)){p=!0;break}}if(!p)for(let y of l){let m=y?.toString();m&&m.trim().length>0&&(o.has(m)||o.set(m,[]),o.get(m).push(n))}}else{let p=l?.toString();p&&p.trim().length>0&&(this.isDefinitionType(p)||(o.has(p)||o.set(p,[]),o.get(p).push(n)))}this.checkNestedTypes(s,n,o,n)}let i=new V(r);for(let[n,c]of o){if(this.builtInClasses.has(n)||a.has(n))continue;let s=await i.resolveEntityAsync(n,e);if(!(s&&this.isClassEntity(s.entity))){let p=Array.from(new Set(c)).sort();for(let y of p)t.push({ruleType:this.ruleName,severity:"Error",message:`Class '${n}' is not defined or imported`,suggestion:`Define '${n}' as a Class in this document, or import a namespace that contains it`,entityName:y,propertyName:"type",actualValue:n,expectedValue:"Defined or imported class"})}}return t}checkNestedTypes(e,r,t,o){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=e,i=a.type;if(i){let n=new Set(["Class","DatatypeProperty","ObjectProperty","AnnotationProperty"]);if(Array.isArray(i))for(let c of i){let s=c?.toString();s&&s.trim().length>0&&!n.has(s)&&(t.has(s)||t.set(s,[]),t.get(s).push(o))}else{let c=i?.toString();c&&c.trim().length>0&&!n.has(c)&&(t.has(c)||t.set(c,[]),t.get(c).push(o))}}for(let[n,c]of Object.entries(a))if(n!=="type"){let s=`${o}.${n}`;this.checkNestedTypes(c,r,t,s)}}else if(Array.isArray(e))for(let a=0;a<e.length;a++){let i=`${o}[${a}]`;this.checkNestedTypes(e[a],r,t,i)}}isClassEntity(e){if(!e)return!1;let r=e.type;if(!r)return!1;if(Array.isArray(r))for(let t of r){let o=t?.toString();if(o==="Class"||o&&o.endsWith(".Class"))return!0}else{let t=r?.toString();if(t==="Class"||t&&t.endsWith(".Class"))return!0}return!1}isDefinitionType(e){return!e||e.trim().length===0?!1:new Set(["Class","Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(e)?!0:e.endsWith(".Class")||e.endsWith(".Property")||e.endsWith(".DatatypeProperty")||e.endsWith(".ObjectProperty")||e.endsWith(".AnnotationProperty")}};var Y=class{ruleName="MarkdownLink";async validateAsync(e,r,t){let o=[],a;if(t){let i=await t.getKanonaks(),n=Re(e);a=n?i.filter(c=>c instanceof J&&c.namespace===n):[]}else{let i=new me(e,r);a=await new Z().parseKanonaks(i)}for(let i of a)i instanceof J&&this.checkDefined(i,i.name,o);return o}checkDefined(e,r,t){for(let o of e.statement)if(o instanceof le){let a=o.predicate.subject?.name??"(unknown)";for(let i of o.links)i.target||t.push(this.unresolvedLinkError(r,a,i.reference));for(let i of ye(o.object))t.push(this.malformedLinkError(r,a,i.snippet))}else if(o instanceof ae)this.checkDefined(o.object,r,t);else if(o instanceof ce)for(let a of o.object)a instanceof se&&this.checkDefined(a,r,t)}unresolvedLinkError(e,r,t){let o=new g;return o.ruleType=this.ruleName,o.severity="Warning",o.entityName=e,o.propertyName=r,o.actualValue=t,o.message=`Embedded link [[${t}]] in '${r}' could not be resolved`,o.expectedValue="A reference resolvable through the document's import closure",o.suggestion=`The reference '${t}' inside a markdown value cannot be found in the current document or any imported namespace.
43
+
44
+ Possible solutions:
45
+ \u2022 Import the package that defines '${t}' so the link can resolve
46
+ \u2022 Check for typos in the reference name
47
+ \u2022 If the name collides across imports, alias-qualify it: [[alias.${t}]]`,o}malformedLinkError(e,r,t){let o=new g;return o.ruleType=this.ruleName,o.severity="Error",o.entityName=e,o.propertyName=r,o.actualValue=t,o.message=`Malformed embedded reference near '${t}' in '${r}'`,o.expectedValue="A single-line [[reference]] with no internal line break",o.suggestion=`A '[[' in '${r}' does not form a complete [[reference]] link.
48
+
49
+ A reference may not span a line break \u2014 the most common cause is wrapping a
50
+ long reference across two lines in a block scalar, e.g.:
51
+ ... read for [[persistent-energy-
52
+ shock]] held ...
53
+ which is parsed as literal text, not a link. Keep each [[reference]] on one
54
+ line (let the line run long), or check for an unterminated [[.`,o}};function Re(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${A(e.version)}`}var oe=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new ie,this.documentRules=[new v,new I,new O,new w],this.repositoryRules=[new j,new E,new N,new $,new S,new C,new K,new T,new x,new M,new W,new L,new _,new H,new U,new F,new B,new q,new X,new z,new Y]}async validateAsync(e,r,t){let o=new D;for(let a of this.documentRules)try{let i=a.validate(e);this.addErrorsToResult(o,i)}catch(i){let n=new g;n.ruleType=a.ruleName,n.severity="Error",n.message=`Validation rule '${a.ruleName}' failed: ${i instanceof Error?i.message:String(i)}`,o.errors.push(n)}if(r){let a=[],i=t?.repository??r;for(let n of this.repositoryRules)try{let c=await n.validateAsync(e,i,t);this.addErrorsToResult(o,c)}catch(c){let s=c instanceof Error?c.message:String(c);a.push({ruleName:n.ruleName,cause:s})}if(a.length>0){let n=new Map;for(let{ruleName:c,cause:s}of a){let l=n.get(s);l?l.push(c):n.set(s,[c])}for(let[c,s]of n){let l=new g;l.ruleType=s[0],l.severity="Error",s.length===1?l.message=`Validation rule '${s[0]}' failed: ${c}`:l.message=`${c} (affects ${s.length} rules: ${s.join(", ")})`,o.errors.push(l)}}}return o.isValid=o.errors.length===0,o}async validateYamlAsync(e,r,t){let o=this.parser.parseWithErrors(e);if(!o.isValid){let a=new D;a.isValid=!1;for(let i of o.errors){let n=new g;n.ruleType="ParseError",n.severity="Error",n.lineNumber=i.line,n.column=i.column,n.message=i.message,i.keyName&&(n.entityName=i.keyName),i.errorType==="DuplicateKey"&&(n.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),a.errors.push(n)}return a}return await this.validateAsync(o.document,r,t)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let r=this.documentRules.findIndex(t=>t instanceof e);r>=0&&this.documentRules.splice(r,1)}removeRepositoryRule(e){let r=this.repositoryRules.findIndex(t=>t instanceof e);r>=0&&this.repositoryRules.splice(r,1)}addErrorsToResult(e,r){for(let t of r)t.severity==="Error"?e.errors.push(t):this.includeWarnings&&e.warnings.push(t)}};export{D as a,R as b,g as c,Q as d,te as e,v as f,I as g,O as h,w as i,j,E as k,N as l,$ as m,S as n,C as o,K as p,T as q,x as r,M as s,W as t,L as u,_ as v,H as w,U as x,F as y,B as z,q as A,X as B,z as C,Y as D,oe as E};
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ export { Kanonak, DefinedKanonak, SubjectKanonak, EmbeddedKanonak, ReferenceKano
14
14
  export type { IStatement } from './statements/index.js';
15
15
  export type { MarkdownLink } from './statements/index.js';
16
16
  export { Statement, ScalarStatement, StringStatement, NumberStatement, BooleanStatement, ReferenceStatement, EmbeddedStatement, ListStatement, MarkdownStatement } from './statements/index.js';
17
+ export { extractMarkdownLinks, findMalformedReferences, type RawMarkdownLink, type MalformedMarkdownLink, } from './parsing/extractMarkdownLinks.js';
17
18
  export { OntologyValidationResult, OntologyValidationError, ValidationSeverity, ValidationContext, ValidationCache, KanonakObjectValidator, NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, EmbeddedKanonakTypeRule, ImportExistenceRule, UnresolvedReferenceRule, TypeAmbiguityRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, InstancePropertyReferenceRule, DefinitionPropertyReferenceRule, XsdImportRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyImportRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyValueTypeRule, ClassDefinitionRule, MarkdownLinkRule } from './validation/index.js';
18
19
  export type { IKanonakObjectValidator, IDocumentValidationRule, IRepositoryValidationRule } from './validation/index.js';
19
20
  export type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{a as Ze,b as Qe,c as et,d as tt,e as rt,f as nt,g as ot,h as at,i as it,j as st}from"./chunk-2BQ6SOU6.js";import{b as Yt}from"./chunk-CP5P7HRI.js";import{a as qe,b as Ye,c as Xe,d as b,e as S,f as i}from"./chunk-REH5YNFQ.js";import{a as qt}from"./chunk-2VCFHCFN.js";import{a as Te,b as je,c as Le,d as Fe,e as Ne}from"./chunk-5AH6GIPO.js";import{a as Be,b as De,c as Oe,d as Ae}from"./chunk-VQFL5C7Q.js";import{a as lt,b as dt,c as ut,d as pt}from"./chunk-IIP6J4EP.js";import{a as Je,b as mt,c as ft,d as yt,e as ht}from"./chunk-4TJZIM7A.js";import{a as gt}from"./chunk-NIGFQYVA.js";import{A as Mt,B as zt,C as Gt,D as Wt,E as Jt,a as kt,b as bt,c as St,d as Ct,e as Pt,f as Rt,g as wt,h as xt,i as $t,j as vt,k as Et,l as Kt,m as Bt,n as It,o as Tt,p as jt,q as Lt,r as Ft,s as Nt,t as Dt,u as Ot,v as At,w as Ut,x as Vt,y as Ht,z as _t}from"./chunk-A2JTW3ON.js";import"./chunk-FJ35VIV6.js";import{a as F,b as D,c as Me,e as We}from"./chunk-4YHWMYAZ.js";import{a as Ue,b as j,c as L,d as N,e as He,f as _e,g as O,h as A,i as U,j as V,k as H,l as _}from"./chunk-W6T7MOKY.js";import{a as Ie}from"./chunk-7CUTGGH3.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as ze,c as Ge}from"./chunk-5ILSX24H.js";import{a as Ve}from"./chunk-FUUTGGJS.js";import{a as ct}from"./chunk-ODIECDN7.js";import{VersionOperator as oo}from"@kanonak-protocol/types/document/models/enums";import{existsSync as fr,readFileSync as yr}from"fs";import{homedir as gr}from"os";import{join as hr}from"path";import{execFile as Xt}from"child_process";import{promisify as Zt}from"util";var C=Zt(Xt),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
1
+ import{a as et,b as tt,c as rt,d as nt,e as ot,f as at,g as it,h as st,i as ct,j as lt}from"./chunk-4EWKM5LF.js";import{b as Zt}from"./chunk-JTPYH2AJ.js";import{a as Xe,b as Ze,c as Qe,d as b,e as S,f as i}from"./chunk-EGHULU3U.js";import{a as Xt}from"./chunk-KE4QZNDZ.js";import{a as Te,b as je,c as Le,d as Fe,e as Ne}from"./chunk-5AH6GIPO.js";import{a as Be,b as De,c as Oe,d as Ae}from"./chunk-VQFL5C7Q.js";import{a as ut,b as pt,c as mt,d as ft}from"./chunk-RZ57SDAT.js";import{a as Ye,b as yt,c as gt,d as ht,e as bt}from"./chunk-4TJZIM7A.js";import{a as kt}from"./chunk-NIGFQYVA.js";import{A as Gt,B as Wt,C as Jt,D as qt,E as Yt,a as St,b as Ct,c as Pt,d as Rt,e as wt,f as xt,g as $t,h as vt,i as Et,j as Kt,k as Bt,l as It,m as Tt,n as jt,o as Lt,p as Ft,q as Nt,r as Dt,s as Ot,t as At,u as Ut,v as Mt,w as Vt,x as Ht,y as _t,z as zt}from"./chunk-YRMZ5R2W.js";import"./chunk-FJ35VIV6.js";import{a as F,b as D,c as _e,d as We,e as Je,f as qe}from"./chunk-SQDXESNM.js";import{a as Ue,b as j,c as L,d as N,e as Ve,f as He,g as O,h as A,i as U,j as M,k as V,l as H}from"./chunk-W6T7MOKY.js";import{a as Ie}from"./chunk-7CUTGGH3.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as ze,c as Ge}from"./chunk-5ILSX24H.js";import{a as Me}from"./chunk-FUUTGGJS.js";import{a as dt}from"./chunk-ODIECDN7.js";import{VersionOperator as so}from"@kanonak-protocol/types/document/models/enums";import{existsSync as gr,readFileSync as hr}from"fs";import{homedir as kr}from"os";import{join as br}from"path";import{execFile as Qt}from"child_process";import{promisify as er}from"util";var C=er(Qt),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${r}' then 'kanonak login ${r}' to fix.`)}}catch(n){if(X(n,44))return null;throw new Error(`macOS Keychain read failed for '${r}': ${w(n)}
3
3
  The Keychain may be locked or inaccessible.
4
4
  Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,r){let n=i(e),o=JSON.stringify(r);try{await C(R,["add-generic-password","-s",P,"-a",n,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${n}': ${w(a)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
6
  On managed devices, your IT policy may block credential storage.`)}}async remove(e){let r=i(e);try{await C(R,["delete-generic-password","-s",P,"-a",r],{timeout:1e4})}catch(n){if(X(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${r}': ${w(n)}
7
7
  The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await C(R,["dump-keychain"],{timeout:1e4}),r=[],n=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${P}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&r.push(a[1]),n=!1}return r}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${w(e)}`),[]}}};function X(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}function w(t){return t instanceof Error?t.message:String(t)}import{execFile as Qt}from"child_process";import{promisify as er}from"util";var tr=er(Qt),x="kanonak:",m=class{async get(e){let r=x+i(e),n=`
8
+ `))if(o.includes(`"svce"<blob>="${P}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&r.push(a[1]),n=!1}return r}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${w(e)}`),[]}}};function X(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}function w(t){return t instanceof Error?t.message:String(t)}import{execFile as tr}from"child_process";import{promisify as rr}from"util";var nr=rr(tr),x="kanonak:",m=class{async get(e){let r=x+i(e),n=`
9
9
  ${v}
10
10
  $target = [Console]::In.ReadLine()
11
11
  $ptr = [IntPtr]::Zero
@@ -41,7 +41,7 @@ ${v}
41
41
  $target = [Console]::In.ReadLine()
42
42
  [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await $(n,r)}catch{}}async list(){let e=`
43
43
  ${v}
44
- ${rr}
44
+ ${or}
45
45
  $prefix = [Console]::In.ReadLine()
46
46
  $count = 0
47
47
  $pCreds = [IntPtr]::Zero
@@ -56,7 +56,7 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
56
56
  }
57
57
  [CredMan]::CredFree($pCreds)
58
58
  }`;try{let{stdout:r}=await $(e,x);return r.trim().split(`
59
- `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function $(t,e){for(let r of["pwsh","powershell"])try{return await tr(r,["-NoProfile","-NonInteractive","-Command",t],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(r==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var v=`
59
+ `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function $(t,e){for(let r of["pwsh","powershell"])try{return await nr(r,["-NoProfile","-NonInteractive","-Command",t],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(r==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var v=`
60
60
  Add-Type -TypeDefinition @"
61
61
  using System;
62
62
  using System.Runtime.InteropServices;
@@ -87,13 +87,13 @@ public class CredMan {
87
87
  [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
88
88
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
89
89
  }
90
- "@`,rr="";import{execFile as nr,spawn as or}from"child_process";import{promisify as ar}from"util";var K=ar(nr),E="kanonak",f=class{async get(e){let r=i(e);try{let{stdout:n}=await K("secret-tool",["lookup","service",E,"publisher",r],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,r){let n=i(e),o=JSON.stringify(r);await new Promise((a,s)=>{let c=or("secret-tool",["store","--label",`Kanonak: ${n}`,"service",E,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});c.stdin.write(o),c.stdin.end(),c.on("close",l=>{l===0?a():s(new Error(`secret-tool store exited with code ${l}`))}),c.on("error",s)})}async remove(e){let r=i(e);try{await K("secret-tool",["clear","service",E,"publisher",r],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await K("secret-tool",["search","service",E],{timeout:1e4}),r=[];for(let n of e.split(`
91
- `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&r.push(o[1].trim())}return r}catch{return[]}}};async function M(){try{return await K("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Z,mkdirSync as Q,readFileSync as ee,writeFileSync as te}from"fs";import{createCipheriv as ir,createDecipheriv as sr,randomBytes as re}from"crypto";import{homedir as cr}from"os";import{join as W,dirname as ne}from"path";var ae=W(cr(),".config","kanonak"),y=W(ae,"keyring.key"),B=W(ae,"credentials.enc"),oe="aes-256-gcm",z=32,u=12,G=16,g=class{async get(e){let r=this.loadStore(),n=i(e);return r[n]??null}async store(e,r){let n=this.loadStore(),o=i(e);n[o]=r,this.saveStore(n)}async remove(e){let r=this.loadStore(),n=i(e);delete r[n],this.saveStore(r)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Z(B))return{};try{let e=this.getOrCreateKey(),r=ee(B);if(r.length<u+G)return{};let n=r.subarray(0,u),o=r.subarray(u,u+G),a=r.subarray(u+G),s=sr(oe,e,n);s.setAuthTag(o);let c=Buffer.concat([s.update(a),s.final()]);return JSON.parse(c.toString("utf-8"))}catch{return{}}}saveStore(e){let r=this.getOrCreateKey(),n=re(u),o=ir(oe,r,n),a=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(a),o.final()]),c=o.getAuthTag(),l=Buffer.concat([n,c,s]);Q(ne(B),{recursive:!0}),te(B,l,{mode:384})}getOrCreateKey(){if(Z(y)){let r=ee(y);if(r.length!==z)throw new Error(`Credential keyring key is corrupted (expected ${z} bytes, got ${r.length}). Delete ${y} and re-authenticate.`);return r}let e=re(z);return Q(ne(y),{recursive:!0}),te(y,e,{mode:384}),e}};import{execFile as lr}from"child_process";import{promisify as dr}from"util";var ur=dr(lr),ie=3e4,h=class{constructor(e){this.helperPath=e}helperPath;async get(e){let r=i(e);try{let o=(await this.runHelper("get",{publisher:r})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${r}': ${I(n)}
90
+ "@`,or="";import{execFile as ar,spawn as ir}from"child_process";import{promisify as sr}from"util";var K=sr(ar),E="kanonak",f=class{async get(e){let r=i(e);try{let{stdout:n}=await K("secret-tool",["lookup","service",E,"publisher",r],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,r){let n=i(e),o=JSON.stringify(r);await new Promise((a,s)=>{let c=ir("secret-tool",["store","--label",`Kanonak: ${n}`,"service",E,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});c.stdin.write(o),c.stdin.end(),c.on("close",l=>{l===0?a():s(new Error(`secret-tool store exited with code ${l}`))}),c.on("error",s)})}async remove(e){let r=i(e);try{await K("secret-tool",["clear","service",E,"publisher",r],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await K("secret-tool",["search","service",E],{timeout:1e4}),r=[];for(let n of e.split(`
91
+ `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&r.push(o[1].trim())}return r}catch{return[]}}};async function _(){try{return await K("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Z,mkdirSync as Q,readFileSync as ee,writeFileSync as te}from"fs";import{createCipheriv as cr,createDecipheriv as lr,randomBytes as re}from"crypto";import{homedir as dr}from"os";import{join as W,dirname as ne}from"path";var ae=W(dr(),".config","kanonak"),y=W(ae,"keyring.key"),B=W(ae,"credentials.enc"),oe="aes-256-gcm",z=32,u=12,G=16,g=class{async get(e){let r=this.loadStore(),n=i(e);return r[n]??null}async store(e,r){let n=this.loadStore(),o=i(e);n[o]=r,this.saveStore(n)}async remove(e){let r=this.loadStore(),n=i(e);delete r[n],this.saveStore(r)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Z(B))return{};try{let e=this.getOrCreateKey(),r=ee(B);if(r.length<u+G)return{};let n=r.subarray(0,u),o=r.subarray(u,u+G),a=r.subarray(u+G),s=lr(oe,e,n);s.setAuthTag(o);let c=Buffer.concat([s.update(a),s.final()]);return JSON.parse(c.toString("utf-8"))}catch{return{}}}saveStore(e){let r=this.getOrCreateKey(),n=re(u),o=cr(oe,r,n),a=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(a),o.final()]),c=o.getAuthTag(),l=Buffer.concat([n,c,s]);Q(ne(B),{recursive:!0}),te(B,l,{mode:384})}getOrCreateKey(){if(Z(y)){let r=ee(y);if(r.length!==z)throw new Error(`Credential keyring key is corrupted (expected ${z} bytes, got ${r.length}). Delete ${y} and re-authenticate.`);return r}let e=re(z);return Q(ne(y),{recursive:!0}),te(y,e,{mode:384}),e}};import{execFile as ur}from"child_process";import{promisify as pr}from"util";var mr=pr(ur),ie=3e4,h=class{constructor(e){this.helperPath=e}helperPath;async get(e){let r=i(e);try{let o=(await this.runHelper("get",{publisher:r})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${r}': ${I(n)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
93
93
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,r){let n=i(e);try{await this.runHelper("store",{publisher:n,credential:r})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${I(o)}
94
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let r=i(e);try{await this.runHelper("erase",{publisher:r})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${r}': ${I(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${I(e)}`),[]}}async runHelper(e,r){try{let{stdout:n}=await ur(this.helperPath,[e],{...r&&{input:JSON.stringify(r)},timeout:ie});return n}catch(n){throw pr(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):mr(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${ie/1e3}s on '${e}'.
96
- The helper may be waiting for authentication to an external vault.`):n}}};function I(t){return t instanceof Error?t.message:String(t)}function pr(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"}function mr(t){return t instanceof Error&&"killed"in t&&t.killed}var J=hr(gr(),".kanonak","config.json"),T=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let r=kr(e);if(r)return r;let o=await(await this.getBackend()).get(e);return!o||!S(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,r){return(await this.getBackend()).store(e,r)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=br();return e.credentialHelper?new h(e.credentialHelper):process.platform==="darwin"?new p:process.platform==="win32"?new m:await M()?new f:new g}};function kr(t){let r="KANONAK_TOKEN_"+i(t).replace(/[.\-]/g,"_").toUpperCase();return process.env[r]??null}function br(){if(!fr(J))return{};try{return JSON.parse(yr(J,"utf-8"))}catch(t){let e=t instanceof Error?t.message:String(t);return console.warn(` Warning: Failed to parse ${J}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Sr,createPrivateKey as Cr,generateKeyPairSync as Pr,randomUUID as Rr,sign as wr}from"crypto";function ce(){let{publicKey:t,privateKey:e}=Pr("ec",{namedCurve:"P-256"});return{publicKey:t.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function k(t,e,r,n,o,a){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},c={jti:Rr(),htm:r.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(c.ath=Sr("sha256").update(o).digest("base64url")),a&&(c.nonce=a),xr(s,c,t)}function le(t){return!t||t.length===0?!1:t.some(e=>e.toUpperCase()==="ES256")}function xr(t,e,r){let n=se(JSON.stringify(t)),o=se(JSON.stringify(e)),a=`${n}.${o}`,s=Cr({key:r,format:"jwk"}),l=wr("SHA256",Buffer.from(a),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${l}`}function se(t){return Buffer.from(t,"utf-8").toString("base64url")}function de(t){let e=new Map;return async(r,n,o="GET")=>{if(!t)return fetch(r,{method:o});let a=await t.getCredential(n);if(!a?.accessToken)return fetch(r,{method:o});b(a)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(a.dpopKeyPair){let l=e.get(n);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.Authorization=`DPoP ${a.accessToken}`,s.DPoP=d}catch(d){let Ce=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${n}': ${Ce}
98
- The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${a.accessToken}`}}else s.Authorization=`Bearer ${a.accessToken}`;let c=await fetch(r,{method:o,headers:s});if(c.status===401&&a.dpopKeyPair){let l=c.headers.get("DPoP-Nonce");if(l){e.set(n,l);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.DPoP=d,c=await fetch(r,{method:o,headers:s})}catch{}}}return c}}import{readFileSync as $r,writeFileSync as vr,existsSync as Er}from"fs";import{createHash as Kr}from"crypto";import ue from"js-yaml";var pe="kanonak.lock",Br=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function me(t=pe){if(!Er(t))return null;let e=$r(t,"utf-8"),r=ue.load(e);return!r||typeof r!="object"||r.version!=="1"?null:{version:"1",lastUpdated:r.lastUpdated??new Date().toISOString(),packages:r.packages??{}}}function fe(t,e=pe){t.lastUpdated=new Date().toISOString();let r={};for(let o of Object.keys(t.packages).sort())r[o]=t.packages[o];t.packages=r;let n=ue.dump(t,{lineWidth:-1,sortKeys:!1,quotingType:'"'});vr(e,Br+n,"utf-8")}function ye(t){return`sha256:${Kr("sha256").update(t).digest("hex")}`}import{createHash as Ir}from"crypto";function q(t){let e=[];for(let n of t)n instanceof L&&e.push(Tr(n));return e.sort((n,o)=>n.uri<o.uri?-1:n.uri>o.uri?1:0),JSON.stringify({subjects:e})}function ge(t){let e=q(t);return`sha256:${Ir("sha256").update(e,"utf8").digest("hex")}`}function Tr(t){let e=Or(t),r=Y(t.statement);return{uri:e,statements:r}}function Y(t){let e=[];for(let r of t){let n=jr(r);n&&e.push(n)}return e.sort((r,n)=>r.predicate<n.predicate?-1:r.predicate>n.predicate?1:0),e}function jr(t){let e=Dr(t);if(!e)return;let r=Lr(t);if(r)return Nr(e,r)}function Lr(t){if(t instanceof O)return{type:"string",value:t.object};if(t instanceof A)return{type:"number",value:Se(t.object)};if(t instanceof U)return{type:"boolean",value:t.object};if(t instanceof V)return{type:"ref",value:ke(t.object)};if(t instanceof H){let e=t.object;return he(e)}if(t instanceof _)return{type:"list",items:t.object.map(Fr)}}function he(t){let e=Y(t.statement);return t.name&&t.name.length>0?{type:"embedded",name:t.name,statements:e}:{type:"embedded",statements:e}}function Fr(t){if(t instanceof N)return{type:"ref",value:ke(t)};if(t instanceof F)return he(t);if(t instanceof D){let e=t.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:Se(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(t instanceof j)return{type:"embedded",statements:Y(t.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${t.constructor?.name??typeof t}); add canonicalization support before hashing data that contains it`)}function Nr(t,e){switch(e.type){case"string":return{predicate:t,type:"string",value:e.value};case"number":return{predicate:t,type:"number",value:e.value};case"boolean":return{predicate:t,type:"boolean",value:e.value};case"ref":return{predicate:t,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:t,type:"embedded",name:e.name,statements:e.statements}:{predicate:t,type:"embedded",statements:e.statements};case"list":return{predicate:t,type:"list",items:e.items}}}function Dr(t){let e=t.predicate;if(e)return be(e.subject)}function Or(t){let e=t.namespace??"",r=t.name??"";return`${e}/${r}`}function ke(t){return be(t.subject)}function be(t){let e=t.version;return e&&typeof e.major=="number"?`${t.publisher}/${t.package_}@${e.major}.${e.minor}.${e.patch}/${t.name}`:`${t.publisher}/${t.package_}/${t.name}`}function Se(t){if(Number.isNaN(t))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(t))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(t,-0)?"0":String(t)}export{Ut as AmbiguousReferenceRule,U as BooleanStatement,Gt as ClassDefinitionRule,It as ClassHierarchyCycleRule,Le as CompositeKanonakDocumentRepository,T as CredentialStore,j as DefinedKanonak,Ot as DefinitionPropertyReferenceRule,je as DocumentLocation,Ye as EdgeType,F as EmbeddedKanonak,vt as EmbeddedKanonakTypeRule,H as EmbeddedStatement,Te as FileSystemKanonakDocumentRepository,ct as GitIgnoreFilter,Xe as GraphBuilder,Ae as HttpKanonakDocumentRepository,Et as ImportExistenceRule,Be as InMemoryKanonakDocumentRepository,Dt as InstancePropertyReferenceRule,Ue as Kanonak,dt as KanonakDocumentPositions,We as KanonakObjectParser,Jt as KanonakObjectValidator,Ie as KanonakParser,Ve as KanonakUri,mt as KanonakUriBuilder,gt as KanonakUrlResolver,nt as KanonakVocabulary,_ as ListStatement,D as LiteralKanonak,Yt as LookRenderer,Wt as MarkdownLinkRule,Me as MarkdownStatement,Nt as NamespaceImportCycleRule,Rt as NamespacePrefixRule,qe as NodeType,A as NumberStatement,at as OWL_RL_CLASSIFICATION_RULES,Ht as ObjectPropertyImportRule,_t as ObjectPropertyValueValidationRule,St as OntologyValidationError,kt as OntologyValidationResult,Mt as PropertyDomainRule,Tt as PropertyHierarchyCycleRule,lt as PropertyMetadata,Vt as PropertyRangeReferenceRule,jt as PropertyRangeRequiredRule,xt as PropertyTypeSpecificityRule,zt as PropertyValueTypeRule,De as PublisherConfigResolver,Oe as PublisherIndex,ot as RDFS_RULES,st as Reasoner,it as ReasoningResult,N as ReferenceKanonak,V as ReferenceStatement,Ne as RepositoryFactory,wt as ResourceNamingRule,ze as ResourceResolver,Je as ResourceTypeClassifier,_e as ScalarStatement,He as Statement,O as StringStatement,Lt as SubClassOfReferenceRule,Ft as SubPropertyOfReferenceRule,L as SubjectKanonak,$t as SubjectKanonakTypeRequiredRule,rt as TripleStore,Bt as TypeAmbiguityRule,Ge as TypeResolver,Kt as UnresolvedReferenceRule,Pt as ValidationCache,Ct as ValidationContext,bt as ValidationSeverity,oo as VersionOperator,At as XsdImportRule,q as canonicalForm,ge as canonicalHash,Pe as compareVersions,ye as computeIntegrity,de as createAuthenticatedFetch,k as createDPoPProof,xe as createVersion,qt as findDerivation,ht as findInstancesByType,pt as findMarkdownLinkAt,yt as formatKanonakAddress,we as formatVersion,ce as generateDPoPKeyPair,Fe as getGlobalCachePath,S as hasValidToken,ve as isCompatibleVersion,b as isExpired,Ee as isMajorCompatible,me as loadLockFile,Qe as makeUriKey,i as normalizeHost,ft as parseKanonakAddress,$e as parseVersionString,ut as parseWithPositions,Ke as pickHighestDocument,fe as saveLockFile,le as serverSupportsDPoP,et as tripleKey,Ze as uriKey,tt as uriTriple,Re as versionsEqual};
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let r=i(e);try{await this.runHelper("erase",{publisher:r})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${r}': ${I(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${I(e)}`),[]}}async runHelper(e,r){try{let{stdout:n}=await mr(this.helperPath,[e],{...r&&{input:JSON.stringify(r)},timeout:ie});return n}catch(n){throw fr(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):yr(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${ie/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):n}}};function I(t){return t instanceof Error?t.message:String(t)}function fr(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"}function yr(t){return t instanceof Error&&"killed"in t&&t.killed}var J=br(kr(),".kanonak","config.json"),T=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let r=Sr(e);if(r)return r;let o=await(await this.getBackend()).get(e);return!o||!S(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,r){return(await this.getBackend()).store(e,r)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Cr();return e.credentialHelper?new h(e.credentialHelper):process.platform==="darwin"?new p:process.platform==="win32"?new m:await _()?new f:new g}};function Sr(t){let r="KANONAK_TOKEN_"+i(t).replace(/[.\-]/g,"_").toUpperCase();return process.env[r]??null}function Cr(){if(!gr(J))return{};try{return JSON.parse(hr(J,"utf-8"))}catch(t){let e=t instanceof Error?t.message:String(t);return console.warn(` Warning: Failed to parse ${J}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Pr,createPrivateKey as Rr,generateKeyPairSync as wr,randomUUID as xr,sign as $r}from"crypto";function ce(){let{publicKey:t,privateKey:e}=wr("ec",{namedCurve:"P-256"});return{publicKey:t.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function k(t,e,r,n,o,a){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},c={jti:xr(),htm:r.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(c.ath=Pr("sha256").update(o).digest("base64url")),a&&(c.nonce=a),vr(s,c,t)}function le(t){return!t||t.length===0?!1:t.some(e=>e.toUpperCase()==="ES256")}function vr(t,e,r){let n=se(JSON.stringify(t)),o=se(JSON.stringify(e)),a=`${n}.${o}`,s=Rr({key:r,format:"jwk"}),l=$r("SHA256",Buffer.from(a),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${l}`}function se(t){return Buffer.from(t,"utf-8").toString("base64url")}function de(t){let e=new Map;return async(r,n,o="GET")=>{if(!t)return fetch(r,{method:o});let a=await t.getCredential(n);if(!a?.accessToken)return fetch(r,{method:o});b(a)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(a.dpopKeyPair){let l=e.get(n);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.Authorization=`DPoP ${a.accessToken}`,s.DPoP=d}catch(d){let Ce=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${n}': ${Ce}
98
+ The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${a.accessToken}`}}else s.Authorization=`Bearer ${a.accessToken}`;let c=await fetch(r,{method:o,headers:s});if(c.status===401&&a.dpopKeyPair){let l=c.headers.get("DPoP-Nonce");if(l){e.set(n,l);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.DPoP=d,c=await fetch(r,{method:o,headers:s})}catch{}}}return c}}import{readFileSync as Er,writeFileSync as Kr,existsSync as Br}from"fs";import{createHash as Ir}from"crypto";import ue from"js-yaml";var pe="kanonak.lock",Tr=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function me(t=pe){if(!Br(t))return null;let e=Er(t,"utf-8"),r=ue.load(e);return!r||typeof r!="object"||r.version!=="1"?null:{version:"1",lastUpdated:r.lastUpdated??new Date().toISOString(),packages:r.packages??{}}}function fe(t,e=pe){t.lastUpdated=new Date().toISOString();let r={};for(let o of Object.keys(t.packages).sort())r[o]=t.packages[o];t.packages=r;let n=ue.dump(t,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Kr(e,Tr+n,"utf-8")}function ye(t){return`sha256:${Ir("sha256").update(t).digest("hex")}`}import{createHash as jr}from"crypto";function q(t){let e=[];for(let n of t)n instanceof L&&e.push(Lr(n));return e.sort((n,o)=>n.uri<o.uri?-1:n.uri>o.uri?1:0),JSON.stringify({subjects:e})}function ge(t){let e=q(t);return`sha256:${jr("sha256").update(e,"utf8").digest("hex")}`}function Lr(t){let e=Ur(t),r=Y(t.statement);return{uri:e,statements:r}}function Y(t){let e=[];for(let r of t){let n=Fr(r);n&&e.push(n)}return e.sort((r,n)=>r.predicate<n.predicate?-1:r.predicate>n.predicate?1:0),e}function Fr(t){let e=Ar(t);if(!e)return;let r=Nr(t);if(r)return Or(e,r)}function Nr(t){if(t instanceof O)return{type:"string",value:t.object};if(t instanceof A)return{type:"number",value:Se(t.object)};if(t instanceof U)return{type:"boolean",value:t.object};if(t instanceof M)return{type:"ref",value:ke(t.object)};if(t instanceof V){let e=t.object;return he(e)}if(t instanceof H)return{type:"list",items:t.object.map(Dr)}}function he(t){let e=Y(t.statement);return t.name&&t.name.length>0?{type:"embedded",name:t.name,statements:e}:{type:"embedded",statements:e}}function Dr(t){if(t instanceof N)return{type:"ref",value:ke(t)};if(t instanceof F)return he(t);if(t instanceof D){let e=t.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:Se(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(t instanceof j)return{type:"embedded",statements:Y(t.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${t.constructor?.name??typeof t}); add canonicalization support before hashing data that contains it`)}function Or(t,e){switch(e.type){case"string":return{predicate:t,type:"string",value:e.value};case"number":return{predicate:t,type:"number",value:e.value};case"boolean":return{predicate:t,type:"boolean",value:e.value};case"ref":return{predicate:t,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:t,type:"embedded",name:e.name,statements:e.statements}:{predicate:t,type:"embedded",statements:e.statements};case"list":return{predicate:t,type:"list",items:e.items}}}function Ar(t){let e=t.predicate;if(e)return be(e.subject)}function Ur(t){let e=t.namespace??"",r=t.name??"";return`${e}/${r}`}function ke(t){return be(t.subject)}function be(t){let e=t.version;return e&&typeof e.major=="number"?`${t.publisher}/${t.package_}@${e.major}.${e.minor}.${e.patch}/${t.name}`:`${t.publisher}/${t.package_}/${t.name}`}function Se(t){if(Number.isNaN(t))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(t))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(t,-0)?"0":String(t)}export{Vt as AmbiguousReferenceRule,U as BooleanStatement,Jt as ClassDefinitionRule,jt as ClassHierarchyCycleRule,Le as CompositeKanonakDocumentRepository,T as CredentialStore,j as DefinedKanonak,Ut as DefinitionPropertyReferenceRule,je as DocumentLocation,Ze as EdgeType,F as EmbeddedKanonak,Kt as EmbeddedKanonakTypeRule,V as EmbeddedStatement,Te as FileSystemKanonakDocumentRepository,dt as GitIgnoreFilter,Qe as GraphBuilder,Ae as HttpKanonakDocumentRepository,Bt as ImportExistenceRule,Be as InMemoryKanonakDocumentRepository,At as InstancePropertyReferenceRule,Ue as Kanonak,pt as KanonakDocumentPositions,qe as KanonakObjectParser,Yt as KanonakObjectValidator,Ie as KanonakParser,Me as KanonakUri,yt as KanonakUriBuilder,kt as KanonakUrlResolver,at as KanonakVocabulary,H as ListStatement,D as LiteralKanonak,Zt as LookRenderer,qt as MarkdownLinkRule,_e as MarkdownStatement,Ot as NamespaceImportCycleRule,xt as NamespacePrefixRule,Xe as NodeType,A as NumberStatement,st as OWL_RL_CLASSIFICATION_RULES,_t as ObjectPropertyImportRule,zt as ObjectPropertyValueValidationRule,Pt as OntologyValidationError,St as OntologyValidationResult,Gt as PropertyDomainRule,Lt as PropertyHierarchyCycleRule,ut as PropertyMetadata,Ht as PropertyRangeReferenceRule,Ft as PropertyRangeRequiredRule,vt as PropertyTypeSpecificityRule,Wt as PropertyValueTypeRule,De as PublisherConfigResolver,Oe as PublisherIndex,it as RDFS_RULES,lt as Reasoner,ct as ReasoningResult,N as ReferenceKanonak,M as ReferenceStatement,Ne as RepositoryFactory,$t as ResourceNamingRule,ze as ResourceResolver,Ye as ResourceTypeClassifier,He as ScalarStatement,Ve as Statement,O as StringStatement,Nt as SubClassOfReferenceRule,Dt as SubPropertyOfReferenceRule,L as SubjectKanonak,Et as SubjectKanonakTypeRequiredRule,ot as TripleStore,Tt as TypeAmbiguityRule,Ge as TypeResolver,It as UnresolvedReferenceRule,wt as ValidationCache,Rt as ValidationContext,Ct as ValidationSeverity,so as VersionOperator,Mt as XsdImportRule,q as canonicalForm,ge as canonicalHash,Pe as compareVersions,ye as computeIntegrity,de as createAuthenticatedFetch,k as createDPoPProof,xe as createVersion,Je as extractMarkdownLinks,Xt as findDerivation,bt as findInstancesByType,We as findMalformedReferences,ft as findMarkdownLinkAt,ht as formatKanonakAddress,we as formatVersion,ce as generateDPoPKeyPair,Fe as getGlobalCachePath,S as hasValidToken,ve as isCompatibleVersion,b as isExpired,Ee as isMajorCompatible,me as loadLockFile,tt as makeUriKey,i as normalizeHost,gt as parseKanonakAddress,$e as parseVersionString,mt as parseWithPositions,Ke as pickHighestDocument,fe as saveLockFile,le as serverSupportsDPoP,rt as tripleKey,et as uriKey,nt as uriTriple,Re as versionsEqual};
@@ -254,6 +254,14 @@ export declare class LookRenderer {
254
254
  * and its nested embedded children (e.g. operands, after/then).
255
255
  */
256
256
  private renderConditionNode;
257
+ /**
258
+ * Render a PackageContents band — the default package listing. The page
259
+ * instance is a Package self-resource; this enumerates every other
260
+ * resource sharing its namespace (the package's members) and renders each
261
+ * as a card with its chip/card-tier SemanticSvg, label, and a truncated
262
+ * comment. Ontology-neutral: works for any package.
263
+ */
264
+ private renderPackageContents;
257
265
  private renderTimeline;
258
266
  /**
259
267
  * Render the Timeline trajectory chart — a server-rendered inline SVG with
@@ -23,6 +23,21 @@ export interface RawMarkdownLink {
23
23
  /** Character offset just past `]]` within the value string. */
24
24
  endOffset: number;
25
25
  }
26
+ /** A `[[` opener that does not form a well-formed `[[reference]]` link. */
27
+ export interface MalformedMarkdownLink {
28
+ /** Character offset of the dangling `[[`. */
29
+ startOffset: number;
30
+ /** A short whitespace-collapsed snippet starting at the `[[`, for messages. */
31
+ snippet: string;
32
+ }
33
+ /**
34
+ * Find every `[[` opener that does NOT begin a well-formed `[[reference]]`
35
+ * link (and is not inside code). The common cause is a reference wrapped
36
+ * across a line break — `[[persistent-energy-\nshock]]` — which the link
37
+ * grammar (no newlines inside `[[ ]]`) silently drops, so it would
38
+ * otherwise render as literal text and never be validated.
39
+ */
40
+ export declare function findMalformedReferences(value: string): MalformedMarkdownLink[];
26
41
  /**
27
42
  * Scan `value` for `[[reference]]` / `[[reference|display]]`
28
43
  * placeholders, skipping any that fall inside fenced or inline code.
@@ -1 +1 @@
1
- import{a as c,b as d,c as e,d as f}from"../chunk-IIP6J4EP.js";import{e as b}from"../chunk-4YHWMYAZ.js";import"../chunk-W6T7MOKY.js";import{a}from"../chunk-7CUTGGH3.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
1
+ import{a as c,b as d,c as e,d as f}from"../chunk-RZ57SDAT.js";import{f as b}from"../chunk-SQDXESNM.js";import"../chunk-W6T7MOKY.js";import{a}from"../chunk-7CUTGGH3.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j}from"../chunk-2BQ6SOU6.js";import"../chunk-4YHWMYAZ.js";import"../chunk-W6T7MOKY.js";import"../chunk-7CUTGGH3.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";export{f as KanonakVocabulary,h as OWL_RL_CLASSIFICATION_RULES,g as RDFS_RULES,j as Reasoner,i as ReasoningResult,e as TripleStore,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
1
+ import{a,b,c,d,e,f,g,h,i,j}from"../chunk-4EWKM5LF.js";import"../chunk-SQDXESNM.js";import"../chunk-W6T7MOKY.js";import"../chunk-7CUTGGH3.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";export{f as KanonakVocabulary,h as OWL_RL_CLASSIFICATION_RULES,g as RDFS_RULES,j as Reasoner,i as ReasoningResult,e as TripleStore,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
@@ -1,4 +1,4 @@
1
- import{b as E,c as F,d as f,f as M}from"../chunk-2JQMUZWN.js";import{a as X,b as ye}from"../chunk-CP5P7HRI.js";import{a as Oe}from"../chunk-2VCFHCFN.js";import"../chunk-IIP6J4EP.js";import"../chunk-NIGFQYVA.js";import{a as Ue}from"../chunk-FJ35VIV6.js";import{a as C,c as Re,e as Ce}from"../chunk-4YHWMYAZ.js";import{b as K,c as w,d as b,g as L,h as U,i as O,j,k as T,l as S}from"../chunk-W6T7MOKY.js";import{a as Le}from"../chunk-7CUTGGH3.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";var gt="kanonak.org",yt="document-ast",m=t=>({publisher:gt,package_:yt,name:t}),k={Document:m("Document"),Block:m("Block"),Inline:m("Inline"),StructuredValue:m("StructuredValue"),Heading:m("Heading"),Paragraph:m("Paragraph"),RawBlock:m("RawBlock"),Text:m("Text"),StructuredMap:m("StructuredMap"),StructuredEntry:m("StructuredEntry"),StructuredList:m("StructuredList"),StringScalar:m("StringScalar"),IntegerScalar:m("IntegerScalar"),EscapeHint:m("EscapeHint"),MediaType:m("MediaType"),metadata:m("metadata"),children:m("children"),level:m("level"),inlines:m("inlines"),text:m("text"),entries:m("entries"),key:m("key"),value:m("value"),escapeHint:m("escapeHint"),items:m("items"),stringValue:m("stringValue"),integerValue:m("integerValue"),rawContent:m("rawContent"),mediaType:m("mediaType"),mimeType:m("mimeType"),ESC_RAW:m("esc-raw"),ESC_YAML_SAFE:m("esc-yaml-safe"),ESC_TOML_STRING:m("esc-toml-string"),ESC_TOML_MULTILINE:m("esc-toml-multiline"),ESC_JSON:m("esc-json"),ESC_DYNAMODB_BOOL:m("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:m("esc-dynamodb-number"),ESC_DYNAMODB_NULL:m("esc-dynamodb-null"),TEXT_PLAIN:m("text-plain"),TEXT_MARKDOWN:m("text-markdown"),TEXT_HTML:m("text-html"),TEXT_CSS:m("text-css"),APPLICATION_JSON:m("application-json"),TEXT_YAML:m("text-yaml"),IMAGE_SVG_XML:m("image-svg-xml"),ResourceLink:m("ResourceLink"),target:m("target"),linkLabel:m("linkLabel"),PropertyList:m("PropertyList"),propertyEntries:m("propertyEntries"),PropertyEntry:m("PropertyEntry"),propertyKey:m("propertyKey"),propertyValue:m("propertyValue"),Table:m("Table"),tableColumnLabels:m("tableColumnLabels"),tableRows:m("tableRows"),TableRow:m("TableRow"),tableCells:m("tableCells")};function Ne(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Y=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,n){let r=kt(e.metadata,n),a=wt(e.children),u=["---",...r,"---","",a].join(`
1
+ import{b as E,c as F,d as f,f as M}from"../chunk-2JQMUZWN.js";import{a as X,b as ye}from"../chunk-JTPYH2AJ.js";import{a as Oe}from"../chunk-KE4QZNDZ.js";import"../chunk-RZ57SDAT.js";import"../chunk-NIGFQYVA.js";import{a as Ue}from"../chunk-FJ35VIV6.js";import{a as C,c as Re,f as Ce}from"../chunk-SQDXESNM.js";import{b as K,c as w,d as b,g as L,h as U,i as O,j,k as T,l as S}from"../chunk-W6T7MOKY.js";import{a as Le}from"../chunk-7CUTGGH3.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";var gt="kanonak.org",yt="document-ast",m=t=>({publisher:gt,package_:yt,name:t}),k={Document:m("Document"),Block:m("Block"),Inline:m("Inline"),StructuredValue:m("StructuredValue"),Heading:m("Heading"),Paragraph:m("Paragraph"),RawBlock:m("RawBlock"),Text:m("Text"),StructuredMap:m("StructuredMap"),StructuredEntry:m("StructuredEntry"),StructuredList:m("StructuredList"),StringScalar:m("StringScalar"),IntegerScalar:m("IntegerScalar"),EscapeHint:m("EscapeHint"),MediaType:m("MediaType"),metadata:m("metadata"),children:m("children"),level:m("level"),inlines:m("inlines"),text:m("text"),entries:m("entries"),key:m("key"),value:m("value"),escapeHint:m("escapeHint"),items:m("items"),stringValue:m("stringValue"),integerValue:m("integerValue"),rawContent:m("rawContent"),mediaType:m("mediaType"),mimeType:m("mimeType"),ESC_RAW:m("esc-raw"),ESC_YAML_SAFE:m("esc-yaml-safe"),ESC_TOML_STRING:m("esc-toml-string"),ESC_TOML_MULTILINE:m("esc-toml-multiline"),ESC_JSON:m("esc-json"),ESC_DYNAMODB_BOOL:m("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:m("esc-dynamodb-number"),ESC_DYNAMODB_NULL:m("esc-dynamodb-null"),TEXT_PLAIN:m("text-plain"),TEXT_MARKDOWN:m("text-markdown"),TEXT_HTML:m("text-html"),TEXT_CSS:m("text-css"),APPLICATION_JSON:m("application-json"),TEXT_YAML:m("text-yaml"),IMAGE_SVG_XML:m("image-svg-xml"),ResourceLink:m("ResourceLink"),target:m("target"),linkLabel:m("linkLabel"),PropertyList:m("PropertyList"),propertyEntries:m("propertyEntries"),PropertyEntry:m("PropertyEntry"),propertyKey:m("propertyKey"),propertyValue:m("propertyValue"),Table:m("Table"),tableColumnLabels:m("tableColumnLabels"),tableRows:m("tableRows"),TableRow:m("TableRow"),tableCells:m("tableCells")};function Ne(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Y=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,n){let r=kt(e.metadata,n),a=wt(e.children),u=["---",...r,"---","",a].join(`
2
2
  `);return n?.trailingNewline&&(u.endsWith(`
3
3
  `)||(u+=`
4
4
  `)),u}};function kt(t,e){if(!t)return[];let n=new Map;for(let c of t.entries)n.set(ue(c.key),c);let r=new Map;if(e?.metadataRenames)for(let[c,l]of e.metadataRenames)r.set(ue(c),l);let i=(e?.metadataKeys??t.entries.map(c=>c.key)).map(ue),u=[];for(let c of i){let l=n.get(c);if(!l)continue;let p=r.get(c),y=ue(p??c),h=Ie(l.value,l.escapeHint);h!==void 0&&u.push(`${y}: ${h}`)}return u}function ue(t){let e=t.lastIndexOf(".");return e===-1?t:t.substring(e+1)||t}function Ie(t,e){switch(t.kind){case"StringScalar":return ht(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let a=Ie(r,e);a!==void 0&&n.push(a)}return n.join(", ")}case"StructuredMap":return;default:return}}function ht(t,e){return!e||Ne(e,k.ESC_RAW)?t:Ne(e,k.ESC_YAML_SAFE)?bt(t):t}function bt(t){return t.includes(`
@@ -1 +1 @@
1
- import{A,B,C,D,E,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-A2JTW3ON.js";import"../chunk-FJ35VIV6.js";import"../chunk-4YHWMYAZ.js";import"../chunk-W6T7MOKY.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";export{w as AmbiguousReferenceRule,C as ClassDefinitionRule,n as ClassHierarchyCycleRule,u as DefinitionPropertyReferenceRule,j as EmbeddedKanonakTypeRule,k as ImportExistenceRule,t as InstancePropertyReferenceRule,E as KanonakObjectValidator,D as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,y as ObjectPropertyImportRule,z as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,A as PropertyDomainRule,o as PropertyHierarchyCycleRule,x as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,g as ResourceNamingRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,m as TypeAmbiguityRule,l as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,v as XsdImportRule};
1
+ import{A,B,C,D,E,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-YRMZ5R2W.js";import"../chunk-FJ35VIV6.js";import"../chunk-SQDXESNM.js";import"../chunk-W6T7MOKY.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";import"../chunk-5ILSX24H.js";import"../chunk-FUUTGGJS.js";export{w as AmbiguousReferenceRule,C as ClassDefinitionRule,n as ClassHierarchyCycleRule,u as DefinitionPropertyReferenceRule,j as EmbeddedKanonakTypeRule,k as ImportExistenceRule,t as InstancePropertyReferenceRule,E as KanonakObjectValidator,D as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,y as ObjectPropertyImportRule,z as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,A as PropertyDomainRule,o as PropertyHierarchyCycleRule,x as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,g as ResourceNamingRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,m as TypeAmbiguityRule,l as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,v as XsdImportRule};
@@ -26,4 +26,5 @@ export declare class MarkdownLinkRule implements IRepositoryValidationRule {
26
26
  */
27
27
  private checkDefined;
28
28
  private unresolvedLinkError;
29
+ private malformedLinkError;
29
30
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.34.0",
3
+ "version": "3.36.0",
4
4
  "description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -113,7 +113,7 @@
113
113
  "yaml-parser"
114
114
  ],
115
115
  "dependencies": {
116
- "@kanonak-protocol/types": "^3.34.0",
116
+ "@kanonak-protocol/types": "^3.36.0",
117
117
  "ignore": "^7.0.5",
118
118
  "js-yaml": "^4.1.0",
119
119
  "yaml": "^2.7.0"
@@ -1 +0,0 @@
1
- import{a as T,b as O,c as K,d as u,g,h as R,i as S,j as D,k as h,l as j}from"./chunk-W6T7MOKY.js";import{a as I}from"./chunk-7CUTGGH3.js";import{b as v,c as M}from"./chunk-5ILSX24H.js";var k=class extends O{name};var w=class extends T{value};var P=class extends g{links=[]};var L=/\[\[([^\[\]\n]+)\]\]/g,V=/```[\s\S]*?```|`[^`\n]*`/g;function x(d){if(!d||!d.includes("[["))return[];let e=[];for(let n of d.matchAll(V))e.push([n.index,n.index+n[0].length]);let t=n=>e.some(([s,a])=>n>=s&&n<a),i=[];for(let n of d.matchAll(L)){let s=n.index;if(t(s))continue;let a=n[1],r=a.indexOf("|"),o=(r===-1?a:a.slice(0,r)).trim();if(o.length===0)continue;let p=r===-1?"":a.slice(r+1).trim(),c={reference:o,startOffset:s,endOffset:s+n[0].length};p.length>0&&(c.displayText=p),i.push(c)}return i}var A=class{constructor(e){}async parseKanonaks(e){let t=[],i=await e.getAllDocumentsAsync(),n=new v(e),s=new M(n);for(let o of i){let p=o.metadata.namespace_?.toString()??"";for(let[c,m]of Object.entries(o.body)){let f=new K,y=this.resolveCanonicalEntity(c,o,p);f.namespace=y.namespace,f.name=y.name,f.statement=[];let l=await this.parseStatements(m,o,n,s,e);f.statement.push(...l),t.push(f)}}let a=new Map,r=[];for(let o of t)if(o instanceof K){let p=`${o.namespace}/${o.name}`,c=a.get(p);c?c.statement.push(...o.statement):(a.set(p,o),r.push(o))}else r.push(o);return r}resolveCanonicalEntity(e,t,i){if(!e.includes(".")||!t.metadata?.imports)return{namespace:i,name:e};let n=e.indexOf("."),s=e.substring(0,n),a=e.substring(n+1);for(let[r,o]of Object.entries(t.metadata.imports))for(let p of o)if((p.alias??p.packageName)===s){let m=p.version;return{namespace:`${r}/${p.packageName}@${m.major}.${m.minor}.${m.patch}`,name:a}}return{namespace:i,name:e}}async parseStatements(e,t,i,n,s){let a=[];if(typeof e!="object"||e===null||Array.isArray(e))return a;for(let[r,o]of Object.entries(e))try{let p=await this.getPropertyMetadata(r,t,i,s,n);if(!p)continue;let c=await this.parsePropertyValue(r,o,p,t,i,n);c&&a.push(c)}catch(p){console.error(`Error parsing property ${r}:`,p)}return a}async getPropertyMetadata(e,t,i,n,s){let a=await i.resolveEntityAsync(e,t);if(!a)return;let r=a.entity,o=r.type?.toString()??"",p=o.includes(".")?o.substring(o.lastIndexOf(".")+1):o;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(p))return;let m=s.getPropertyTypeClassification(o),f=r.range?.toString(),y;if(m==="ObjectProperty")y="ObjectProperty";else if(m==="DatatypeProperty")y="DatatypeProperty";else{let b=f&&f.includes(".")?f.substring(f.lastIndexOf(".")+1):f??"";(f?s.isKnownXsdDatatypeName(f):!1)||b==="Literal"?y="DatatypeProperty":y="ObjectProperty"}let l;return f&&(l=(await i.resolveEntityAsync(f,t))?.uri),{propertyUri:a.uri.toString(),propertyType:y,range:f,rangeUri:l,isImported:a.isImported,definedInNamespace:a.definedInNamespace}}async parsePropertyValue(e,t,i,n,s,a){let r=i.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(r,t,i,n,s,a);if(i.propertyType==="DatatypeProperty")return this.parseDatatypeValue(r,t,i,n,s,a);if(i.propertyType==="ObjectProperty")return this.parseObjectValue(r,t,i,n,s,a)}}async parseDatatypeValue(e,t,i,n,s,a){if(t instanceof Date)return g.parse(e,t.toISOString());if(typeof t=="string")return a.isSubstitutableDatatype(i.rangeUri)?await this.parseSubstitutableValue(e,t,n,s):g.parse(e,t);if(typeof t=="number")return R.parse(e,t);if(typeof t=="boolean"){let r=new S;return r.predicate=u.parse(e),r.object=t,r}}async parseSubstitutableValue(e,t,i,n){let s=new P;s.predicate=u.parse(e),s.object=t;for(let a of x(t)){let r=await n.resolveEntityAsync(a.reference,i),o;r&&(o=new u,o.subject=r.uri);let p={reference:a.reference,startOffset:a.startOffset,endOffset:a.endOffset};a.displayText!==void 0&&(p.displayText=a.displayText),o!==void 0&&(p.target=o),s.links.push(p)}return s}async parseObjectValue(e,t,i,n,s,a){if(typeof t=="string"){let r=await this.resolveReference(t,n,s);if(!r)return;let o=new D;return o.predicate=u.parse(e),o.object=r,o}if(typeof t=="object"&&!Array.isArray(t)){let r=new k;if(r.statement=await this.parseStatements(t,n,s,a,{}),r.statement.length>0){let c=new h;return c.predicate=u.parse(e),c.object=r,c}let o=[];for(let[c,m]of Object.entries(t))if(typeof m=="object"&&m!==null&&!Array.isArray(m)){let f=new k;f.name=c,f.statement=await this.parseStatements(m,n,s,a,{}),o.push(f)}else if(typeof m=="string"){let f=await this.resolveReference(m,n,s);f&&o.push(f)}if(o.length>0){let c=new j;return c.predicate=u.parse(e),c.object=o,c}let p=new h;return p.predicate=u.parse(e),p.object=r,p}}async parseListValue(e,t,i,n,s,a){let r=[],o=i.propertyType==="DatatypeProperty";for(let c of t){if(o&&(typeof c=="string"||typeof c=="number"||typeof c=="boolean")){let m=new w;m.value=c,r.push(m);continue}if(o&&c instanceof Date){let m=new w;m.value=c.toISOString(),r.push(m);continue}if(typeof c=="string"){let m=await this.resolveReference(c,n,s);m&&r.push(m)}else if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let m=new k;m.statement=await this.parseStatements(c,n,s,a,{}),r.push(m)}}let p=new j;return p.predicate=u.parse(e),p.object=r,p}async resolveReference(e,t,i){let n=await i.resolveEntityAsync(e,t);if(n){let a=new u;return a.subject=n.uri,a}let s=t.metadata?.namespace_;if(s){let{KanonakUri:a}=await import("./KanonakUri-4VJGV3FN.js"),r=s.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let p=e.indexOf("."),c=e.substring(0,p),m=e.substring(p+1);if(t.metadata?.imports){for(let[f,y]of Object.entries(t.metadata.imports))for(let l of y)if((l.alias??l.packageName)===c){let b=new u;return b.subject=new a(f,l.packageName,m,l.version),b}}}let o=new u;return o.subject=new a(s.publisher,s.package_,e,r),o}return null}async saveKanonaks(e,t){let i=new Map;for(let n of e)n instanceof K&&n.namespace&&(i.has(n.namespace)||i.set(n.namespace,[]),i.get(n.namespace).push(n));for(let[n,s]of i){let a=await this.convertKanonaksToDocument(n,s),r=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(a,r)}}async serializeToYaml(e,t){let i=e.filter(a=>a instanceof K&&a.namespace===t);if(i.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,i);return new I().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let a=[];for(let r of Object.values(this.imports))a.push(...r);return a}},body:{}},s=new Map;for(let a of t){let r={};for(let o of a.statement){let[p,c]=this.convertStatementToProperty(o);p&&c!==null&&c!==void 0&&(r[p]=c),this.collectImportsFromStatement(o,e,s)}n.body[a.name]=r}return n}convertStatementToProperty(e){if(e instanceof g)return[e.predicate.subject.name,e.object];if(e instanceof R)return[e.predicate.subject.name,e.object];if(e instanceof S)return[e.predicate.subject.name,e.object];if(e instanceof D)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof j){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof h){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let i of e)i instanceof u?t.push(i.subject.name):i instanceof k&&t.push(this.convertEmbeddedKanonakToValue(i));return t}convertEmbeddedKanonakToValue(e){let t={};for(let i of e.statement){let[n,s]=this.convertStatementToProperty(i);n&&s!==null&&s!==void 0&&(t[n]=s)}return t}collectImportsFromStatement(e,t,i){}};export{k as a,w as b,P as c,x as d,A as e};