@kanonak-protocol/sdk 3.47.0 → 3.49.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.
Files changed (53) hide show
  1. package/dist/browser.js +1 -1
  2. package/dist/chunk-2CLFEFQP.js +1 -0
  3. package/dist/chunk-3NEUHF7E.js +0 -0
  4. package/dist/chunk-64TVBQFR.js +1 -0
  5. package/dist/chunk-BHDXQKDP.js +1 -0
  6. package/dist/{chunk-RCI34BYO.js → chunk-D7A5HWZK.js} +1 -1
  7. package/dist/chunk-DC774EQL.js +1 -0
  8. package/dist/chunk-EDINPLEL.js +116 -0
  9. package/dist/{chunk-NIJV5UYW.js → chunk-GR5IXWKN.js} +1 -1
  10. package/dist/chunk-GYKITV44.js +1 -0
  11. package/dist/chunk-MOFATNEC.js +1 -0
  12. package/dist/chunk-N224PFBI.js +1 -0
  13. package/dist/chunk-Q4DKP5DO.js +1 -0
  14. package/dist/chunk-WDVGQCGC.js +59 -0
  15. package/dist/index.d.ts +6 -6
  16. package/dist/index.js +13 -13
  17. package/dist/look/LookRenderer.d.ts +10 -2
  18. package/dist/look/displayValue.d.ts +27 -0
  19. package/dist/look/index.d.ts +1 -0
  20. package/dist/parsing/KanonakObjectParser.d.ts +6 -0
  21. package/dist/parsing/index.js +1 -1
  22. package/dist/reasoning/KanonakVocabulary.d.ts +35 -8
  23. package/dist/reasoning/index.d.ts +1 -1
  24. package/dist/reasoning/index.js +1 -1
  25. package/dist/repositories/LocalFirstRepository.d.ts +28 -0
  26. package/dist/repositories/buildLocalFirstRepository.d.ts +29 -0
  27. package/dist/repositories/index.d.ts +2 -0
  28. package/dist/repositories/index.js +1 -1
  29. package/dist/resolution/TypeDirectedResolver.d.ts +36 -0
  30. package/dist/resolution/index.d.ts +2 -0
  31. package/dist/resolution/index.js +1 -1
  32. package/dist/server/index.d.ts +3 -0
  33. package/dist/server/index.js +3 -0
  34. package/dist/server/loadServerModel.d.ts +16 -0
  35. package/dist/server/route.d.ts +12 -0
  36. package/dist/server/types.d.ts +62 -0
  37. package/dist/transformations/index.js +1 -1
  38. package/dist/uri-helpers/index.js +1 -1
  39. package/dist/validation/index.d.ts +1 -1
  40. package/dist/validation/index.js +1 -1
  41. package/dist/validation/rules/repository/DisplayLensScopeRule.d.ts +27 -0
  42. package/dist/validation/rules/repository/index.d.ts +1 -0
  43. package/package.json +6 -2
  44. package/dist/chunk-2JQMUZWN.js +0 -1
  45. package/dist/chunk-4TJZIM7A.js +0 -1
  46. package/dist/chunk-5AH6GIPO.js +0 -1
  47. package/dist/chunk-FJ35VIV6.js +0 -1
  48. package/dist/chunk-FMYLEPMC.js +0 -1
  49. package/dist/chunk-HEMBMX7T.js +0 -1
  50. package/dist/chunk-IOJMTW4T.js +0 -1
  51. package/dist/chunk-JGVDV6PM.js +0 -1
  52. package/dist/chunk-KPLFNUIL.js +0 -116
  53. package/dist/chunk-SKTXJV4T.js +0 -54
@@ -0,0 +1,59 @@
1
+ import{a as ae,c as pe,d as me,f as v}from"./chunk-GYKITV44.js";import{a as se}from"./chunk-7CUTGGH3.js";import{d as fe,f as de,g as ge}from"./chunk-N224PFBI.js";import{i as ue,l as J}from"./chunk-Q4DKP5DO.js";import{c as V}from"./chunk-FQHALFRR.js";import{a as P,b as D,c as ye}from"./chunk-64TVBQFR.js";import{c as G,k as le,l as ce}from"./chunk-W6T7MOKY.js";var A=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 ee=class d{resolvedDocuments=[];currentEntityPath;withPath(e){let r=new d;return r.resolvedDocuments=this.resolvedDocuments,r.currentEntityPath=e,r}};var re=class{constructor(e){this.underlying=e;this.repository=new oe(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new v().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 s=t.shift(),i=o.get(s);if(i?.metadata.imports)for(let[n,l]of Object.entries(i.metadata.imports))for(let a of l){let c=await this.repository.getHighestCompatibleVersionAsync(n,a);if(!c)continue;let p=te(c);!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=te(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,s]of Object.entries(r.body)){if(!he(s))continue;let i=s,n=be(i,"type");if(n==="Class"||n?.endsWith(".Class")){let l=De(i);t.set(o,l)}}return t}async computePropertyNames(e){let r=await this.findDocById(e),t=new Set;if(!r)return t;for(let[o,s]of Object.entries(r.body)){if(!he(s))continue;let n=be(s,"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(te(t)===e)return t}};function te(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${V(e.version)}`}function he(d){return typeof d=="object"&&d!==null&&!Array.isArray(d)}function be(d,e){if(e in d)return Re(d[e]);for(let r of Object.keys(d))if(r.endsWith(`.${e}`))return Re(d[r])}function Re(d){return Array.isArray(d)?d.length>0?String(d[0]):void 0:d==null?void 0:String(d)}function De(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 oe=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}`:"",s=`${e}/${r.packageName}@${r.versionOperator}:${o}`,i=this.highestVersionCache.get(s);return i||(i=this.inner.getHighestCompatibleVersionAsync(e,r),this.highestVersionCache.set(s,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 I=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,s]of Object.entries(r)){let i=s?.toString()??"";if(i&&d.NAMESPACE_PREFIX_PATTERN.test(i)){let n=this.getSuggestionForPrefixedValue(i),l=e.split(".")[0],a=new g;a.ruleType=this.ruleName,a.severity="Error",a.entityName=l,a.propertyName=e,a.actualValue=o,a.expectedValue=n,a.message=`Invalid namespace prefix '${i}'. Use '${n}' without prefix.`,a.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(a)}s&&typeof s=="object"&&!Array.isArray(s)&&this.validateEntity(`${e}.${o}`,s,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 O=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,s]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 l=new g;l.ruleType=this.ruleName,l.severity="Error",l.entityName=o,l.message=`Invalid entity name '${o}'. ${n}`,l.suggestion=n,r.push(l)}s&&typeof s=="object"&&!Array.isArray(s)&&this.validatePropertyNames(o,s,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 s=new g;s.ruleType=this.ruleName,s.severity="Warning",s.entityName=e,s.propertyName=o,s.message=`Property name '${o}' in entity '${e}' doesn't follow naming conventions.`,s.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(s)}}};var w=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,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s,n=i.type;if(n){let l=[];if(Array.isArray(n))for(let a of n){let c=a?.toString();c&&c==="Property"&&!t&&l.push(c)}else{let a=n?.toString();a&&a==="Property"&&!t&&l.push(a)}for(let a of l){let c=this.getPropertyValue(i,"range"),p=this.determinePropertyType(c),y=new g;y.ruleType=this.ruleName,y.severity="Error",y.entityName=o,y.propertyName="type",y.actualValue=a,y.expectedValue=p,y.message=`Invalid property type '${a}'. 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 s=o.toString();return s==="Class"||s.endsWith(".Class")}}return!1}};var j=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 s=o,i="type"in s,n=s.type?.toString().trim();if(!i||!n){let l=new g;l.ruleType=this.ruleName,l.severity="Error",l.entityName=t,l.propertyName="type",l.message=`Subject Kanonak '${t}' must have a 'type' property.`,l.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.`,l.expectedValue="A valid class name (Scene, Character, Story, etc.)",r.push(l)}}return r}};var E=class{get ruleName(){return"EmbeddedKanonakType"}async validateAsync(e,r){let t=[],o=new D(r),s=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,s,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 s=r.substring(0,o),i=e.find(n=>n.declaringAlias===s);if(i)return i.range}if(t){let s=this.localName(t),i=e.find(n=>this.localName(n.domain)===s);if(i)return i.range}return e[0].range}async checkEmbeddedTypes(e,r,t,o,s,i,n,l){if(l>0){let c=r.type;if(c!=null){let p=await this.validateEmbeddedType(e,String(c),t,s,i);p&&n.push(p)}}let a=r.type!==void 0&&r.type!==null?String(r.type):void 0;for(let[c,p]of Object.entries(r)){let y=this.localName(c),m=o.get(y),f=(m!==void 0?this.pickRange(m,c,a):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}.${c}[${b}]`,h,f,o,s,i,n,l+1)}else await this.checkEmbeddedTypes(`${e}.${c}`,p,f,o,s,i,n,l+1)}}async validateEmbeddedType(e,r,t,o,s){if(r.length===0||!t)return null;let i=this.localName(r),n=this.localName(t);if(n==="Resource"||n==="Class")return null;let l=e.split(".")[0];if(i===n){let c=new g;return c.ruleType=this.ruleName,c.severity="Warning",c.entityName=l,c.propertyName=e,c.actualValue=r,c.expectedValue=t,c.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.`,c.suggestion=`Remove the 'type: ${r}' line, or keep it if explicitness is preferred over concision.`,c}if(await o.isSubclassOfAsync(r,t,s)||(i!==r||n!==t)&&await o.isSubclassOfAsync(i,n,s))return null;let a=new g;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=l,a.propertyName=e,a.actualValue=r,a.expectedValue=t,a.message=`Embedded object at '${e}' has 'type: ${r}', which is not a subclass of the parent property's range '${t}'.`,a.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.`,a}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),s=new Map;for(let[i,n]of o){let l=n.entity.type;if(l==null)continue;let a=String(l),c=this.localName(a);if(!(c==="Property"||c==="DatatypeProperty"||c==="ObjectProperty"||c==="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=s.get(b),k=i.includes(".");(!h||k&&!h.entityName.includes("."))&&s.set(b,{entityName:i,domain:f,range:m})}for(let i of s.values()){let n=this.localName(i.entityName),l=i.entityName.indexOf("."),a=l>0?i.entityName.substring(0,l):void 0,c=t.get(n)??[];c.push({domain:i.domain,range:i.range,declaringAlias:a}),t.set(n,c)}return t}};var $=class{ruleName="ImportExistence";async validateAsync(e,r){let t=[];if(!e.metadata?.imports)return t;let o=await r.getAllDocumentsAsync();for(let[s,i]of Object.entries(e.metadata.imports))for(let n of i)if(!await r.getHighestCompatibleVersionAsync(s,n)){let a=await this.determineImportErrorAsync(r,s,n,o),c=new g;c.ruleType=this.ruleName,c.severity="Error",c.message=a.message,c.suggestion=a.suggestion,c.entityName=`Import: ${s}/${n.packageName}`,c.actualValue=n.toString(),c.expectedValue=a.expectedValue,t.push(c)}return t}async determineImportErrorAsync(e,r,t,o){let s=await e.getDocumentsByNamespaceAsync(r,t.packageName);if(s.length===0){let a=o.filter(m=>m.metadata.namespace_?.publisher===r).map(m=>m.metadata.namespace_.package_).filter((m,u,f)=>f.indexOf(m)===u),c=this.findSimilarPackages(t.packageName,a),p=`Import '${r}/${t.package_}' not found - package does not exist`,y=c.length>0?`Did you mean: ${c.slice(0,3).join(", ")}?`:a.length>0?`Available packages in ${r}: ${a.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=s.filter(a=>a.metadata.namespace_?.version).map(a=>a.metadata.namespace_.version.toString()).sort().join(", "),l=this.getAcceptableVersionRange(t);return{message:`Import '${r}/${t.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${n}. Required: ${l}`,expectedValue:l}}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),s=Math.max(3,Math.floor(e.length*.4));return o.filter(i=>i.distance<=s).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,s=Array(t+1).fill(null).map(()=>Array(o+1).fill(0));for(let i=0;i<=t;i++)s[i][0]=i;for(let i=0;i<=o;i++)s[0][i]=i;for(let i=1;i<=t;i++)for(let n=1;n<=o;n++){let l=e[i-1]===r[n-1]?0:1;s[i][n]=Math.min(Math.min(s[i-1][n]+1,s[i][n-1]+1),s[i-1][n-1]+l)}return s[t][o]}};var S=class{ruleName="UnresolvedReference";async validateAsync(e,r){let t=[],o=new D(r),s=await o.buildEntityIndexAsync(e),i=new Set;for(let[n,l]of s.entries()){let a=l.entity.type;if(a){let c=a.toString();(c==="ObjectProperty"||c.endsWith(".ObjectProperty"))&&i.add(n)}}for(let[n,l]of Object.entries(e.body)){if(!l||typeof l!="object"||Array.isArray(l))continue;let a=l,c=this.getPropertyValue(a,"type");if(!(!c||c==="Class"||c.endsWith("Property")||c==="AnnotationProperty"))for(let[p,y]of Object.entries(a))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,s,i){if(t!=null){if(typeof t=="string")await s.resolveEntityAsync(t,o)||i.push(this.createUnresolvedReferenceError(e,r,t));else if(Array.isArray(t))for(let n=0;n<t.length;n++){let l=t[n];typeof l=="string"&&(await s.resolveEntityAsync(l,o)||i.push(this.createUnresolvedReferenceError(e,`${r}[${n}]`,l)))}}}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`,s=new g;return s.ruleType=this.ruleName,s.severity="Error",s.entityName=e,s.propertyName=r,s.actualValue=t,s.message=`Reference to '${t}' could not be resolved`,s.suggestion=o,s.expectedValue="A valid entity reference that exists in the current document or imported namespaces",s}getPropertyValue(e,r){let t=e[r];return t?t.toString():null}};var N=class{ruleName="ClassHierarchyCycle";async validateAsync(e,r){let t=[],o=new Map,s=new Set;await this.buildClassHierarchy(e,r,o,s);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let l=n,a=l.type,c=l.subClassOf;if(a?.toString()==="Class"&&c){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 s=e.metadata?.namespace_?.toString()??"";if(!(s&&o.has(s))){s&&o.add(s);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let l=n,a=l.type,c=l.subClassOf;if(a?.toString()==="Class"&&c){let p=P(c);p.length>0&&t.set(i,p)}}if(e.metadata?.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);a&&await this.buildClassHierarchy(a,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 s=r.get(e);if(s)for(let i of s){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,s=new Set;await this.buildPropertyHierarchy(e,r,o,s);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.subPropertyOf){let c=i,p=this.detectCycle(c,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=c,m.propertyName="subPropertyOf",m.actualValue=y,t.push(m);break}}return t}async buildPropertyHierarchy(e,r,t,o){let s=e.metadata?.namespace_?.toString()??"";if(!(s&&o.has(s))){s&&o.add(s);for(let[i,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)){let l=n,a=l.type;if(a){let c=a.toString();if(c==="DatatypeProperty"||c==="ObjectProperty"||c==="AnnotationProperty"){let p=l.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 l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);a&&await this.buildPropertyHierarchy(a,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 s=r.get(e);if(s)for(let i of s){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,s]of Object.entries(e.body)){if(typeof s!="object"||s===null||Array.isArray(s))continue;let i=s,n=i.type?.toString();if(n==="DatatypeProperty"||n==="ObjectProperty"||n?.endsWith(".DatatypeProperty")||n?.endsWith(".ObjectProperty")){let l="range"in i,a=i.range?.toString().trim();if(!l||!a){let c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=o,c.propertyName="range",c.message=`Property '${o}' must have a 'range' defined.`,c.suggestion=n==="DatatypeProperty"?"Add a range like: range: string (or integer, boolean, etc.)":"Add a range like: range: ClassName (the class this property expects)",c.expectedValue=n==="DatatypeProperty"?"A datatype (string, integer, boolean, decimal, etc.)":"A class name (Character, Scene, Story, etc.)",t.push(c)}}}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[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let l=i.type?.toString();this.isClassLikeType(l)&&o.add(s)}for(let[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let l=P(i.subClassOf);for(let a=0;a<l.length;a++){let c=l[a];if(this.builtInClasses.has(c)||o.has(c))continue;if(!await this.isClassAvailableInImports(e,r,c)){let y=l.length>1?`[${a}]`:"",m=new g;m.ruleType=this.ruleName,m.severity="Error",m.message=`Class '${c}' referenced in subClassOf${y} is not defined or imported`,m.suggestion=`Define '${c}' as a Class, or import a namespace that contains it`,m.entityName=s,m.propertyName="subClassOf",m.actualValue=c,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,s=t;if(t.includes(".")){let i=t.split(".",2);o=i[0],s=i[1]}for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){if(o!==null&&l.alias!==o)continue;let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=o!==null?s:t,p=a.body[c];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(a,r,c,y))return!0}}return!1}async isClassAvailableInImportsRecursive(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(s&&o.has(s)||(s&&o.add(s),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=a.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isClassLikeType(y))return!0}if(await this.isClassAvailableInImportsRecursive(a,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[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let l=i.type?.toString();(l==="DatatypeProperty"||l==="ObjectProperty"||l==="AnnotationProperty")&&o.add(s)}for(let[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let l=P(i.subPropertyOf);for(let a=0;a<l.length;a++){let c=l[a];if(this.builtInProperties.has(c)||o.has(c))continue;if(!await this.isPropertyAvailableInImports(e,r,c)){let y=l.length>1?`[${a}]`:"",m=new g;m.ruleType=this.ruleName,m.severity="Error",m.message=`Property '${c}' referenced in subPropertyOf${y} is not defined or imported`,m.suggestion=`Define '${c}' as a DatatypeProperty or ObjectProperty, or import a namespace that contains it`,m.entityName=s,m.propertyName="subPropertyOf",m.actualValue=c,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,s=t;if(t.includes(".")){let i=t.split(".",2);o=i[0],s=i[1]}for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){if(o!==null&&l.alias!==o)continue;let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=o!==null?s:t,p=a.body[c];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(a,r,c,y))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(s&&o.has(s)||(s&&o.add(s),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=a.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(y==="DatatypeProperty"||y==="ObjectProperty"||y==="AnnotationProperty")return!0}if(await this.isPropertyAvailableInImportsRecursive(a,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 s=new Map,i=new Set;await this.buildImportGraph(e,r,s,i);let n=this.detectCycle(o,s);if(n){let l=n.join(" \u2192 "),a=new g;a.ruleType=this.ruleName,a.severity="Error",a.message=`Circular namespace import detected: ${l}`,a.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",a.entityName="imports",a.propertyName="imports",a.actualValue=l,t.push(a)}return t}async buildImportGraph(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(!(!s||o.has(s))&&(o.add(s),e.metadata.imports)){let i=[];for(let[n,l]of Object.entries(e.metadata.imports))for(let a of l){let c=`${n}/${a.packageName}@${a.version}`;i.push(c);let p=await r.getHighestCompatibleVersionAsync(n,a);p&&await this.buildImportGraph(p,r,t,o)}i.length>0&&t.set(s,i)}}detectCycle(e,r){let t=[],o=new Set;return this.detectCycleRecursive(e,r,t,o)}detectCycleRecursive(e,r,t,o){let s=t.indexOf(e);if(s>=0){let n=t.slice(s);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 l=this.detectCycleRecursive(n,r,t,o);if(l)return l}return t.pop(),null}};var L=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=[],s=new Set,i=t?await this.closurePropertyNamesViaCache(e,t):void 0,n=t?await this.aliasClosurePropertyNamesViaCache(e,t):void 0;for(let[l,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=a.type?.toString();this.isPropertyType(p)&&s.add(l)}for(let[l,a]of Object.entries(e.body))if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=a,p=c.type?.toString();if(this.isPropertyType(p)||this.isClassType(p))continue;for(let[y,m]of Object.entries(c)){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(s.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=l,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,s,i){if(s!==void 0&&i!==void 0){if(o===null)return s.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=ke(e);if(!o)return t;let s=await r.getImportClosure(o);for(let i of s)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,s]of Object.entries(e.metadata.imports))for(let i of s){if(!i.alias)continue;let n=await r.repository.getHighestCompatibleVersionAsync(o,i);if(!n)continue;let l=ke(n);if(!l)continue;let a=await r.getImportClosure(l),c=t.get(i.alias)??new Set;for(let p of a)for(let y of await r.getPropertyNames(p))c.add(y);t.set(i.alias,c)}return t}async isPropertyAvailableInImports(e,r,t,o){if(!e.metadata.imports)return!1;for(let[s,i]of Object.entries(e.metadata.imports))for(let n of i){if(o!==null&&n.alias!==o)continue;let l=await r.getHighestCompatibleVersionAsync(s,n);if(l){let a=l.body[t];if(a&&typeof a=="object"&&!Array.isArray(a)){let y=a.type?.toString();if(this.isPropertyType(y))return!0}let c=new Set;if(await this.isPropertyAvailableInImportsRecursive(l,r,t,c))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(s&&o.has(s)||(s&&o.add(s),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=a.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(a,r,t,o))return!0}}return!1}};function ke(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${V(e.version)}`}var W=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[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let l=i.type?.toString();this.isPropertyType(l)&&o.add(s)}for(let[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let n=i,l=n.type?.toString();if(!this.isPropertyType(l)&&!this.isClassType(l))continue;for(let[a,c]of Object.entries(n)){if(!a||this.metadataKeys.has(a))continue;let p=a,y=null;if(a.includes(".")){let u=a.lastIndexOf(".");y=a.substring(0,u),p=a.substring(u+1)}if(o.has(p))continue;if(!await this.isPropertyAvailableInImports(e,r,p,y)){let u=this.isClassType(l)?"class":"property",f=new g;f.ruleType=this.ruleName,f.severity="Error",f.message=`Property '${a}' used on ${u} '${s}' 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 '${a}' is not defined in this namespace or any imported namespace.
21
+ 1. Define '${a}' as an ObjectProperty or DatatypeProperty in this namespace, OR
22
+ 2. Import the namespace that contains '${a}', OR
23
+ 3. Use a qualified reference like 'alias.${a}' if already imported with an alias`,f.entityName=s,f.propertyName=a,f.actualValue=c?.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[s,i]of Object.entries(e.metadata.imports))for(let n of i){if(o!==null&&n.alias!==o)continue;let l=await r.getHighestCompatibleVersionAsync(s,n);if(l){let a=l.body[t];if(a&&typeof a=="object"&&!Array.isArray(a)){let y=a.type?.toString();if(this.isPropertyType(y))return!0}let c=new Set;if(await this.isPropertyAvailableInImportsRecursive(l,r,t,c))return!0}}return!1}async isPropertyAvailableInImportsRecursive(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(s&&o.has(s)||(s&&o.add(s),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=a.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isPropertyType(y))return!0}if(await this.isPropertyAvailableInImportsRecursive(a,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,s=[];for(let[i,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let l=n,a=!1,c=l.type;if(Array.isArray(c)){for(let p of c)if(p?.toString()==="DatatypeProperty"){a=!0;break}}else c?.toString()==="DatatypeProperty"&&(a=!0);if(a){s.push(i);let p=this.getPropertyValue(l,"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(", "),l=s.sort().join(", "),a=new g;a.ruleType=this.ruleName,a.severity="Error",a.message=`XSD namespace not imported but XSD types are used: ${n}`,a.suggestion=`Add an XSD import to the imports section. The core XSD types package is 'core-xsd' from publisher 'kanonak.org'. Used by properties: ${l}`,a.entityName="imports",t.push(a)}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[,s]of Object.entries(e.imports))for(let i of s)if(i.packageName==="xsd"||i.packageName.toLowerCase().endsWith("-xsd"))return!0;for(let[s,i]of Object.entries(e.imports))for(let n of i){let l=await r.getHighestCompatibleVersionAsync(s,n);if(l?.metadata&&await this.checkXsdImportAsync(l.metadata,r,t))return!0}return!1}getPropertyValue(e,r){return e[r]?.toString()}};var U=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,r){let t=[],o=await this.buildEntitySourceMapAsync(e,r),s=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,s,e,t);return t}async buildEntitySourceMapAsync(e,r){let t=new Map,o=new Set;for(let s of Object.keys(e.body)){let i=e.metadata.namespace_?.toString()??"";t.has(s)||t.set(s,[]),t.get(s).push(`(local:${i})`)}if(e.metadata.imports)for(let[s,i]of Object.entries(e.metadata.imports))for(let n of i){let l=await r.getHighestCompatibleVersionAsync(s,n);l&&await this.collectEntitiesRecursivelyAsync(l,t,o,r)}return t}async collectEntitiesRecursivelyAsync(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(!t.has(s)){t.add(s);for(let i of Object.keys(e.body)){r.has(i)||r.set(i,[]);let n=r.get(i);n.includes(s)||n.push(s)}if(e.metadata.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await o.getHighestCompatibleVersionAsync(i,l);a&&await this.collectEntitiesRecursivelyAsync(a,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[s,i]of Object.entries(e.metadata.imports))for(let n of i){let l=await r.getHighestCompatibleVersionAsync(s,n);l&&await this.collectDatatypePropertiesAsync(l,t,o,r)}return t}async collectDatatypePropertiesAsync(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(!t.has(s)){t.add(s);for(let[i,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n))continue;let l=n.type;if(typeof l!="string")continue;(l.includes(".")?l.substring(l.lastIndexOf(".")+1):l)==="DatatypeProperty"&&r.add(i)}if(e.metadata.imports)for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await o.getHighestCompatibleVersionAsync(i,l);a&&await this.collectDatatypePropertiesAsync(a,r,t,o)}}}validateEntityReferences(e,r,t,o,s,i){for(let[n,l]of Object.entries(r)){let a=n;if(a&&!a.includes(".")){let c=t.get(a);if(c&&c.length>1&&!c.some(y=>y.startsWith("(local:"))){let y=c.filter(m=>!m.startsWith("(local:"));y.length>1&&i.push(this.createAmbiguityError(e,a,`Property '${a}'`,y,s,!0,a))}}this.validatePropertyValue(e,a,l,t,o,s,i)}}validatePropertyValue(e,r,t,o,s,i,n){if(t==null)return;let l=r&&r.includes(".")?r.substring(r.lastIndexOf(".")+1):r,a=!!l&&s.has(l);if(typeof t=="string"&&!t.includes(".")&&!a){let c=o.get(t);if(c&&c.length>1&&!c.some(y=>y.startsWith("(local:"))){let y=c.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 c=0;c<t.length;c++){let p=`${e}.${r}[${c}]`;this.validatePropertyValue(p,r,t[c],o,s,i,n)}else if(typeof t=="object"&&!Array.isArray(t)){let c=r?`${e}.${r}`:e;this.validateEntityReferences(c,t,o,s,i,n)}}createAmbiguityError(e,r,t,o,s,i,n){let l=[];for(let f of o){let b=this.findAliasForNamespace(s,f);if(b){let h=r?.split(".").pop()??r;l.push(`${b}.${h}`)}}let a=l.length>0?`Use one of: ${l.map(f=>`'${f}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${r}')`,c=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=`${a}
25
+
26
+ Defined in:
27
+ ${c}`,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 s of o)if(`${t}/${s.packageName}@${s.version}`===r&&s.alias)return s.alias;return null}};var H=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[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let l=i.type?.toString();this.isValidRangeTargetType(l)&&o.add(s)}for(let[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let n=i,l=n.type?.toString();if(l!=="DatatypeProperty"&&l!=="ObjectProperty"&&!l?.endsWith(".DatatypeProperty")&&!l?.endsWith(".ObjectProperty"))continue;let a=n.range;if(!a)continue;let c=[];if(Array.isArray(a))for(let p of a){let y=p?.toString();y&&c.push(y)}else{let p=a?.toString();p&&c.push(p)}if(c.length===0)continue;for(let p of c){if(this.primitiveTypes.has(p)||this.builtInClasses.has(p)||o.has(p))continue;if(!await this.isTypeAvailableInImports(e,r,p)){let m=l?.includes("ObjectProperty")?"ObjectProperty":"DatatypeProperty",u=new g;u.ruleType=this.ruleName,u.severity="Error",u.message=`Property '${s}' 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=s,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,s=t;if(t.includes(".")){let i=t.split(".",2);o=i[0],s=i[1]}for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){if(o!==null&&l.alias!==o)continue;let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=o!==null?s:t,p=a.body[c];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(a,r,c,y))return!0}}return!1}async isTypeAvailableInImportsRecursive(e,r,t,o){let s=e.metadata.namespace_?.toString()??"";if(s&&o.has(s)||(s&&o.add(s),!e.metadata.imports))return!1;for(let[i,n]of Object.entries(e.metadata.imports))for(let l of n){let a=await r.getHighestCompatibleVersionAsync(i,l);if(a){let c=a.body[t];if(c&&typeof c=="object"&&!Array.isArray(c)){let y=c.type?.toString();if(this.isValidRangeTargetType(y))return!0}if(await this.isTypeAvailableInImportsRecursive(a,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,s=new D(r);await s.buildEntityIndexAsync(e);for(let[i,n]of Object.entries(e.body))if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let l=n,a=!1,c=l.type;if(Array.isArray(c)){for(let p of c)if(p?.toString()==="ObjectProperty"){a=!0;break}}else c?.toString()==="ObjectProperty"&&(a=!0);if(a){let p=l.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 s.resolveEntityAsync(i,e))for(let a of n){let c=new g;c.ruleType=this.ruleName,c.severity="Warning",c.message=`ObjectProperty references class '${i}' which may not be imported`,c.suggestion=`Ensure the namespace containing '${i}' is imported, or define '${i}' in this document`,c.entityName=a,c.propertyName="range",c.actualValue=i,t.push(c)}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 D(r),s=new ye(o),i=await o.buildEntityIndexAsync(e),n=await this.buildPropertyMetadataAsync(e,r,o,i);for(let[l,a]of Object.entries(e.body))typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.scanEntityForObjectProperties(a,l,"",n,o,s,e,t);return t}async scanEntityForObjectProperties(e,r,t,o,s,i,n,l){for(let[a,c]of Object.entries(e)){if(this.standardProperties.has(a))continue;let p,y=await s.resolveEntityAsync(a,n);if(y?.uri){let m=`${y.uri.publisher}/${y.uri.package_}/${y.uri.name}`;p=o.get(m)}if(!p){let m=a,u=a.lastIndexOf(".");u>0&&u<a.length-1&&(m=a.substring(u+1)),p=o.get(m)}if(p&&i.isEffectiveObjectProperty(p.propertyType,p.rangeUri)){let u=t?`${t}.${a}`:a;if(typeof c=="string"&&c.trim().length>0){let f=c.trim();if(f.includes(",")){let h=f.split(",").map(k=>k.trim()).filter(k=>k.length>0);l.push({ruleType:this.ruleName,severity:"Error",message:`Property '${a}' has a comma-separated string value, but ObjectProperty expects a list of references`,suggestion:`Use YAML list format:
33
+ ${a}:
34
+ - ${h[0]}
35
+ ${h.slice(1).map(k=>` - ${k}`).join(`
36
+ `)}`,entityName:r,propertyName:a,propertyPath:u,actualValue:f,expectedValue:`A single reference to ${p.range??"an entity"} OR a YAML list`});continue}let b=await s.resolveEntityAsync(f,n);if(b)p.range&&(await this.validateRangeType(b,p.range,s,n)||l.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${a}' expects a ${p.range}, but '${f}' may not be a ${p.range}`,suggestion:`Ensure '${f}' is defined with appropriate type`,entityName:r,propertyName:a,propertyPath:u,actualValue:f,expectedValue:p.range}));else{let h=p.range??"entity";l.push({ruleType:this.ruleName,severity:"Error",message:`Property '${a}' references '${f}' which is not defined or imported`,suggestion:`Define '${f}' or import a namespace that contains it. Expected range: ${h}`,entityName:r,propertyName:a,propertyPath:u,actualValue:f,expectedValue:"Defined or imported entity"})}}else if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let f=t?`${t}.${a}`:a;await this.scanEntityForObjectProperties(c,r,f,o,s,i,n,l)}else if(Array.isArray(c))for(let f=0;f<c.length;f++){let b=c[f];if(typeof b=="string"&&b.trim().length>0){let h=b.trim(),k=await s.resolveEntityAsync(h,n);if(k){if(p.range&&!await this.validateRangeType(k,p.range,s,n)){let Q=t?`${t}.${a}[${f}]`:`${a}[${f}]`;l.push({ruleType:this.ruleName,severity:"Warning",message:`Property '${a}' expects a ${p.range}, but '${h}' may not be a ${p.range}`,suggestion:`Ensure '${h}' is defined with appropriate type`,entityName:r,propertyName:`${a}[${f}]`,propertyPath:Q,actualValue:h,expectedValue:p.range})}}else{let ie=p.range??"entity",Q=t?`${t}.${a}[${f}]`:`${a}[${f}]`;l.push({ruleType:this.ruleName,severity:"Error",message:`Property '${a}' references '${h}' which is not defined or imported`,suggestion:`Define '${h}' or import a namespace that contains it. Expected range: ${ie}`,entityName:r,propertyName:`${a}[${f}]`,propertyPath:Q,actualValue:h,expectedValue:"Defined or imported entity"})}}else if(typeof b=="object"&&b!==null&&!Array.isArray(b)){let h=t?`${t}.${a}[${f}]`:`${a}[${f}]`;await this.scanEntityForObjectProperties(b,r,h,o,s,i,n,l)}}}if(typeof c=="object"&&c!==null&&!Array.isArray(c)&&!o.has(a)){let m=t?`${t}.${a}`:a;await this.scanEntityForObjectProperties(c,r,m,o,s,i,n,l)}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=t?`${t}.${a}[${m}]`:`${a}[${m}]`;await this.scanEntityForObjectProperties(u,r,f,o,s,i,n,l)}}}}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 l of i){let a=l?.toString();a&&a.trim().length>0&&n.push(a)}else{let l=i?.toString();l&&l.trim().length>0&&n.push(l)}for(let l of n){let a=l.includes(".")?l.split(".")[1]:l;if(a===r||r==="Property"&&(a==="DatatypeProperty"||a==="ObjectProperty"||a==="AnnotationProperty")||r==="Class"&&a==="Class"||await t.isSubclassOfAsync(l,r,o))return!0}}return!1}async buildPropertyMetadataAsync(e,r,t,o){let s=new Map;for(let[i,n]of o){let l=n.entity.type;if(l){let a=[];if(Array.isArray(l))for(let y of l){let m=y?.toString();m&&m.trim().length>0&&a.push(m)}else{let y=l?.toString();y&&y.trim().length>0&&a.push(y)}let c=!1,p="Property";for(let y of a){let m=y.includes(".")?y.split(".")[1]:y;if(m==="Property"||m==="DatatypeProperty"||m==="ObjectProperty"||m==="AnnotationProperty"){c=!0,p=y;break}}if(c){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(s.set(i,y),n.uri){let u=`${n.uri.publisher}/${n.uri.package_}/${n.uri.name}`;s.set(u,y)}}}}return s}};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=[],s=new Map;for(let[n,l]of Object.entries(e.body))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let a=l,c=this.getPropertyValue(a,"type");(c==="DatatypeProperty"||c?.endsWith(".DatatypeProperty")||c==="ObjectProperty"||c?.endsWith(".ObjectProperty")||c==="AnnotationProperty"||c?.endsWith(".AnnotationProperty"))&&s.set(n,a)}let i=t?await this.buildClassHierarchyViaCache(e,t):await this.buildCompleteClassHierarchyAsync(e,r);for(let[n,l]of Object.entries(e.body))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let a=l,c=this.getPropertyValue(a,"type");if(!c||c==="Class"||c.endsWith(".Class")||c.endsWith("Property")||c==="AnnotationProperty")continue;this.validateEntityProperties(a,n,c,s,i,o)}return o}async buildClassHierarchyViaCache(e,r){let t=new Map,o=ve(e);if(!o)return t;let s=await r.getImportClosure(o);for(let i of s){let n=await r.getClassDeclarations(i);for(let[l,a]of n)a.length>0&&t.set(l,a)}return t}async buildCompleteClassHierarchyAsync(e,r){let t=new Map,o=new Set,s=async(n,l)=>{if(!o.has(l)){o.add(l);for(let[a,c]of Object.entries(n.body))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let p=c,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(a,u)}}if(n.metadata.imports)for(let[a,c]of Object.entries(n.metadata.imports))for(let p of c)try{let y=await r.getHighestCompatibleVersionAsync(a,p);if(y){let m=`${a}/${p.packageName}@${p.version}`;await s(y,m)}}catch{}}},i=e.metadata.namespace_?.toString()??"unknown";return await s(e,i),t}validateEntityProperties(e,r,t,o,s,i){for(let[n,l]of Object.entries(e)){if(this.standardProperties.has(n))continue;let a=n,c=n.lastIndexOf(".");c>0&&c<n.length-1&&(a=n.substring(c+1));let p=o.get(a);if(!p)continue;let y=this.getPropertyValue(p,"domain");if(y){if(!this.isTypeCompatibleWithDomain(t,y,s)){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 l=="object"&&l!==null&&!Array.isArray(l)){let m=l,u=this.getPropertyValue(m,"type");if(u){let f=`${r}.${n}`;this.validateEntityProperties(m,f,u,o,s,i)}else{let f=this.getPropertyValue(p,"range");if(f){let b=`${r}.${n}`;this.validateEntityProperties(m,b,f,o,s,i)}}}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=u,b=this.getPropertyValue(f,"type");if(b){let h=`${r}.${n}[${m}]`;this.validateEntityProperties(f,h,b,o,s,i)}else{let h=this.getPropertyValue(p,"range");if(h){let k=`${r}.${n}[${m}]`;this.validateEntityProperties(f,k,h,o,s,i)}}}}}}}isTypeCompatibleWithDomain(e,r,t){if(e===r)return!0;let o=new Set,s=[e];for(;s.length>0;){let i=s.shift();if(o.has(i))continue;o.add(i);let n=t.get(i);if(n)for(let l of n){if(l===r)return!0;s.push(l)}}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 ve(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${V(e.version)}`}var X=class{get ruleName(){return"PropertyValueType"}async validateAsync(e,r){let t=[],o=new Map;for(let[s,i]of Object.entries(e.body))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let n=i,l=this.getPropertyValue(n,"type");(l==="DatatypeProperty"||l==="ObjectProperty")&&o.set(s,n)}for(let[s,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let n=i,l=this.getPropertyValue(n,"type");if(!(!l||l==="Class"||l.endsWith("Property")||l==="AnnotationProperty"))for(let[a,c]of Object.entries(n)){if(a==="type"||a==="label"||a==="comment")continue;let p=a,y=a.lastIndexOf(".");y>0&&y<a.length-1&&(p=a.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 c=="object"&&c!==null&&!Array.isArray(c)||Array.isArray(c))t.push({ruleType:this.ruleName,severity:"Error",entityName:s,propertyName:a,message:`Property '${a}' is a DatatypeProperty with range '${f}' but instance '${s}' has a complex object value`,suggestion:`Either:
40
+ 1. Create a class for this data and change '${a}' 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,c)){let b={ruleType:this.ruleName,severity:"Error",entityName:s,propertyName:a,message:`Property '${a}' expects type '${f}' but instance '${s}' has value of type '${this.getValueTypeName(c)}'`,suggestion:`Provide a value of type '${f}'`,toString:()=>""};f&&(b.expectedValue=f),t.push(b)}}else if(u==="ObjectProperty")if(Array.isArray(c))for(let b=0;b<c.length;b++){let h=c[b];typeof h!="string"&&(typeof h!="object"||h===null||Array.isArray(h))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:s,propertyName:`${a}[${b}]`,message:`ObjectProperty '${a}' array item ${b} in instance '${s}' has invalid type '${this.getValueTypeName(h)}'`,suggestion:"Array items must be references (strings) or embedded objects (dictionaries)",expectedValue:"string or object"})}else typeof c!="string"&&(typeof c!="object"||c===null||Array.isArray(c))&&t.push({ruleType:this.ruleName,severity:"Error",entityName:s,propertyName:a,message:`ObjectProperty '${a}' in instance '${s}' has invalid value type '${this.getValueTypeName(c)}'`,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 s of t)o.push(s?.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,s=new Set;for(let[n,l]of Object.entries(e.body))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let c=l.type;if(c)if(Array.isArray(c))for(let p of c){let y=p?.toString();if(y==="Class"||y&&y.endsWith(".Class")){s.add(n);break}}else{let p=c?.toString();(p==="Class"||p&&p.endsWith(".Class"))&&s.add(n)}}for(let[n,l]of Object.entries(e.body))if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let a=l,c=a.type;if(c)if(Array.isArray(c)){let p=!1;for(let y of c){let m=y?.toString();if(m&&this.isDefinitionType(m)){p=!0;break}}if(!p)for(let y of c){let m=y?.toString();m&&m.trim().length>0&&(o.has(m)||o.set(m,[]),o.get(m).push(n))}}else{let p=c?.toString();p&&p.trim().length>0&&(this.isDefinitionType(p)||(o.has(p)||o.set(p,[]),o.get(p).push(n)))}this.checkNestedTypes(a,n,o,n)}let i=new D(r);for(let[n,l]of o){if(this.builtInClasses.has(n)||s.has(n))continue;let a=await i.resolveEntityAsync(n,e);if(!(a&&this.isClassEntity(a.entity))){let p=Array.from(new Set(l)).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 s=e,i=s.type;if(i){let n=new Set(["Class","DatatypeProperty","ObjectProperty","AnnotationProperty"]);if(Array.isArray(i))for(let l of i){let a=l?.toString();a&&a.trim().length>0&&!n.has(a)&&(t.has(a)||t.set(a,[]),t.get(a).push(o))}else{let l=i?.toString();l&&l.trim().length>0&&!n.has(l)&&(t.has(l)||t.set(l,[]),t.get(l).push(o))}}for(let[n,l]of Object.entries(s))if(n!=="type"){let a=`${o}.${n}`;this.checkNestedTypes(l,r,t,a)}}else if(Array.isArray(e))for(let s=0;s<e.length;s++){let i=`${o}[${s}]`;this.checkNestedTypes(e[s],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=[],s;if(t){let i=await t.getKanonaks(),n=Ae(e);s=n?i.filter(l=>l instanceof G&&l.namespace===n):[]}else{let i=new J(e,r);s=await new v().parseKanonaks(i)}for(let i of s)i instanceof G&&this.checkDefined(i,i.name,o);return o}checkDefined(e,r,t){for(let o of e.statement)if(o instanceof pe){let s=o.predicate.subject?.name??"(unknown)";for(let i of o.links)i.target||t.push(this.unresolvedLinkError(r,s,i.reference));for(let i of me(o.object))t.push(this.malformedLinkError(r,s,i.snippet))}else if(o instanceof le)this.checkDefined(o.object,r,t);else if(o instanceof ce)for(let s of o.object)s instanceof ae&&this.checkDefined(s,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 Ae(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${V(e.version)}`}var Pe="kanonak.org",Ve="look",Ie={publisher:Pe,package_:Ve,name:"displayLabel"},Oe={publisher:Pe,package_:Ve,name:"displaySummary"},Z=class{ruleName="DisplayLensScope";async validateAsync(e,r,t){let o=[],s;t?s=await t.getKanonaks():s=await new v().parseKanonaks(new J(e,r));let i=we(e);if(!i)return o;for(let n of s)n instanceof G&&n.namespace===i&&(this.checkLens(s,n,Ie,"displayLabel",o),this.checkLens(s,n,Oe,"displaySummary",o));return o}checkLens(e,r,t,o,s){let i=ue(r,t);if(!i)return;let n=[],l=fe(r);if(l&&n.push(l),n.push(...ge(r)),n.length===0)return;n.some(c=>de(e,c,i).ok)||s.push(this.scopeError(r.name,o,i.name))}scopeError(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=`${r} points at '${t}', which is not a property in scope for '${e}'`,o.expectedValue="A property whose domain is this resource's class, an ancestor, or rdfs.Resource",o.suggestion=`'${t}' resolves, but its domain does not cover '${e}', so the lens would silently fall back to the resource's name at render time.
55
+
56
+ Possible solutions:
57
+ \u2022 Point ${r} at a property declared on this class (or an ancestor / rdfs.Resource)
58
+ \u2022 Set the property's domain to this class if it should apply here
59
+ \u2022 Use rdfs.label / rdfs.comment for the universal default`,o}};function we(d){let e=d.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${V(e.version)}`}var ne=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new se,this.documentRules=[new I,new O,new w,new j],this.repositoryRules=[new E,new $,new S,new N,new C,new K,new T,new x,new M,new L,new W,new _,new U,new H,new F,new B,new q,new X,new z,new Y,new Z]}async validateAsync(e,r,t){let o=new A;for(let s of this.documentRules)try{let i=s.validate(e);this.addErrorsToResult(o,i)}catch(i){let n=new g;n.ruleType=s.ruleName,n.severity="Error",n.message=`Validation rule '${s.ruleName}' failed: ${i instanceof Error?i.message:String(i)}`,o.errors.push(n)}if(r){let s=[],i=t?.repository??r;for(let n of this.repositoryRules)try{let l=await n.validateAsync(e,i,t);this.addErrorsToResult(o,l)}catch(l){let a=l instanceof Error?l.message:String(l);s.push({ruleName:n.ruleName,cause:a})}if(s.length>0){let n=new Map;for(let{ruleName:l,cause:a}of s){let c=n.get(a);c?c.push(l):n.set(a,[l])}for(let[l,a]of n){let c=new g;c.ruleType=a[0],c.severity="Error",a.length===1?c.message=`Validation rule '${a[0]}' failed: ${l}`:c.message=`${l} (affects ${a.length} rules: ${a.join(", ")})`,o.errors.push(c)}}}return o.isValid=o.errors.length===0,o}async validateYamlAsync(e,r,t){let o=this.parser.parseWithErrors(e);if(!o.isValid){let s=new A;s.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."),s.errors.push(n)}return s}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{A as a,R as b,g as c,ee as d,re as e,I as f,O as g,w as h,j as i,E as j,$ as k,S as l,N as m,C as n,K as o,T as p,x as q,M as r,L as s,W as t,_ as u,U as v,H as w,F as x,B as y,q as z,X as A,z as B,Y as C,Z as D,ne as E};
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { InMemoryKanonakDocumentRepository, FileSystemKanonakDocumentRepository, CompositeKanonakDocumentRepository, RepositoryFactory, DocumentLocation, HttpKanonakDocumentRepository, PublisherIndex, PublisherConfigResolver, getGlobalCachePath } from './repositories/index.js';
2
- export type { PublisherConfig } from './repositories/index.js';
1
+ export { InMemoryKanonakDocumentRepository, FileSystemKanonakDocumentRepository, CompositeKanonakDocumentRepository, RepositoryFactory, DocumentLocation, HttpKanonakDocumentRepository, LocalFirstRepository, buildLocalFirstRepository, collectKanonakFiles, PublisherIndex, PublisherConfigResolver, getGlobalCachePath } from './repositories/index.js';
2
+ export type { PublisherConfig, HttpCacheHooks } from './repositories/index.js';
3
3
  export { GraphBuilder, NodeType, EdgeType } from './graph/index.js';
4
4
  export type { GraphNode, GraphEdge, GraphData } from './graph/index.js';
5
5
  export { Reasoner, ReasoningResult, TripleStore, KanonakVocabulary, uriKey, makeUriKey, tripleKey, uriTriple, RDFS_RULES, OWL_RL_CLASSIFICATION_RULES, } from './reasoning/index.js';
@@ -8,8 +8,8 @@ export { GitIgnoreFilter } from './filtering/index.js';
8
8
  export type { IGitIgnoreFilter } from './filtering/index.js';
9
9
  export { KanonakParser, KanonakObjectParser, PropertyMetadata, KanonakDocumentPositions, parseWithPositions, findMarkdownLinkAt, } from './parsing/index.js';
10
10
  export type { IKanonakObjectParser, SourcePosition, ImportPackageEntry, ParsedDocumentWithPositions, } from './parsing/index.js';
11
- export { ResourceResolver, KanonakUri, KanonakUriBuilder, parseKanonakAddress, formatKanonakAddress, KanonakUrlResolver, TypeResolver, ResourceTypeClassifier, findInstancesByType, compareVersions, versionsEqual, formatVersion, parseVersionString, createVersion, isCompatibleVersion, isMajorCompatible, pickHighestDocument, } from './resolution/index.js';
12
- export type { ResourceResolutionResult, ILogger, InstanceSearchResult, DocumentVersionPick, KanonakAddress, UrlAddress, PublisherUrlAddress, PackageUrlAddress, ResourceUrlAddress, VersionSpec, UrlForm, } from './resolution/index.js';
11
+ export { ResourceResolver, KanonakUri, KanonakUriBuilder, parseKanonakAddress, formatKanonakAddress, KanonakUrlResolver, TypeResolver, ResourceTypeClassifier, findInstancesByType, compareVersions, versionsEqual, formatVersion, parseVersionString, createVersion, isCompatibleVersion, isMajorCompatible, pickHighestDocument, propertiesInScope, resolvePropertyStep, contextTypesOf, subjectUri, } from './resolution/index.js';
12
+ export type { ResourceResolutionResult, ILogger, InstanceSearchResult, DocumentVersionPick, PropertyDescriptor, PropertyKind, StepResolution, KanonakAddress, UrlAddress, PublisherUrlAddress, PackageUrlAddress, ResourceUrlAddress, VersionSpec, UrlForm, } from './resolution/index.js';
13
13
  export { Kanonak, DefinedKanonak, SubjectKanonak, EmbeddedKanonak, ReferenceKanonak, LiteralKanonak } from './kanonaks/index.js';
14
14
  export type { IStatement } from './statements/index.js';
15
15
  export type { MarkdownLink } from './statements/index.js';
@@ -27,6 +27,6 @@ export { loadLockFile, saveLockFile, computeIntegrity, } from './lock/index.js';
27
27
  export type { LockFile, LockEntry } from './lock/index.js';
28
28
  export { findDerivation } from './derivation/index.js';
29
29
  export type { DerivationEntityUri, TransformationReferenceTuple, DerivationLookupResult, } from './derivation/index.js';
30
- export { LookRenderer } from './look/index.js';
31
- export type { ResolvedLook } from './look/index.js';
30
+ export { LookRenderer, resolveDisplayValue } from './look/index.js';
31
+ export type { ResolvedLook, DisplayValue } from './look/index.js';
32
32
  export { canonicalForm, canonicalHash } from './canonical/index.js';
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
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-IOJMTW4T.js";import{b as Xt}from"./chunk-KPLFNUIL.js";import{a as Xe,b as Ze,c as Qe,d as b,e as S,f as i}from"./chunk-RCI34BYO.js";import{a as Yt}from"./chunk-JGVDV6PM.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-VHUJSHH7.js";import{a as ut,b as pt,c as mt,d as ft}from"./chunk-NIJV5UYW.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,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-SKTXJV4T.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-FMYLEPMC.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-HEMBMX7T.js";import{a as Me}from"./chunk-FUUTGGJS.js";import{a as dt}from"./chunk-ODIECDN7.js";import{VersionOperator as io}from"@kanonak-protocol/types/document/models/enums";import{existsSync as yr,readFileSync as gr}from"fs";import{homedir as hr}from"os";import{join as kr}from"path";import{execFile as Zt}from"child_process";import{promisify as Qt}from"util";var C=Qt(Zt),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 ct,b as lt,c as dt,d as ut,e as pt}from"./chunk-2CLFEFQP.js";import{a as or,c as ar}from"./chunk-EDINPLEL.js";import{a as at,b as it,c as st,d as b,e as S,f as i}from"./chunk-D7A5HWZK.js";import{a as nr}from"./chunk-BHDXQKDP.js";import"./chunk-3NEUHF7E.js";import{a as Te,b as je,c as Le,d as Fe,e as De,f as Ue,g as Ve,h as He}from"./chunk-MOFATNEC.js";import{a as Ie,b as Ne,c as Oe,d as Ae}from"./chunk-VHUJSHH7.js";import{a as ft,b as yt,c as gt,d as ht}from"./chunk-GR5IXWKN.js";import{a as kt,b as $t}from"./chunk-DC774EQL.js";import{a as Ct}from"./chunk-NIGFQYVA.js";import{A as Qt,B as er,C as tr,E as rr,a as vt,b as Et,c as Kt,d as It,e as Bt,f as Tt,g as jt,h as Lt,i as Ft,j as Dt,k as Nt,l as Ot,m as At,n as Ut,o as Vt,p as Ht,q as Mt,r as _t,s as zt,t as Gt,u as Wt,v as Jt,w as qt,x as Yt,y as Xt,z as Zt}from"./chunk-WDVGQCGC.js";import{a as F,b as N,c as We,d as tt,e as rt,f as nt}from"./chunk-GYKITV44.js";import{a as Be}from"./chunk-7CUTGGH3.js";import{a as ot,b as bt,c as St,d as Pt,e as Rt,f as wt,g as xt}from"./chunk-N224PFBI.js";import"./chunk-Q4DKP5DO.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 Je,c as qe,d as Ye,e as Xe,f as Ze,h as Qe,j as et}from"./chunk-64TVBQFR.js";import{a as Me,b as j,c as L,d as D,e as ze,f as Ge,g as O,h as A,i as U,j as V,k as H,l as M}from"./chunk-W6T7MOKY.js";import{a as _e}from"./chunk-FUUTGGJS.js";import{a as mt}from"./chunk-ODIECDN7.js";import{VersionOperator as yo}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Rr,readFileSync as wr}from"fs";import{homedir as xr}from"os";import{join as $r}from"path";import{execFile as ir}from"child_process";import{promisify as sr}from"util";var C=sr(ir),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 er}from"child_process";import{promisify as tr}from"util";var rr=tr(er),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 cr}from"child_process";import{promisify as lr}from"util";var dr=lr(cr),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
- ${nr}
44
+ ${ur}
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 rr(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 dr(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
- "@`,nr="";import{execFile as or,spawn as ar}from"child_process";import{promisify as ir}from"util";var K=ir(or),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=ar("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 sr,createDecipheriv as cr,randomBytes as re}from"crypto";import{homedir as lr}from"os";import{join as W,dirname as ne}from"path";var ae=W(lr(),".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=cr(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=sr(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 dr}from"child_process";import{promisify as ur}from"util";var pr=ur(dr),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
+ "@`,ur="";import{execFile as pr,spawn as mr}from"child_process";import{promisify as fr}from"util";var K=fr(pr),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=mr("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 yr,createDecipheriv as gr,randomBytes as re}from"crypto";import{homedir as hr}from"os";import{join as W,dirname as ne}from"path";var ae=W(hr(),".config","kanonak"),y=W(ae,"keyring.key"),I=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(I))return{};try{let e=this.getOrCreateKey(),r=ee(I);if(r.length<u+G)return{};let n=r.subarray(0,u),o=r.subarray(u,u+G),a=r.subarray(u+G),s=gr(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=yr(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(I),{recursive:!0}),te(I,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 kr}from"child_process";import{promisify as br}from"util";var Sr=br(kr),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}': ${B(n)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
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 pr(this.helperPath,[e],{...r&&{input:JSON.stringify(r)},timeout:ie});return n}catch(n){throw mr(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):fr(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 mr(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"}function fr(t){return t instanceof Error&&"killed"in t&&t.killed}var J=kr(hr(),".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=br(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=Sr();return e.credentialHelper?new h(e.credentialHelper):process.platform==="darwin"?new p:process.platform==="win32"?new m:await _()?new f:new g}};function br(t){let r="KANONAK_TOKEN_"+i(t).replace(/[.\-]/g,"_").toUpperCase();return process.env[r]??null}function Sr(){if(!yr(J))return{};try{return JSON.parse(gr(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 Cr,createPrivateKey as Pr,generateKeyPairSync as Rr,randomUUID as wr,sign as xr}from"crypto";function ce(){let{publicKey:t,privateKey:e}=Rr("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:wr(),htm:r.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(c.ath=Cr("sha256").update(o).digest("base64url")),a&&(c.nonce=a),$r(s,c,t)}function le(t){return!t||t.length===0?!1:t.some(e=>e.toUpperCase()==="ES256")}function $r(t,e,r){let n=se(JSON.stringify(t)),o=se(JSON.stringify(e)),a=`${n}.${o}`,s=Pr({key:r,format:"jwk"}),l=xr("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 vr,writeFileSync as Er,existsSync as Kr}from"fs";import{createHash as Br}from"crypto";import ue from"js-yaml";var pe="kanonak.lock",Ir=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function me(t=pe){if(!Kr(t))return null;let e=vr(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:'"'});Er(e,Ir+n,"utf-8")}function ye(t){return`sha256:${Br("sha256").update(t).digest("hex")}`}import{createHash as Tr}from"crypto";function q(t){let e=[];for(let n of t)n instanceof L&&e.push(jr(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:${Tr("sha256").update(e,"utf8").digest("hex")}`}function jr(t){let e=Ar(t),r=Y(t.statement);return{uri:e,statements:r}}function Y(t){let e=[];for(let r of t){let n=Lr(r);n&&e.push(n)}return e.sort((r,n)=>r.predicate<n.predicate?-1:r.predicate>n.predicate?1:0),e}function Lr(t){let e=Or(t);if(!e)return;let r=Fr(t);if(r)return Dr(e,r)}function Fr(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(Nr)}}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 Nr(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 Dr(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 Or(t){let e=t.predicate;if(e)return be(e.subject)}function Ar(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{Mt as AmbiguousReferenceRule,U as BooleanStatement,Wt as ClassDefinitionRule,Tt as ClassHierarchyCycleRule,Le as CompositeKanonakDocumentRepository,T as CredentialStore,j as DefinedKanonak,At 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,Ot as InstancePropertyReferenceRule,Ue as Kanonak,pt as KanonakDocumentPositions,qe as KanonakObjectParser,qt as KanonakObjectValidator,Ie as KanonakParser,Me as KanonakUri,yt as KanonakUriBuilder,kt as KanonakUrlResolver,at as KanonakVocabulary,H as ListStatement,D as LiteralKanonak,Xt as LookRenderer,Jt as MarkdownLinkRule,_e as MarkdownStatement,Dt as NamespaceImportCycleRule,xt as NamespacePrefixRule,Xe as NodeType,A as NumberStatement,st as OWL_RL_CLASSIFICATION_RULES,Ht as ObjectPropertyImportRule,_t as ObjectPropertyValueValidationRule,Pt as OntologyValidationError,St as OntologyValidationResult,zt as PropertyDomainRule,jt as PropertyHierarchyCycleRule,ut as PropertyMetadata,Vt as PropertyRangeReferenceRule,Lt as PropertyRangeRequiredRule,vt as PropertyTypeSpecificityRule,Gt 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,Ft as SubClassOfReferenceRule,Nt as SubPropertyOfReferenceRule,L as SubjectKanonak,Et as SubjectKanonakTypeRequiredRule,ot as TripleStore,Ge as TypeResolver,It as UnresolvedReferenceRule,wt as ValidationCache,Rt as ValidationContext,Ct as ValidationSeverity,io as VersionOperator,Ut 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,Yt 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};
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}': ${B(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}': ${B(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: ${B(e)}`),[]}}async runHelper(e,r){try{let{stdout:n}=await Sr(this.helperPath,[e],{...r&&{input:JSON.stringify(r)},timeout:ie});return n}catch(n){throw Cr(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Pr(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 B(t){return t instanceof Error?t.message:String(t)}function Cr(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"}function Pr(t){return t instanceof Error&&"killed"in t&&t.killed}var J=$r(xr(),".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=vr(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=Er();return e.credentialHelper?new h(e.credentialHelper):process.platform==="darwin"?new p:process.platform==="win32"?new m:await _()?new f:new g}};function vr(t){let r="KANONAK_TOKEN_"+i(t).replace(/[.\-]/g,"_").toUpperCase();return process.env[r]??null}function Er(){if(!Rr(J))return{};try{return JSON.parse(wr(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 Kr,createPrivateKey as Ir,generateKeyPairSync as Br,randomUUID as Tr,sign as jr}from"crypto";function ce(){let{publicKey:t,privateKey:e}=Br("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:Tr(),htm:r.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(c.ath=Kr("sha256").update(o).digest("base64url")),a&&(c.nonce=a),Lr(s,c,t)}function le(t){return!t||t.length===0?!1:t.some(e=>e.toUpperCase()==="ES256")}function Lr(t,e,r){let n=se(JSON.stringify(t)),o=se(JSON.stringify(e)),a=`${n}.${o}`,s=Ir({key:r,format:"jwk"}),l=jr("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 Fr,writeFileSync as Dr,existsSync as Nr}from"fs";import{createHash as Or}from"crypto";import ue from"js-yaml";var pe="kanonak.lock",Ar=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function me(t=pe){if(!Nr(t))return null;let e=Fr(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:'"'});Dr(e,Ar+n,"utf-8")}function ye(t){return`sha256:${Or("sha256").update(t).digest("hex")}`}import{createHash as Ur}from"crypto";function q(t){let e=[];for(let n of t)n instanceof L&&e.push(Vr(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:${Ur("sha256").update(e,"utf8").digest("hex")}`}function Vr(t){let e=Wr(t),r=Y(t.statement);return{uri:e,statements:r}}function Y(t){let e=[];for(let r of t){let n=Hr(r);n&&e.push(n)}return e.sort((r,n)=>r.predicate<n.predicate?-1:r.predicate>n.predicate?1:0),e}function Hr(t){let e=Gr(t);if(!e)return;let r=Mr(t);if(r)return zr(e,r)}function Mr(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 M)return{type:"list",items:t.object.map(_r)}}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 _r(t){if(t instanceof D)return{type:"ref",value:ke(t)};if(t instanceof F)return he(t);if(t instanceof N){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 zr(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 Gr(t){let e=t.predicate;if(e)return be(e.subject)}function Wr(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{Jt as AmbiguousReferenceRule,U as BooleanStatement,er as ClassDefinitionRule,At as ClassHierarchyCycleRule,Le as CompositeKanonakDocumentRepository,T as CredentialStore,j as DefinedKanonak,Gt as DefinitionPropertyReferenceRule,je as DocumentLocation,it as EdgeType,F as EmbeddedKanonak,Dt as EmbeddedKanonakTypeRule,H as EmbeddedStatement,Te as FileSystemKanonakDocumentRepository,mt as GitIgnoreFilter,st as GraphBuilder,Ae as HttpKanonakDocumentRepository,Nt as ImportExistenceRule,Ie as InMemoryKanonakDocumentRepository,zt as InstancePropertyReferenceRule,Me as Kanonak,yt as KanonakDocumentPositions,nt as KanonakObjectParser,rr as KanonakObjectValidator,Be as KanonakParser,_e as KanonakUri,kt as KanonakUriBuilder,Ct as KanonakUrlResolver,et as KanonakVocabulary,M as ListStatement,N as LiteralKanonak,Ue as LocalFirstRepository,ar as LookRenderer,tr as MarkdownLinkRule,We as MarkdownStatement,_t as NamespaceImportCycleRule,Tt as NamespacePrefixRule,at as NodeType,A as NumberStatement,dt as OWL_RL_CLASSIFICATION_RULES,Yt as ObjectPropertyImportRule,Xt as ObjectPropertyValueValidationRule,Kt as OntologyValidationError,vt as OntologyValidationResult,Zt as PropertyDomainRule,Ut as PropertyHierarchyCycleRule,ft as PropertyMetadata,qt as PropertyRangeReferenceRule,Vt as PropertyRangeRequiredRule,Lt as PropertyTypeSpecificityRule,Qt as PropertyValueTypeRule,Ne as PublisherConfigResolver,Oe as PublisherIndex,lt as RDFS_RULES,pt as Reasoner,ut as ReasoningResult,D as ReferenceKanonak,V as ReferenceStatement,De as RepositoryFactory,jt as ResourceNamingRule,Je as ResourceResolver,ot as ResourceTypeClassifier,Ge as ScalarStatement,ze as Statement,O as StringStatement,Ht as SubClassOfReferenceRule,Mt as SubPropertyOfReferenceRule,L as SubjectKanonak,Ft as SubjectKanonakTypeRequiredRule,ct as TripleStore,qe as TypeResolver,Ot as UnresolvedReferenceRule,Bt as ValidationCache,It as ValidationContext,Et as ValidationSeverity,yo as VersionOperator,Wt as XsdImportRule,He as buildLocalFirstRepository,q as canonicalForm,ge as canonicalHash,Ve as collectKanonakFiles,Pe as compareVersions,ye as computeIntegrity,xt as contextTypesOf,de as createAuthenticatedFetch,k as createDPoPProof,xe as createVersion,rt as extractMarkdownLinks,nr as findDerivation,$t as findInstancesByType,tt as findMalformedReferences,ht as findMarkdownLinkAt,St 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,Xe as makeUriKey,i as normalizeHost,bt as parseKanonakAddress,$e as parseVersionString,gt as parseWithPositions,Ke as pickHighestDocument,Rt as propertiesInScope,or as resolveDisplayValue,wt as resolvePropertyStep,fe as saveLockFile,le as serverSupportsDPoP,Pt as subjectUri,Ze as tripleKey,Ye as uriKey,Qe as uriTriple,Re as versionsEqual};
@@ -568,9 +568,17 @@ export declare class LookRenderer {
568
568
  private urlForReference;
569
569
  /** Look up the `look.urlForm` annotation on a property, defaulting to `=`. */
570
570
  private getUrlFormForProperty;
571
- /** Look up rdfs.label of a resource by URI. */
571
+ /**
572
+ * The display label of a resource by URI — resolved through the
573
+ * `look.displayLabel` lens (class-declarable, default rdfs.label), not
574
+ * hardcoded to rdfs.label. Returns undefined only when no resource with
575
+ * the URI is in the catalog.
576
+ */
572
577
  private readLabelForUri;
573
- /** Look up rdfs.comment of a resource by URI. */
578
+ /**
579
+ * The display summary of a resource by URI — resolved through the
580
+ * `look.displaySummary` lens (class-declarable, default rdfs.comment).
581
+ */
574
582
  private readCommentForUri;
575
583
  }
576
584
  export {};
@@ -0,0 +1,27 @@
1
+ import type { Kanonak } from '../kanonaks/Kanonak.js';
2
+ import type { SubjectKanonak } from '../kanonaks/SubjectKanonak.js';
3
+ export interface DisplayValue {
4
+ /** The resource's display name. Never empty — falls back to the local name. */
5
+ label: string;
6
+ /** The resource's one-line summary, or undefined when none is set. */
7
+ summary: string | undefined;
8
+ }
9
+ /**
10
+ * Resolve a resource's display label + summary through the
11
+ * `look.displayLabel` / `look.displaySummary` lens.
12
+ *
13
+ * The lens names WHICH property carries the resource's display text. It
14
+ * is resolved closest-wins across: the instance itself, then its type
15
+ * cascade (each type, then `subClassOf` ancestors), then the
16
+ * `rdfs.Resource` floor whose look default is `displayLabel → rdfs.label`
17
+ * and `displaySummary → rdfs.comment`. The named property is then read
18
+ * off the instance; the label falls back to the instance's local name so
19
+ * it is never empty.
20
+ *
21
+ * Single-hop: the lens value is read directly off the instance (a
22
+ * datatype property such as `rdfs.label` or a domain property like
23
+ * `teamName`). Built entirely on the canonical object-model helpers in
24
+ * `uri-helpers`; relies on built-in URIs already canonicalized at parse
25
+ * time (see KanonakVocabulary.canonicalizeBuiltinUri).
26
+ */
27
+ export declare function resolveDisplayValue(catalog: Kanonak[], instance: SubjectKanonak): DisplayValue;
@@ -1 +1,2 @@
1
1
  export { LookRenderer, type ResolvedLook } from './LookRenderer.js';
2
+ export { resolveDisplayValue, type DisplayValue } from './displayValue.js';
@@ -5,6 +5,12 @@ import type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
5
5
  export declare class KanonakObjectParser implements IKanonakObjectParser {
6
6
  constructor(_kanonakParser?: IKanonakParser);
7
7
  parseKanonaks(documentRepository: IKanonakDocumentRepository): Promise<Kanonak[]>;
8
+ /**
9
+ * Walk a statement list, canonicalizing built-in URIs on every
10
+ * predicate and reference target (recursing into embeddeds and list
11
+ * items). See BuiltinVocabulary.canonicalizeBuiltinUri.
12
+ */
13
+ private canonicalizeStatementBuiltins;
8
14
  /**
9
15
  * Determine the canonical (namespace, name) for an entity name as
10
16
  * authored in `document.body`. Aliased entity names like
@@ -1 +1 @@
1
- import{a as c,b as d,c as e,d as f}from"../chunk-NIJV5UYW.js";import{f as b}from"../chunk-FMYLEPMC.js";import"../chunk-W6T7MOKY.js";import{a}from"../chunk-7CUTGGH3.js";import"../chunk-HEMBMX7T.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-GR5IXWKN.js";import{f as b}from"../chunk-GYKITV44.js";import{a}from"../chunk-7CUTGGH3.js";import"../chunk-64TVBQFR.js";import"../chunk-W6T7MOKY.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,15 +1,32 @@
1
+ import type { KanonakUri } from '../resolution/KanonakUri.js';
1
2
  import type { Vocabulary } from './Vocabulary.js';
2
3
  /**
3
- * Default `Vocabulary` for the Kanonak ontology.
4
+ * Canonicalize a built-in URI in place against {@link BUILTIN_HOMES}.
4
5
  *
5
- * Binds the W3C semantic roles to the URIs published in
6
- * `kanonak.org/core-rdf` (RDF + RDFS terms) and
7
- * `kanonak.org/core-owl` (OWL 2 terms).
6
+ * Structural terms are stamped unconditionally. Other built-ins
7
+ * (`Class`, `ObjectProperty`, `Thing`, `Package`, ...) are stamped to
8
+ * their core home UNLESS a real local resource genuinely defines that
9
+ * name — an under-imported reference does not arrive with an empty
10
+ * publisher; the resolver falls back to the document's own namespace
11
+ * (e.g. `acme.com/widgets/Thing`). The reliable signal that this is a
12
+ * dangling built-in reference rather than a legitimate local class is
13
+ * that no resource with that URI exists in the catalog;
14
+ * `isDefinedLocally` supplies that check. Stamping a URI already at its
15
+ * core home is idempotent, so correctly-resolved built-ins are
16
+ * unaffected whether or not the check is provided.
8
17
  *
9
- * URIs are version-stripped; the reasoner matches identity by
10
- * `{publisher}/{package}/{name}` so any compatible release of the
11
- * core ontologies (e.g. a future `core-owl@2.1.0`) is recognised
12
- * without a code change here.
18
+ * No-op for non-built-in names.
19
+ */
20
+ export declare function canonicalizeBuiltinUri(uri: KanonakUri | undefined | null, isDefinedLocally?: (uri: KanonakUri) => boolean): void;
21
+ /**
22
+ * Default `Vocabulary` for the Kanonak ontology — binds the W3C
23
+ * semantic roles to the URIs published in `kanonak.org/core-rdf`
24
+ * (RDF + RDFS terms) and `kanonak.org/core-owl` (OWL 2 terms).
25
+ *
26
+ * URIs are version-stripped; identity is matched by
27
+ * `{publisher}/{package}/{name}` so any compatible release of the core
28
+ * ontologies is recognised without a code change here. The built-in
29
+ * homes above and these role bindings share one set of constants.
13
30
  */
14
31
  export declare class KanonakVocabulary implements Vocabulary {
15
32
  readonly type: string;
@@ -17,10 +34,20 @@ export declare class KanonakVocabulary implements Vocabulary {
17
34
  readonly subPropertyOf: string;
18
35
  readonly domain: string;
19
36
  readonly range: string;
37
+ readonly label: string;
38
+ readonly comment: string;
39
+ readonly resource: string;
40
+ readonly class_: string;
41
+ readonly datatype: string;
42
+ readonly literal: string;
20
43
  readonly equivalentClass: string;
21
44
  readonly equivalentProperty: string;
22
45
  readonly inverseOf: string;
23
46
  readonly sameAs: string;
24
47
  readonly transitiveProperty: string;
25
48
  readonly symmetricProperty: string;
49
+ readonly objectProperty: string;
50
+ readonly datatypeProperty: string;
51
+ readonly annotationProperty: string;
52
+ readonly package_: string;
26
53
  }
@@ -22,7 +22,7 @@ export { Reasoner } from './Reasoner.js';
22
22
  export type { ReasonerOptions, ReasoningProfile } from './Reasoner.js';
23
23
  export { ReasoningResult } from './ReasoningResult.js';
24
24
  export { TripleStore } from './TripleStore.js';
25
- export { KanonakVocabulary } from './KanonakVocabulary.js';
25
+ export { KanonakVocabulary, canonicalizeBuiltinUri } from './KanonakVocabulary.js';
26
26
  export type { Vocabulary } from './Vocabulary.js';
27
27
  export type { Triple, TripleObject, UriKey } from './Triple.js';
28
28
  export { uriKey, makeUriKey, tripleKey, uriTriple } from './Triple.js';
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j}from"../chunk-IOJMTW4T.js";import"../chunk-FMYLEPMC.js";import"../chunk-W6T7MOKY.js";import"../chunk-7CUTGGH3.js";import"../chunk-HEMBMX7T.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 as g,b as h,c as i,d as j,e as k}from"../chunk-2CLFEFQP.js";import"../chunk-GYKITV44.js";import"../chunk-7CUTGGH3.js";import{d as a,e as b,f as c,h as d,i as e,j as f}from"../chunk-64TVBQFR.js";import"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";export{f as KanonakVocabulary,i as OWL_RL_CLASSIFICATION_RULES,h as RDFS_RULES,k as Reasoner,j as ReasoningResult,g as TripleStore,e as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
@@ -0,0 +1,28 @@
1
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
+ import type { KanonakDocument, Import, DocumentReference } from '@kanonak-protocol/types/document/models/types';
3
+ /**
4
+ * A repository that tries several backends in order. For read operations the
5
+ * first backend to return a value wins; writes go to the first backend.
6
+ *
7
+ * The canonical stack is workspace → global cache → HTTP (see
8
+ * `buildLocalFirstRepository`). Document ORDER is significant: open-world
9
+ * augmentations (e.g. a publisher look re-opening `rdfs.Resource`) merge in
10
+ * the order documents are returned, so the workspace must precede the cache
11
+ * for renders to match what the workspace authored. Use this rather than
12
+ * `CompositeKanonakDocumentRepository` (cache-first, no HTTP tier) when that
13
+ * ordering matters — notably anything that renders via `LookRenderer`.
14
+ */
15
+ export declare class LocalFirstRepository implements IKanonakDocumentRepository {
16
+ private readonly repos;
17
+ constructor(...repos: IKanonakDocumentRepository[]);
18
+ getHighestCompatibleVersionAsync(publisher: string, import_: Import): Promise<KanonakDocument | null>;
19
+ getAllDocumentsAsync(): Promise<KanonakDocument[]>;
20
+ getDocumentAsync(identifier: string): Promise<KanonakDocument | null>;
21
+ getDocumentsByNamespaceAsync(publisher: string, package_: string): Promise<KanonakDocument[]>;
22
+ saveDocumentAsync(document: KanonakDocument, identifier: string): Promise<void>;
23
+ deleteDocumentAsync(identifier: string): Promise<void>;
24
+ clearNamespaceAsync(publisher: string, package_: string): Promise<void>;
25
+ getAllDocumentReferencesAsync(): Promise<DocumentReference[]>;
26
+ getDocumentContentAsync(identifier: string): Promise<string | null>;
27
+ getDocumentUriAsync(identifier: string): Promise<string | null>;
28
+ }