@kanonak-protocol/sdk 4.13.0 → 4.15.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 (60) hide show
  1. package/dist/browser.d.ts +1 -1
  2. package/dist/browser.js +2 -2
  3. package/dist/chunk-6U26UASC.js +1 -0
  4. package/dist/chunk-7BHDZHJY.js +1 -0
  5. package/dist/{chunk-VWS25JH4.js → chunk-EZSHR3CB.js} +1 -1
  6. package/dist/chunk-GZPLWII7.js +1 -0
  7. package/dist/{chunk-V72IVYR4.js → chunk-IHB7UVEH.js} +4 -4
  8. package/dist/chunk-MX3DEXMV.js +1 -0
  9. package/dist/{chunk-RGOBWOBB.js → chunk-S6VSAKXB.js} +1 -1
  10. package/dist/{chunk-CR55WXIN.js → chunk-TVSHIXLA.js} +1 -1
  11. package/dist/chunk-VZNNI2VR.js +2 -0
  12. package/dist/chunk-WFQANMBQ.js +1 -0
  13. package/dist/chunk-ZO5IUMX6.js +63 -0
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +12 -12
  16. package/dist/kanonaks/DefinedKanonak.d.ts +12 -0
  17. package/dist/parsing/KanonakObjectParser.d.ts +14 -1
  18. package/dist/parsing/index.js +1 -1
  19. package/dist/reasoning/KanonakVocabulary.d.ts +11 -0
  20. package/dist/reasoning/index.js +1 -1
  21. package/dist/resolution/ResourceResolver.d.ts +0 -4
  22. package/dist/resolution/index.js +1 -1
  23. package/dist/search/index.js +1 -1
  24. package/dist/server/index.js +1 -1
  25. package/dist/transformations/index.js +1 -1
  26. package/dist/uri-helpers/index.js +1 -1
  27. package/dist/validation/OntologyValidationResult.d.ts +12 -0
  28. package/dist/validation/ValidationCache.d.ts +34 -76
  29. package/dist/validation/ValidationSeverity.d.ts +7 -0
  30. package/dist/validation/documentModel.d.ts +47 -1
  31. package/dist/validation/index.d.ts +1 -1
  32. package/dist/validation/index.js +1 -1
  33. package/dist/validation/rules/repository/ClassDefinitionRule.d.ts +21 -6
  34. package/dist/validation/rules/repository/ClassHierarchyCycleRule.d.ts +9 -4
  35. package/dist/validation/rules/repository/EmbeddedKanonakTypeRule.d.ts +29 -90
  36. package/dist/validation/rules/repository/ObjectPropertyValueValidationRule.d.ts +20 -6
  37. package/dist/validation/rules/repository/PropertyDomainRule.d.ts +21 -17
  38. package/dist/validation/rules/repository/PropertyHierarchyCycleRule.d.ts +8 -4
  39. package/dist/validation/rules/repository/PropertyKindRangeConsistencyRule.d.ts +29 -0
  40. package/dist/validation/rules/repository/PropertyRangeReferenceRule.d.ts +14 -7
  41. package/dist/validation/rules/repository/PropertyRangeRequiredRule.d.ts +13 -2
  42. package/dist/validation/rules/repository/ReservedNameShadowRule.d.ts +24 -0
  43. package/dist/validation/rules/repository/SubClassOfReferenceRule.d.ts +16 -13
  44. package/dist/validation/rules/repository/SubPropertyOfReferenceRule.d.ts +12 -5
  45. package/dist/validation/rules/repository/UnresolvedReferenceRule.d.ts +16 -4
  46. package/dist/validation/rules/repository/hierarchyCycle.d.ts +25 -0
  47. package/dist/validation/rules/repository/index.d.ts +2 -4
  48. package/package.json +2 -2
  49. package/dist/chunk-4UT2CLAT.js +0 -1
  50. package/dist/chunk-7HRKWTBB.js +0 -1
  51. package/dist/chunk-7TKJHKC2.js +0 -1
  52. package/dist/chunk-BKVPSPG4.js +0 -1
  53. package/dist/chunk-IEOSSSB5.js +0 -1
  54. package/dist/chunk-NUXUITUC.js +0 -2
  55. package/dist/chunk-SHDHMKMJ.js +0 -1
  56. package/dist/chunk-UBBZWWRB.js +0 -86
  57. package/dist/validation/rules/repository/DefinitionPropertyReferenceRule.d.ts +0 -13
  58. package/dist/validation/rules/repository/ObjectPropertyImportRule.d.ts +0 -9
  59. package/dist/validation/rules/repository/PropertyValueTypeRule.d.ts +0 -11
  60. package/dist/validation/rules/repository/XsdImportRule.d.ts +0 -11
@@ -0,0 +1 @@
1
+ import{j as d}from"./chunk-GZPLWII7.js";import{c as U,d as S,m as u,r as _,v as m,w as g,y as j}from"./chunk-7BHDZHJY.js";import{a as b}from"./chunk-FUUTGGJS.js";var $=new Set(["kanonak.org/core-rdf","kanonak.org/core-owl","kanonak.org/core-xsd","kanonak.org/core-kanonak"]);function i(r){let n=r;if(n.entity&&typeof n.entity=="object"){let e=n.entity.type;if(typeof e=="string"){let a={publisher:"",package_:"",name:e.includes(".")?e.substring(e.lastIndexOf(".")+1):e};return d(a),{publisher:a.publisher,package_:a.package_,name:a.name}}}if(n.statement&&Array.isArray(n.statement)){for(let e of n.statement)if(e.predicate?.subject?.name==="type"&&e.object?.subject){let t=e.object.subject,a={publisher:t.publisher??"",package_:t.package_??"",name:t.name};return d(a),{publisher:a.publisher,package_:a.package_,name:a.name}}}return null}function c(r,n){return $.has(`${r}/${n}`)}var y=class r{static getTypeUri(n){return i(n)}static isCoreOntologyType(n){return c(n.publisher,n.package_)}static isClassType(n){let e=i(n);return e?c(e.publisher,e.package_)&&e.name==="Class":!1}static isDatatypeType(n){let e=i(n);return e?c(e.publisher,e.package_)&&e.name==="Datatype":!1}static isDatatypePropertyType(n){let e=i(n);return e?c(e.publisher,e.package_)&&e.name==="DatatypeProperty":!1}static isObjectPropertyType(n){let e=i(n);return e?c(e.publisher,e.package_)&&e.name==="ObjectProperty":!1}static isAnnotationPropertyType(n){let e=i(n);return e?c(e.publisher,e.package_)&&e.name==="AnnotationProperty":!1}static isGenericPropertyType(n){let e=i(n);return e?c(e.publisher,e.package_)&&e.name==="Property":!1}static isAnyPropertyType(n){let e=i(n);return!e||!c(e.publisher,e.package_)?!1:e.name==="Property"||e.name==="DatatypeProperty"||e.name==="ObjectProperty"||e.name==="AnnotationProperty"}static isSchemaDefinitionType(n){let e=i(n);return!e||!c(e.publisher,e.package_)?!1:e.name==="Class"||e.name==="Property"||e.name==="DatatypeProperty"||e.name==="ObjectProperty"||e.name==="AnnotationProperty"||e.name==="Datatype"}static isInstanceOfKnownClass(n,e){if(r.isSchemaDefinitionType(n))return!1;let t=i(n);return t?e.has(t.name):!1}};function P(r){if(!r||r.trim().length===0)throw new Error("Kanonak address string cannot be null or empty");let n=r.trim(),e=n.split("/");if(e.length===1){let t=e[0];if(!t)throw new Error(`Invalid Kanonak address: "${r}". Expected publisher, publisher/package[@version], or publisher/package[@version]/name.`);if(t.includes("@"))throw new Error(`Invalid Kanonak address: "${r}". A bare publisher cannot carry an @version qualifier \u2014 versions belong to packages.`);return{kind:"publisher",publisher:t}}if(e.length===2){let[t,a]=e;if(!t||!a)throw new Error(`Invalid Kanonak address: "${r}". Expected publisher/package[@version].`);let o=a.indexOf("@");if(o===-1)return{kind:"package",publisher:t,package_:a};let s=a.substring(0,o),p=a.substring(o+1);if(!s||!p)throw new Error(`Invalid Kanonak address: "${r}". Expected publisher/package[@version].`);let f=A(p);return{kind:"package",publisher:t,package_:s,version:f}}return{kind:"resource",uri:b.parse(n)}}function G(r){switch(r.kind){case"publisher":return r.publisher;case"package":return r.version?`${r.publisher}/${r.package_}@${r.version.major}.${r.version.minor}.${r.version.patch}`:`${r.publisher}/${r.package_}`;case"resource":return r.uri.toString()}}function A(r){let n=r.split(".").map(Number);return w(n[0]||0,n[1]||0,n[2]||0)}function w(r,n,e){return{major:r,minor:n,patch:e,toString:()=>`${r}.${n}.${e}`,equals:t=>!t||typeof t!="object"?!1:t.major===r&&t.minor===n&&t.patch===e,getHashCode:()=>r<<20|n<<10|e,compareTo:t=>r!==t.major?r-t.major:n!==t.minor?n-t.minor:e-t.patch}}var k="kanonak.org",l="core-rdf",T={publisher:k,package_:l,name:"domain"},C={publisher:k,package_:l,name:"range"},R={publisher:k,package_:l,name:"subClassOf"},v={publisher:k,package_:l,name:"type"},x={publisher:k,package_:l,name:"label"},D={publisher:k,package_:l,name:"comment"},O=new b(k,l,"Resource"),I=r=>r;function V(r){try{let n=P(`${r.namespace}/${r.name}`);return n.kind==="resource"?n.uri:void 0}catch{return}}function h(r,n){let e=g(r,n);if(e)return[e];let t=[];for(let a of j(r,n))a instanceof S&&t.push(a.subject);return t}function N(r,n){let e=[],t=new Set,a=[new b(n.publisher,n.package_,n.name)];for(;a.length>0;){let o=a.shift(),s=u(o);if(t.has(s))continue;t.add(s),e.push(o);let p=_(r,o);p&&a.push(...h(p,R))}return e}function B(r,n){let e=new Set([u(O)]);for(let t of N(r,n))e.add(u(t));return e}function F(r,n){let e=B(r,n),t=[],a=new Set;for(let o of r){if(!(o instanceof U))continue;let s=I(o);if(!y.isAnyPropertyType(s))continue;let p=h(o,T);if(!p.some(E=>e.has(u(E))))continue;let f=V(o);if(!f)continue;let K=u(f);a.has(K)||(a.add(K),t.push({uri:f,label:m(o,x),comment:m(o,D),kind:y.isObjectPropertyType(s)?"object":y.isDatatypePropertyType(s)?"datatype":"other",range:g(o,C),domains:p}))}return t}function Z(r,n,e){let t=F(r,n).find(a=>u(a.uri)===u(e));return t?{ok:!0,descriptor:t}:{ok:!1,message:`Property ${e.publisher}/${e.package_}/${e.name} is not in scope for ${n.publisher}/${n.package_}/${n.name}.`}}function ee(r){return h(r,v)}export{y as a,P as b,G as c,V as d,N as e,F as f,Z as g,ee as h};
@@ -0,0 +1,63 @@
1
+ import{a as v,b as Me,c as it,g as M,j as ct,l as S}from"./chunk-MX3DEXMV.js";import{a as rt}from"./chunk-NJ3AZYQD.js";import{a as y,d as A,e as Y,f as pt,g as L,h as lt}from"./chunk-WFQANMBQ.js";import{a as G}from"./chunk-6U26UASC.js";import{h as Fe,i as st}from"./chunk-GZPLWII7.js";import{c as d,d as I,j as Be,k as H,l as F,m as K,n as z,p as P,r as h,t as J,u as x,v as W,w as g,x as O,y as V}from"./chunk-7BHDZHJY.js";import{a as at}from"./chunk-FUUTGGJS.js";import{e as U}from"./chunk-2ACBWC7K.js";var Q=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var k=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(k||{});var u=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 ze=class c{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new c;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ee=class{constructor(e){this.underlying=e;this.repository=new Xe(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e={};return{merged:await new S().parseKanonaks(this.underlying,e),authored:e.authored??[]}})()),this.parsePromise}},Xe=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,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}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)}};async function D(c,e,t){return t?t.getKanonaks():new S().parseKanonaks(new te(c,e))}async function C(c,e,t){let o=await D(c,e,t),n=We(c);return n?o.filter(r=>r instanceof d&&r.namespace===n):[]}async function oe(c,e,t){let o=We(c);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new S().parseKanonaks(new te(c,e),r),n=r.authored??[]}return n.filter(r=>r instanceof d&&r.sourceDoc===o)}function q(c,e){for(let t of c)t instanceof d&&Ze(t,t.name,e)}function Ze(c,e,t){t({kanonak:c,path:e});for(let o of c.statement)if(o instanceof H)Ze(o.object,mt(e,o.object),t);else if(o instanceof F)for(let n of o.object)n instanceof v&&Ze(n,mt(e,n),t)}function mt(c,e){let t=e instanceof v&&e.name?e.name:"<embedded>";return`${c}/${t}`}function We(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var te=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var ne=class c{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&c.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),s=e.split(".")[0],p=new u;p.ruleType=this.ruleName,p.severity="Error",p.entityName=s,p.propertyName=e,p.actualValue=n,p.expectedValue=i,p.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(p)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var re=class c{static RESERVED_WORDS=new Set(["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 t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=c.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&c.RESERVED_WORDS.has(n.toLowerCase())){let i=new u;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!c.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new u;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Invalid entity name '${n}'. ${i}`,s.suggestion=i,t.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!c.VALID_PROPERTIES.has(n)&&!c.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new u;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var ae=class c{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let s=[];if(Array.isArray(i))for(let p of i){let l=p?.toString();l&&l==="Property"&&!o&&s.push(l)}else{let p=i?.toString();p&&p==="Property"&&!o&&s.push(p)}for(let p of s){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),f=new u;f.ruleType=this.ruleName,f.severity="Error",f.entityName=n,f.propertyName="type",f.actualValue=p,f.expectedValue=m,f.message=`Invalid property type '${p}'. Use '${m}' instead.`,f.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(f)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":c.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ie=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let s=new u;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.propertyName="type",s.message=`Subject Kanonak '${o}' must have a 'type' property.`,s.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.`,s.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(s)}}return t}};var Ut=new Set(["EphemeralPackage"]),se=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let o=[],n=this.packageKey(e,t.type_);return t.namespace_?(!Ut.has(t.type_)&&!t.namespace_.version&&o.push(this.error(n,"version",`Package resource '${n}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
5
+ version: 1.0.0`)),o):(o.push(this.error(n,"publisher",`Package resource '${n}' requires a 'publisher' property.`,`Add a publisher, e.g.:
6
+ publisher: example.org`)),o)}packageKey(e,t){for(let[o,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type===t)return o;return t}error(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.message=o,r.suggestion=n,r}};var At={publisher:"kanonak.org",package_:"core-rdf",name:"type"},wt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},xt={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Tt={publisher:"kanonak.org",package_:"core-rdf",name:"Class"},ce=class{ruleName="EmbeddedKanonakType";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof H){let a=r.predicate?.subject,i=`${o}.${a?.name??"<embedded>"}`;this.check(e,a,r.object,o,i,n),this.walk(e,r.object,i,n)}else if(r instanceof F){let a=r.predicate?.subject,i=0;for(let s of r.object){if(s instanceof v){let p=`${o}.${a?.name??"<embedded>"}[${i}]`;this.check(e,a,s,o,p,n),this.walk(e,s,p,n)}i++}}}check(e,t,o,n,r,a){if(!t)return;let i=g(o,At);if(!i)return;let s=h(e,t);if(!s)return;let p=g(s,wt);if(p&&!(z(p,xt)||z(p,Tt))){if(K(i)===K(p)){a.push(this.redundant(n,r,i,p));return}Y(e,i).some(l=>K(l)===K(p))||a.push(this.notSubclass(n,r,i,p))}}redundant(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' declares 'type: ${o.name}', which equals the parent property's range '${n.name}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,r.suggestion=`Remove the 'type: ${o.name}' line, or keep it if explicitness is preferred over concision.`,r}notSubclass(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' has 'type: ${o.name}', which is not a subclass of the parent property's range '${n.name}'.`,r.suggestion=`Either remove the 'type: ${o.name}' line (so the type is inferred from the property's range '${n.name}'), or add 'subClassOf: ${n.name}' to the '${o.name}' class definition so the relationship holds.`,r}};import{VersionOperator as He}from"@kanonak-protocol/types/document/models/enums";var pe=class{ruleName="ImportExistence";async validateAsync(e,t){let o=[];if(!e.metadata?.imports)return o;let n=await t.getAllDocumentsAsync();for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a)if(!await t.getHighestCompatibleVersionAsync(r,i)){let p=await this.determineImportErrorAsync(t,r,i,n),l=new u;l.ruleType=this.ruleName,l.severity="Error",l.message=p.message,l.suggestion=p.suggestion,l.entityName=`Import: ${r}/${i.packageName}`,l.actualValue=i.toString(),l.expectedValue=p.expectedValue,o.push(l)}return o}async determineImportErrorAsync(e,t,o,n){let r=await e.getDocumentsByNamespaceAsync(t,o.packageName);if(r.length===0){let p=n.filter(R=>R.metadata.namespace_?.publisher===t).map(R=>R.metadata.namespace_.package_).filter((R,E,N)=>N.indexOf(R)===E),l=this.findSimilarPackages(o.packageName,p),m=`Import '${t}/${o.package_}' not found - package does not exist`,f=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:p.length>0?`Available packages in ${t}: ${p.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:m,suggestion:f,expectedValue:"Existing package"}}let i=r.filter(p=>p.metadata.namespace_?.version).map(p=>p.metadata.namespace_.version.toString()).sort().join(", "),s=this.getAcceptableVersionRange(o);return{message:`Import '${t}/${o.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${i}. Required: ${s}`,expectedValue:s}}getAcceptableVersionRange(e){switch(e.versionOperator){case He.Exact:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case He.Compatible:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case He.Major:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case He.Any:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let o=t.filter(a=>a.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(a.toLowerCase()));if(o.length>0)return o.sort((a,i)=>a.length-i.length);let n=t.map(a=>({package:a,distance:this.levenshteinDistance(e.toLowerCase(),a.toLowerCase())})).sort((a,i)=>a.distance-i.distance),r=Math.max(3,Math.floor(e.length*.4));return n.filter(a=>a.distance<=r).map(a=>a.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let o=e.length,n=t.length,r=Array(o+1).fill(null).map(()=>Array(n+1).fill(0));for(let a=0;a<=o;a++)r[a][0]=a;for(let a=0;a<=n;a++)r[0][a]=a;for(let a=1;a<=o;a++)for(let i=1;i<=n;i++){let s=e[a-1]===t[i-1]?0:1;r[a][i]=Math.min(Math.min(r[a-1][i]+1,r[a][i-1]+1),r[a-1][i-1]+s)}return r[o][n]}};var Nt="kanonak.org",_t="core-rdf",Lt=new Set(["type","subClassOf","subPropertyOf","domain","range"].map(c=>K({publisher:Nt,package_:_t,name:c}))),le=class{ruleName="UnresolvedReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of i.statement){let l=Mt(p);if(!(!l||Lt.has(K(l)))){if(p instanceof Be)this.check(r,s,l,p.object,n);else if(p instanceof F)for(let m of p.object)m instanceof I&&this.check(r,s,l,m,n)}}}),n}check(e,t,o,n,r){h(e,n.subject)||r.push(this.unresolvedError(t,o.name,n.subject))}unresolvedError(e,t,o){let n=`${o.publisher}/${o.package_}/${o.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=n,r.expectedValue="A reference that resolves to a defined or imported resource",r.message=`Reference to '${o.name}' in '${t}' could not be resolved`,r.suggestion=`The entity '${n}' is not defined in this namespace or any imported namespace.
7
+ \u2022 Import the package that defines it, or check for a typo in '${o.name}'
8
+ \u2022 If it lives in an imported namespace, alias-qualify the reference`,r}};function Mt(c){return c.predicate?.subject}var ut={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},ft={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"};function Bt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}function Ge(c,e,t){let o=[],n=new Set,r=new Set,a=i=>{let s=h(c,i),p=s?`${s.namespace}/${s.name}`:K(i);if(n.has(p)){let l=o.findIndex(f=>f.key===p),m=o.slice(l);return m.length<=1?null:[...m.map(f=>f.uri),i]}if(r.has(p))return null;if(n.add(p),o.push({key:p,uri:i}),s)for(let l of Bt(s,t)){let m=a(l);if(m)return m}return o.pop(),n.delete(p),r.add(p),null};return a(e)}var dt=c=>c,me=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!(y.isClassType(dt(i))||y.isDatatypeType(dt(i))))continue;let s=A(i);if(!s)continue;let p=Ge(r,s,ut);if(p){let l=p.map(f=>f.name).join(" \u2192 "),m=new u;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=i.name,m.propertyName="subClassOf",m.actualValue=l,n.push(m);break}}return n}};var Ft=c=>c,ue=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!y.isAnyPropertyType(Ft(i)))continue;let s=A(i);if(!s)continue;let p=Ge(r,s,ft);if(p){let l=p.map(f=>f.name).join(" \u2192 "),m=new u;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=i.name,m.propertyName="subPropertyOf",m.actualValue=l,n.push(m);break}}return n}};var Wt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},yt=c=>c,fe=class{ruleName="PropertyRangeRequired";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);for(let a of r){if(!(a instanceof d))continue;let i=y.isObjectPropertyType(yt(a));!i&&!y.isDatatypePropertyType(yt(a))||J(a,Wt)||n.push(this.error(a.name,i))}return n}error(e,t){let o=new u;return o.ruleType=this.ruleName,o.severity="Error",o.entityName=e,o.propertyName="range",o.message=`Property '${e}' must have a 'range' defined.`,o.suggestion=t?"Add a range like: range: ClassName (the class this property expects)":"Add a range like: range: string (or integer, boolean, etc.)",o.expectedValue=t?"A class name (Character, Scene, Story, etc.)":"A datatype (string, integer, boolean, decimal, etc.)",o}};var Ht={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},gt=c=>c,de=class{ruleName="SubClassOfReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!kt(gt(i)))continue;let s=Gt(i,Ht);for(let p=0;p<s.length;p++)this.resolvesToClassLike(r,s[p])||n.push(this.error(i.name,s[p],s.length>1?`[${p}]`:""))}return n}resolvesToClassLike(e,t){let o=h(e,t);return o?kt(gt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subClassOf",r.actualValue=n,r.expectedValue="Defined or imported class",r.message=`Class '${t.name}' referenced in subClassOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a Class, or import a namespace that contains it`,r}};function kt(c){return y.isClassType(c)||y.isDatatypeType(c)}function Gt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Yt={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"},ht=c=>c,ye=class{ruleName="SubPropertyOfReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!y.isAnyPropertyType(ht(i)))continue;let s=qt(i,Yt);for(let p=0;p<s.length;p++)this.resolvesToProperty(r,s[p])||n.push(this.error(i.name,s[p],s.length>1?`[${p}]`:""))}return n}resolvesToProperty(e,t){let o=h(e,t);return o?y.isAnyPropertyType(ht(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subPropertyOf",r.actualValue=n,r.expectedValue="Defined or imported property",r.message=`Property '${t.name}' referenced in subPropertyOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a property, or import a namespace that contains it`,r}};function qt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var ge=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let o=[],n=e.metadata.namespace_?.toString();if(!n)return o;let r=new Map,a=new Set;await this.buildImportGraph(e,t,r,a);let i=this.detectCycle(n,r);if(i){let s=i.join(" \u2192 "),p=new u;p.ruleType=this.ruleName,p.severity="Error",p.message=`Circular namespace import detected: ${s}`,p.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",p.entityName="imports",p.propertyName="imports",p.actualValue=s,o.push(p)}return o}async buildImportGraph(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!(!r||n.has(r))&&(n.add(r),e.metadata.imports)){let a=[];for(let[i,s]of Object.entries(e.metadata.imports))for(let p of s){let l=`${i}/${p.packageName}@${p.version}`;a.push(l);let m=await t.getHighestCompatibleVersionAsync(i,p);m&&await this.buildImportGraph(m,t,o,n)}a.length>0&&o.set(r,a)}}detectCycle(e,t){let o=[],n=new Set;return this.detectCycleRecursive(e,t,o,n)}detectCycleRecursive(e,t,o,n){let r=o.indexOf(e);if(r>=0){let i=o.slice(r);return i.push(e),i}if(n.has(e))return null;o.push(e),n.add(e);let a=t.get(e);if(a)for(let i of a){let s=this.detectCycleRecursive(i,t,o,n);if(s)return s}return o.pop(),null}};var ke=class{ruleName="UnresolvedPredicate";async validateAsync(e,t,o){let n=[],r=We(e);if(!r)return n;let a=await D(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of i.unresolvedPredicates)p.sourceDoc===r&&n.push(this.unresolvedPredicateError(s,p.key))}),n}unresolvedPredicateError(e,t){let o=t.lastIndexOf("."),n=o>0?t.slice(0,o):null,r=o>0?t.slice(o+1):t,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=t,a.expectedValue="A defined or imported property",a.message=`Property '${t}' is not defined or imported`,a.suggestion=n?`The property '${r}' was not found in the namespace imported as '${n}'.
9
+ 1. Check '${r}' is spelled correctly
10
+ 2. Verify '${n}' is imported with the right alias and version
11
+ 3. Ensure that namespace version actually defines '${r}'`:`The property '${t}' is not defined in this namespace or any imported namespace.
12
+ 1. Define '${t}' as an ObjectProperty or DatatypeProperty here, OR
13
+ 2. Import the namespace that defines it, OR
14
+ 3. Alias-qualify it if it lives in an imported namespace ('alias.${t}')`,a}};var he=class{get ruleName(){return"AmbiguousReference"}async validateAsync(e,t){let o=[],{entitySources:n,importPaths:r}=await this.buildEntitySourceMapAsync(e,t),a=await this.buildDatatypePropertyNamesAsync(e,t);for(let[i,s]of Object.entries(e.body))typeof s=="object"&&s!==null&&!Array.isArray(s)&&this.validateEntityReferences(i,s,n,r,a,e,o);return o}async buildEntitySourceMapAsync(e,t){let o=new Map,n=new Set,r=new Map;for(let a of Object.keys(e.body)){let i=e.metadata.namespace_?.toString()??"";o.has(a)||o.set(a,[]),o.get(a).push(`(local:${i})`)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let s of i){let p=await t.getHighestCompatibleVersionAsync(a,s);if(p){let l=p.metadata.namespace_?.toString()??"";await this.collectEntitiesRecursivelyAsync(p,o,n,r,[l],t)}}return{entitySources:o,importPaths:r}}async collectEntitiesRecursivelyAsync(e,t,o,n,r,a){let i=e.metadata.namespace_?.toString()??"";if(!o.has(i)){o.add(i),n.has(i)||n.set(i,r);for(let s of Object.keys(e.body)){t.has(s)||t.set(s,[]);let p=t.get(s);p.includes(i)||p.push(i)}if(e.metadata.imports)for(let[s,p]of Object.entries(e.metadata.imports))for(let l of p){let m=await a.getHighestCompatibleVersionAsync(s,l);if(m){let f=m.metadata.namespace_?.toString()??"";await this.collectEntitiesRecursivelyAsync(m,t,o,n,[...r,f],a)}}}}async buildDatatypePropertyNamesAsync(e,t){let o=new Set,n=new Set;if(await this.collectDatatypePropertiesAsync(e,o,n,t),e.metadata.imports)for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a){let s=await t.getHighestCompatibleVersionAsync(r,i);s&&await this.collectDatatypePropertiesAsync(s,o,n,t)}return o}async collectDatatypePropertiesAsync(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!o.has(r)){o.add(r);for(let[a,i]of Object.entries(e.body)){if(typeof i!="object"||i===null||Array.isArray(i))continue;let s=i.type;if(typeof s!="string")continue;(s.includes(".")?s.substring(s.lastIndexOf(".")+1):s)==="DatatypeProperty"&&t.add(a)}if(e.metadata.imports)for(let[a,i]of Object.entries(e.metadata.imports))for(let s of i){let p=await n.getHighestCompatibleVersionAsync(a,s);p&&await this.collectDatatypePropertiesAsync(p,t,o,n)}}}validateEntityReferences(e,t,o,n,r,a,i){for(let[s,p]of Object.entries(t)){let l=s;if(l&&!l.includes(".")){let m=o.get(l);if(m&&m.length>1&&!m.some(R=>R.startsWith("(local:"))){let R=m.filter(E=>!E.startsWith("(local:"));R.length>1&&i.push(this.createAmbiguityError(e,l,`Property '${l}'`,R,n,a,!0,l))}}this.validatePropertyValue(e,l,p,o,n,r,a,i)}}validatePropertyValue(e,t,o,n,r,a,i,s){if(o==null)return;let p=t&&t.includes(".")?t.substring(t.lastIndexOf(".")+1):t,l=!!p&&a.has(p);if(typeof o=="string"&&!o.includes(".")&&!l){let m=n.get(o);if(m&&m.length>1&&!m.some(R=>R.startsWith("(local:"))){let R=m.filter(E=>!E.startsWith("(local:"));R.length>1&&s.push(this.createAmbiguityError(e,t,`Reference '${o}'`,R,r,i,!1,o))}}else if(Array.isArray(o))for(let m=0;m<o.length;m++){let f=`${e}.${t}[${m}]`;this.validatePropertyValue(f,t,o[m],n,r,a,i,s)}else if(typeof o=="object"&&!Array.isArray(o)){let m=t?`${e}.${t}`:e;this.validateEntityReferences(m,o,n,r,a,i,s)}}createAmbiguityError(e,t,o,n,r,a,i,s){let p=[];for(let j of n){let $=this.findAliasForNamespace(a,j);if($){let B=t?.split(".").pop()??t;p.push(`${$}.${B}`)}}let l=p.length>0?`Use one of: ${p.map(j=>`'${j}'`).join(", ")}`:`Add aliases to imports and use qualified names (e.g., 'alias.${t}')`,m=n.map(j=>{let $=r.get(j);return!$||$.length===0?` \u2022 ${j}`:$.length===1?` \u2022 ${j} (direct import)`:` \u2022 ${j}
15
+ imported via: ${$.join(" \u2192 ")}`}).join(`
16
+ `),f=e.split(".")[0],R=e.includes(".")?e:t,E=new u;E.ruleType=this.ruleName,E.severity="Error",E.entityName=f,R&&(E.propertyName=R);let N=s??t;return N&&(E.actualValue=N),E.message=`${o} is ambiguous - defined in multiple imported namespaces`,E.suggestion=`${l}
17
+
18
+ Defined in:
19
+ ${m}`,E.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",E}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(`${o}/${r.packageName}@${r.version}`===t&&r.alias)return r.alias;return null}};var zt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ye=c=>c,Re=class{ruleName="PropertyRangeReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d))continue;let s=y.isObjectPropertyType(Ye(i));if(!(!s&&!y.isDatatypePropertyType(Ye(i))))for(let p of Xt(i,zt))this.resolvesToClassLike(r,p)||n.push(this.error(i.name,p,s))}return n}resolvesToClassLike(e,t){let o=h(e,t);return o?y.isClassType(Ye(o))||y.isDatatypeType(Ye(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="range",r.actualValue=n,r.expectedValue=o?"A defined or imported class":"A datatype or defined class",r.message=`Property '${e}' has range '${t.name}' which is not defined or imported`,r.suggestion=o?`Define '${t.name}' as a Class here, or import the namespace that contains it (alias-qualify it if imported under an alias).`:`Use a datatype (xsd type, rdfs.Literal, or a datatype-derived type), or \u2014 if '${t.name}' is a class \u2014 make this an ObjectProperty.`,r}};function Xt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Zt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ke="kanonak.org",Je="core-rdf",Qe="core-owl",Jt=c=>c,Qt=[{uri:{publisher:Ke,package_:Je,name:"Class"},ok:c=>y.isClassType(c)||y.isDatatypeType(c)},{uri:{publisher:Ke,package_:Je,name:"Datatype"},ok:c=>y.isDatatypeType(c)},{uri:{publisher:Ke,package_:Je,name:"Property"},ok:c=>y.isAnyPropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"ObjectProperty"},ok:c=>y.isObjectPropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"DatatypeProperty"},ok:c=>y.isDatatypePropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"AnnotationProperty"},ok:c=>y.isAnnotationPropertyType(c)}],be=class{ruleName="ObjectPropertyValue";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof Be)this.check(e,r.predicate?.subject,r.object.subject,o,n);else if(r instanceof H)this.walk(e,r.object,Rt(o,r.predicate?.subject),n);else if(r instanceof F){let a=r.predicate?.subject;for(let i of r.object)i instanceof I?this.check(e,a,i.subject,o,n):i instanceof v&&this.walk(e,i,Rt(o,a),n)}}check(e,t,o,n,r){if(!t)return;let a=h(e,t);if(!a)return;let i=g(a,Zt);if(!i)return;let s=Qt.find(l=>z(i,l.uri));if(!s)return;let p=h(e,o);p&&(s.ok(Jt(p))||r.push(this.warn(n,t,i,o)))}warn(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e.split(".")[0],r.propertyName=e,r.actualValue=n.name,r.expectedValue=o.name,r.message=`Property '${t.name}' expects a ${o.name}, but '${n.name}' is not a ${o.name}`,r.suggestion=`Reference a resource that is a ${o.name}, or correct the type of '${n.name}'.`,r}};function Rt(c,e){return`${c}.${e?.name??"<embedded>"}`}var eo={publisher:"kanonak.org",package_:"core-rdf",name:"type"},to={publisher:"kanonak.org",package_:"core-rdf",name:"domain"},oo={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Ve=class{ruleName="PropertyDomain";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){this.checkNode(e,t,o,n);for(let r of t.statement)if(r instanceof H)this.walk(e,r.object,bt(o,r.predicate?.subject),n);else if(r instanceof F)for(let a of r.object)a instanceof v&&this.walk(e,a,bt(o,r.predicate?.subject),n)}checkNode(e,t,o,n){let r=Kt(t,eo);if(r.length===0)return;let a,i=()=>{if(!a){a=new Set([K(oo)]);for(let p of r)for(let l of Y(e,p))a.add(K(l))}return a},s=new Set;for(let p of t.statement){let l=no(p);if(!l||Fe(l.name)||s.has(K(l)))continue;s.add(K(l));let m=h(e,l);if(!m)continue;let f=Kt(m,to);f.length!==0&&(f.some(R=>i().has(K(R)))||n.push(this.error(o,l,f,r[0])))}}error(e,t,o,n){let r=o.map(i=>i.name).join(" | "),a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e.split(".")[0],a.propertyName=e,a.actualValue=t.name,a.expectedValue=`Property used on ${r} or its subclasses`,a.message=`Property '${t.name}' has domain '${r}' but is used on '${n.name}' at '${e}'`,a.suggestion=`Either:
20
+ 1. Use '${t.name}' only on '${r}' (or a subclass) instances
21
+ 2. Widen the property's domain to include '${n.name}'
22
+ 3. Use a different property for '${n.name}'`,a}};function no(c){return c.predicate?.subject}function Kt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}function bt(c,e){return`${c}.${e?.name??"<embedded>"}`}var ro={publisher:"kanonak.org",package_:"core-rdf",name:"range"},ao={publisher:"kanonak.org",package_:"core-rdf",name:"Literal"},et=c=>c,Ee=class{ruleName="PropertyKindRangeConsistency";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d))continue;let s=y.isObjectPropertyType(et(i)),p=y.isDatatypePropertyType(et(i));if(!s&&!p)continue;let l=g(i,ro);if(!l||!h(r,l))continue;let m=io(r,l);p&&!m?n.push(this.error(i.name,l,"datatype")):s&&m&&n.push(this.error(i.name,l,"object"))}return n}error(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="range",n.actualValue=t.name,o==="datatype"?(n.expectedValue="A datatype (xsd type, rdfs.Literal, or a datatype-derived class)",n.message=`DatatypeProperty '${e}' has range '${t.name}', which is a class, not a datatype. A datatype property's values are literals.`,n.suggestion=`Use a datatype range (e.g. xsd.string, rdfs.Literal, or a datatype-derived class), or \u2014 if '${t.name}' is the intended target \u2014 declare '${e}' an ObjectProperty.`):(n.expectedValue="A plain class (not datatype-derived)",n.message=`ObjectProperty '${e}' has range '${t.name}', which is a datatype, not a class. An object property's values are references to resources.`,n.suggestion=`Declare '${e}' a DatatypeProperty (its values are literals of '${t.name}'), or change the range to a plain class.`),n}};function io(c,e){for(let t of Y(c,e)){if(z(t,ao))return!0;let o=h(c,t);if(o&&y.isDatatypeType(et(o)))return!0}return!1}var ve=class{ruleName="ReservedNameShadow";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);for(let a of r){if(!(a instanceof d))continue;let i=st(a.name);if(!i)continue;let s=A(a);s&&(i.publisher===s.publisher&&i.package_===s.package_||n.push(this.info(a.name,s,i)))}return n}info(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Info",n.entityName=e,n.propertyName=e,n.actualValue=`${t.publisher}/${t.package_}/${e}`,n.expectedValue=`${o.publisher}/${o.package_}/${e}`,n.message=`'${e}' is also the reserved built-in '${o.publisher}/${o.package_}/${e}'. This local definition shadows it \u2014 a bare '${e}' reference in this package resolves to the local entity, not the built-in.`,n.suggestion=`If this is intentional, qualify bare references to '${e}' explicitly (this local one vs. the built-in '${o.publisher}/${o.package_}/${e}') so the choice is unambiguous to readers and tools \u2014 e.g. a self-referential 'subClassOf: ${e}' silently resolves to this local entity.`,n}};var so={publisher:"kanonak.org",package_:"core-rdf",name:"type"},Vt=c=>c,De=class{ruleName="ClassDefinition";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of co(i,so))this.resolvesToClassLike(r,p)||n.push(this.error(s,p))}),n}resolvesToClassLike(e,t){if(Fe(t.name))return!0;let o=h(e,t);return o?y.isClassType(Vt(o))||y.isDatatypeType(Vt(o)):!1}error(e,t){let o=`${t.publisher}/${t.package_}/${t.name}`,n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="type",n.actualValue=o,n.expectedValue="Defined or imported class",n.message=`Class '${t.name}' is not defined or imported`,n.suggestion=`Define '${t.name}' as a Class in this document, or import a namespace that contains it`,n}};function co(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Ie=class{ruleName="MarkdownLink";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);return q(r,({kanonak:a,path:i})=>{this.checkNode(a,i,n)}),n}checkNode(e,t,o){for(let n of e.statement){if(!(n instanceof it))continue;let r=n.predicate.subject?.name??"(unknown)";for(let a of n.links)a.target||o.push(this.unresolvedLinkError(t,r,a.reference));for(let a of ct(n.object))o.push(this.malformedLinkError(t,r,a.snippet))}}unresolvedLinkError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Embedded link [[${o}]] in '${t}' could not be resolved`,n.expectedValue="A reference resolvable through the document's import closure",n.suggestion=`The reference '${o}' inside a markdown value cannot be found in the current document or any imported namespace.
23
+
24
+ Possible solutions:
25
+ \u2022 Import the package that defines '${o}' so the link can resolve
26
+ \u2022 Check for typos in the reference name
27
+ \u2022 If the name collides across imports, alias-qualify it: [[alias.${o}]]`,n}malformedLinkError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Malformed embedded reference near '${o}' in '${t}'`,n.expectedValue="A single-line [[reference]] with no internal line break",n.suggestion=`A '[[' in '${t}' does not form a complete [[reference]] link.
28
+
29
+ A reference may not span a line break \u2014 the most common cause is wrapping a
30
+ long reference across two lines in a block scalar, e.g.:
31
+ ... read for [[persistent-energy-
32
+ shock]] held ...
33
+ which is parsed as literal text, not a link. Keep each [[reference]] on one
34
+ line (let the line run long), or check for an unterminated [[.`,n}};var Et="kanonak.org",vt="look",po={publisher:Et,package_:vt,name:"displayLabel"},lo={publisher:Et,package_:vt,name:"displaySummary"},Ce=class{ruleName="DisplayLensScope";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=mo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&(this.checkLens(r,i,po,"displayLabel",n),this.checkLens(r,i,lo,"displaySummary",n));return n}checkLens(e,t,o,n,r){let a=g(t,o);if(!a)return;let i=[],s=A(t);if(s&&i.push(s),i.push(...lt(t)),i.length===0)return;i.some(l=>L(e,l,a).ok)||r.push(this.scopeError(t.name,n,a.name))}scopeError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`${t} points at '${o}', which is not a property in scope for '${e}'`,n.expectedValue="A property whose domain is this resource's class, an ancestor, or rdfs.Resource",n.suggestion=`'${o}' resolves, but its domain does not cover '${e}', so the lens would silently fall back to the resource's name at render time.
35
+
36
+ Possible solutions:
37
+ \u2022 Point ${t} at a property declared on this class (or an ancestor / rdfs.Resource)
38
+ \u2022 Set the property's domain to this class if it should apply here
39
+ \u2022 Use rdfs.label / rdfs.comment for the universal default`,n}};function mo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function X(c,e,t){let o=[];return Te(c,t,{input:e},o),o}function Te(c,e,t,o){if(P(e,M.VarRef)){let a=W(e,M.varName);return a?t[a]:void 0}if(P(e,M.PropertyRead)){let a=O(e,M.readSource),i=a?Te(c,a,t,o):void 0,s=g(e,M.readProp);if(!i||!s)return;let p=L(c,i,s);if(!p.ok){o.push({contextClass:i,propertyUri:s,via:"PropertyRead"});return}return p.descriptor?.range}if(P(e,M.Traverse)){let a=O(e,M.traverseSource),i=a?Te(c,a,t,o):void 0,s=g(e,M.through),p;if(i&&s){let m=L(c,i,s);m.ok?p=m.descriptor?.range:o.push({contextClass:i,propertyUri:s,via:"Traverse"})}let l=O(e,M.step);return l?Te(c,l,{...t,input:p},o):void 0}let n=W(e,M.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of uo(e))Te(c,a,r,o)}function uo(c){let e=[];for(let t of c.statement){let o=t.object;if(o instanceof v)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof v&&e.push(n)}return e}var Ne="kanonak.org",_e="look",fo={publisher:Ne,package_:_e,name:"semanticSvg"},yo={publisher:Ne,package_:_e,name:"tierChip"},go={publisher:Ne,package_:_e,name:"tierIcon"},ko={publisher:Ne,package_:_e,name:"tierCard"},ho={publisher:Ne,package_:_e,name:"tierFull"},Ro=[yo,go,ko,ho],Se=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=Ko(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=O(t,fo);if(!n)return;let r=A(t);if(r)for(let a of Ro){let i=O(n,a);if(i)for(let s of X(e,r,i))o.push(this.toError(t.name,a.name,s))}}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=r===e?`'${e}' (the class this SemanticSvg is declared on)`:`'${r}', reached by traversal from '${e}' (the class this SemanticSvg is declared on)`,i=new u;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=`look.semanticSvg.${t}`,i.actualValue=n,i.message=`tx.${o.via} reads property '${o.propertyUri.name}' off the rendered instance, but its domain is not in scope for ${a}. The read would silently return undefined at render time.`,i.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,i.suggestion=`Property '${n}' is not in scope for '${r}'.
40
+
41
+ Possible solutions:
42
+ \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
43
+ \u2022 If the property should apply to '${r}', adjust its domain
44
+ \u2022 If the value comes from a pre-computed env binding, use tx.VarRef instead of PropertyRead`,i}};function Ko(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var bo="kanonak.org",b=(c,e)=>({publisher:bo,package_:c,name:e}),Vo=b("derivation","look"),Eo=b("look","bands"),vo=b("look","Distribution"),Do=b("look","StatRow"),Io=b("look","VersionDelta"),Co=b("look","Timeline"),So=b("look","VersionDiff"),Po=b("look","TimePlot"),jo=b("look","ReferenceList"),$o=b("look","Diagram"),Oo=b("look","alphaPath"),Uo=b("look","betaPath"),tt=b("look","metricPath"),Dt=b("look","lowerPath"),It=b("look","upperPath"),Ct=b("look","hueBy"),Ao=b("look","statPath"),wo=b("look","laneBy"),St=b("look","labelPath"),xo=b("look","badgePath"),To=b("look","mapPath"),No=b("look","nodeNote"),_o=b("look","edgeValue"),Lo=b("look","stats"),Mo=b("look","facets"),Bo=b("look","channels"),Fo=b("look","track"),Wo=b("look","source"),Ho=b("look","relation"),Go=b("look","entries"),Le=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=qo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=O(t,Vo);if(!n)return;let r=A(t);if(!r)return;let a=V(n,Eo).filter(i=>i instanceof v);for(let i of a)for(let s of this.carriersOf(e,i,r))for(let p of X(e,s.context,s.expr))o.push(this.toError(t.name,s.slot,p))}carriersOf(e,t,o){let n=[],r=(a,i)=>{let s=O(t,a);s&&n.push({slot:`look.${a.name}`,context:i,expr:s})};if(P(t,vo))for(let a of[Oo,Uo,tt,Dt,It,Ct])r(a,o);if(P(t,Io)&&r(tt,o),P(t,Do)){let a=V(t,Lo).filter(i=>i instanceof v);for(let i of a){let s=O(i,Ao);s&&n.push({slot:"look.stats[].statPath",context:o,expr:s})}}if(P(t,Co)||P(t,So)){let a=this.rangeOf(e,o,g(t,Fo));if(a)for(let i of[tt,Dt,It,Ct])r(i,a)}if(P(t,Po)){let a=this.rangeOf(e,o,g(t,Wo));if(a)for(let i of[wo,St])r(i,a)}if(P(t,jo))for(let a of V(t,Go)){let i=a instanceof v?void 0:Yo(a),s=this.rangeOf(e,o,i);if(s)for(let p of[St,xo])r(p,s)}if(P(t,$o)){let a=V(t,Mo).filter(i=>i instanceof v);for(let i of a){let s=this.rangeOf(e,o,g(i,Ho));if(!s)continue;let p=O(i,No);p&&n.push({slot:"look.facets[].nodeNote",context:s,expr:p});let l=O(i,_o);l&&n.push({slot:"look.facets[].edgeValue",context:s,expr:l});let m=V(i,Bo).filter(f=>f instanceof v);for(let f of m){let R=O(f,To);R&&n.push({slot:"look.facets[].channels[].mapPath",context:s,expr:R})}}}return n}rangeOf(e,t,o){if(!o)return;let n=L(e,t,o);return n.ok?n.descriptor?.range:void 0}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=n,a.message=`tx.${o.via} reads property '${o.propertyUri.name}', but its domain is not in scope for '${r}' (the class this band carrier is evaluated against). The read would silently return undefined at render time and the band would render empty.`,a.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${n}' is not in scope for '${r}'.
45
+
46
+ Possible solutions:
47
+ \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
48
+ \u2022 If the property should apply to '${r}', adjust its domain
49
+ \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,a}};function Yo(c){let e=c.subject;return e&&typeof e.name=="string"?e:void 0}function qo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var je="kanonak.org",$e="view",zo={publisher:je,package_:$e,name:"bind"},Xo={publisher:je,package_:$e,name:"produces"},Zo={publisher:je,package_:$e,name:"projections"},Jo={publisher:je,package_:$e,name:"where"},Qo={publisher:je,package_:$e,name:"value"},en={publisher:je,package_:$e,name:"as"},Pe=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=nn(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=g(t,zo);if(!n)return;let r=g(t,Xo),a=0;for(let s of on(e,V(t,Zo))){let p=O(s,Qo);if(p)for(let m of X(e,n,p))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=g(s,en);l&&r&&(L(e,r,l).ok||o.push(this.asError(t.name,a,r,l))),a+=1}let i=0;for(let s of tn(t,Jo)){for(let p of X(e,n,s))o.push(this.toError(t.name,`view.where[${i}]`,n,p));i+=1}}asError(e,t,o,n){let r=`${n.publisher}/${n.package_}/${n.name}`,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=`view.projections[${t}].as`,a.actualValue=r,a.message=`Projection stores its value under property '${n.name}', but that property's domain is not in scope for the view's produces class '${o.name}'. The materialized result instance could not carry this value.`,a.expectedValue=`A property whose domain is '${o.name}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${r}' is not in scope for produces class '${o.name}'.
50
+
51
+ Possible solutions:
52
+ \u2022 Use an output property whose domain covers '${o.name}'
53
+ \u2022 Define a new property in the ViewPackage with domain '${o.name}' and the right range
54
+ \u2022 If the value belongs on a different output class, adjust the view's produces`,a}toError(e,t,o,n){let r=`${n.propertyUri.publisher}/${n.propertyUri.package_}/${n.propertyUri.name}`,a=n.contextClass.name,i=a===o.name?`the view's bound class '${o.name}'`:`'${a}', reached by traversal from the view's bound class '${o.name}'`,s=new u;return s.ruleType=this.ruleName,s.severity="Error",s.entityName=e,s.propertyName=t,s.actualValue=r,s.message=`tx.${n.via} reads property '${n.propertyUri.name}', but its domain is not in scope for ${i}. The read would silently return undefined when the view materializes.`,s.expectedValue=`A property whose domain is '${a}', an ancestor, or rdfs.Resource`,s.suggestion=`Property '${r}' is not in scope for '${a}'.
55
+
56
+ Possible solutions:
57
+ \u2022 Read a property declared on '${a}' (or an ancestor / rdfs.Resource)
58
+ \u2022 If the property should apply to '${a}', adjust its domain
59
+ \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,s}};function tn(c,e){let t=O(c,e);return t?[t]:V(c,e).filter(o=>o instanceof v)}function on(c,e){let t=[];for(let o of e)if(o instanceof v)t.push(o);else if(o instanceof I){let n=h(c,o.subject);n&&t.push(n)}return t}function nn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var qe="kanonak.org",rn="core-shacl",w=c=>({publisher:qe,package_:rn,name:c}),an=w("NodeShape"),sn=w("PropertyShape"),cn=w("targetClass"),pn=w("property"),ln=w("path"),mn=w("minCount"),un=w("maxCount"),fn=w("datatype"),dn=w("class"),Pt=w("in"),yn=w("pattern"),gn=w("flags"),kn=w("minLength"),hn=w("maxLength"),Rn=w("minInclusive"),Kn=w("maxInclusive"),bn=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),ot=c=>c,Ue=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Vn(e);if(!a)return n;let i=new Set;for(let s of r){if(!(s instanceof d)||s.namespace!==a||!P(s,an))continue;let p=g(s,cn);p?this.resolvesToClass(r,p)||n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' sh:targetClass '${p.name}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",Z(p))):n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' has no sh:targetClass; it constrains nothing.`,"Add sh:targetClass naming the class this shape applies to."));for(let l of V(s,pn)){let m;if(l instanceof v)m=l;else if(l instanceof I){let f=h(r,l.subject);f&&(m=f,i.add(K(l.subject)))}m&&this.checkPropertyShape(r,s.name,m,p??void 0,n)}}for(let s of r){if(!(s instanceof d)||s.namespace!==a||!P(s,sn))continue;let p=A(s);p&&i.has(K(p))||this.checkPropertyShape(r,s.name,s,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=g(o,ln);if(!a){r.push(this.err(t,"property.path","Error",`A PropertyShape on '${t}' has no sh:path; a PropertyShape must name the property it constrains.`,"Add sh:path naming a property."));return}let i=h(e,a),s=i?y.isAnyPropertyType(ot(i)):!1;s?n&&(L(e,n,a).ok||r.push(this.err(t,"property.path","Warning",`sh:path '${a.name}' is not in scope for sh:targetClass '${n.name}'; the constraint would never bind a value.`,`Constrain a property whose domain is '${n.name}', an ancestor, or rdfs.Resource.`,Z(a)))):r.push(this.err(t,"property.path","Error",`sh:path '${a.name}' on '${t}' does not resolve to a property.`,"Reference a defined or imported property.",Z(a)));let p=g(o,fn),l=g(o,dn);p&&l&&r.push(this.err(t,"property","Error",`A PropertyShape on '${t}' sets both sh:datatype and sh:class; a value is a literal or a node, not both.`,"Keep sh:datatype (literal values) or sh:class (node values), not both.")),p&&!this.resolvesToDatatype(e,p)&&r.push(this.err(t,"datatype","Error",`sh:datatype '${p.name}' on '${t}' does not resolve to a datatype.`,"Reference an xsd datatype or rdfs.Datatype.",Z(p))),l&&!this.resolvesToClass(e,l)&&r.push(this.err(t,"class","Error",`sh:class '${l.name}' on '${t}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",Z(l)));let m=Oe(x(o,mn)),f=Oe(x(o,un));this.checkOrder(t,"minCount",m,"maxCount",f,r);let R=Oe(x(o,kn)),E=Oe(x(o,hn));this.checkOrder(t,"minLength",R,"maxLength",E,r);let N=Oe(x(o,Rn)),j=Oe(x(o,Kn));this.checkOrder(t,"minInclusive",N,"maxInclusive",j,r);let $=W(o,yn);if($!==void 0){let B=W(o,gn);try{new RegExp($,B)}catch{r.push(this.err(t,"pattern","Error",`sh:pattern on '${t}' is not a valid regular expression`+(B!==void 0?` (with flags '${B}')`:"")+`: ${$}`,"Provide a valid regular expression and flags.",$))}}if(J(o,Pt)&&V(o,Pt).length===0&&r.push(this.err(t,"in","Error",`sh:in on '${t}' is empty; an enumeration must list at least one permitted value.`,"List the permitted literal values, or remove sh:in.")),s&&n){let _=L(e,n,a).descriptor;_&&(($!==void 0||R!==void 0||E!==void 0)&&_.kind==="object"&&r.push(this.err(t,"pattern/minLength/maxLength","Warning",`String facets on '${t}' apply to '${a.name}', which is an object property; string facets constrain literal values.`,"Apply string facets to a datatype property, or use sh:class for node values.",Z(a))),(N!==void 0||j!==void 0)&&!this.isNumericDatatypeRange(_.range)&&r.push(this.err(t,"minInclusive/maxInclusive","Warning",`Numeric bounds on '${t}' apply to '${a.name}', whose range is not a numeric datatype.`,"Apply numeric bounds to a numeric datatype property.",Z(a))))}}checkOrder(e,t,o,n,r,a){o!==void 0&&r!==void 0&&o>r&&a.push(this.err(e,`${t}/${n}`,"Error",`${t} (${o}) exceeds ${n} (${r}) on '${e}'.`,`Set ${t} <= ${n}.`))}resolvesToClass(e,t){let o=h(e,t);return o?y.isClassType(ot(o)):!1}resolvesToDatatype(e,t){if(t.publisher===qe&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=h(e,t);return o?y.isDatatypeType(ot(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===qe&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===qe&&e.package_==="core-xsd"&&bn.has(e.name)}err(e,t,o,n,r,a){let i=new u;return i.ruleType=this.ruleName,i.severity=o,i.entityName=e,i.propertyName=t,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function Oe(c){return typeof c=="number"?c:void 0}function Z(c){return`${c.publisher}/${c.package_}/${c.name}`}function Vn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var jt={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},En=c=>c,Ae=class{ruleName="OwlOneOf";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=vn(e);if(!a)return n;for(let i of r){if(!(i instanceof d)||i.namespace!==a||!J(i,jt))continue;let s=V(i,jt);if(s.length===0){n.push(this.err(i.name,"Warning",`owl:oneOf on '${i.name}' is empty; a closed enumeration must list at least one individual.`,"List the individuals that make up the enumeration, or remove owl:oneOf."));continue}for(let p of s)if(p instanceof Me)n.push(this.err(i.name,"Error",`owl:oneOf member '${String(p.value)}' on '${i.name}' is not a named individual; a class enumeration is of individuals (a misspelled or unimported individual reads as a literal). For a closed set of literal VALUES, constrain a property with sh:in instead.`,"Reference a defined or imported individual, or move literal value sets to a property sh:in.",String(p.value)));else if(p instanceof I){let l=h(r,p.subject);l&&y.isSchemaDefinitionType(En(l))&&n.push(this.err(i.name,"Error",`owl:oneOf member '${p.subject.name}' on '${i.name}' is a class/property/datatype, not an individual.`,"List named individuals (instances), not schema definitions.",`${p.subject.publisher}/${p.subject.package_}/${p.subject.name}`))}}return n}err(e,t,o,n,r){let a=new u;return a.ruleType=this.ruleName,a.severity=t,a.entityName=e,a.propertyName="oneOf",a.message=o,a.suggestion=n,r!==void 0&&(a.actualValue=r),a}};function vn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Dn="kanonak.org",In="core-shacl",T=c=>({publisher:Dn,package_:In,name:c}),Cn=T("NodeShape"),Sn=T("targetClass"),Pn=T("property"),jn=T("path"),$n=T("minCount"),On=T("maxCount"),Un=T("in"),An=T("pattern"),wn=T("flags"),xn=T("minLength"),Tn=T("maxLength"),Nn=T("minInclusive"),_n=T("maxInclusive"),Ln=T("message");function we(c){return typeof c=="number"?c:void 0}function Mn(c){let e={},t=we(x(c,$n)),o=we(x(c,On));t!==void 0&&(e.minCount=t),o!==void 0&&(e.maxCount=o);let n=we(x(c,xn)),r=we(x(c,Tn));n!==void 0&&(e.minLength=n),r!==void 0&&(e.maxLength=r);let a=we(x(c,Nn)),i=we(x(c,_n));a!==void 0&&(e.minInclusive=a),i!==void 0&&(e.maxInclusive=i);let s=W(c,An);if(s!==void 0){let m=W(c,wn);e.pattern=m!==void 0?{regex:s,flags:m}:{regex:s}}let p=V(c,Un).filter(m=>m instanceof Me).map(m=>m.value);p.length>0&&(e.enumValues=p);let l=W(c,Ln);return l!==void 0&&(e.message=l),e}function Bn(c,e){let t=[];for(let o of V(e,Pn))if(o instanceof v)t.push(o);else if(o instanceof I){let n=h(c,o.subject);n&&t.push(n)}return t}function $t(c){let e=new Map;for(let t of c){if(!(t instanceof d)||!P(t,Cn))continue;let o=g(t,Sn);if(!o)continue;let n=K(o);for(let r of Bn(c,t)){let a=g(r,jn);if(!a)continue;let i={pathKey:K(a),constraints:Mn(r)},s=e.get(n);s?s.push(i):e.set(n,[i])}}return e}function Fn(c,e){e.minCount!==void 0&&(c.minCount=e.minCount),e.maxCount!==void 0&&(c.maxCount=e.maxCount),e.minLength!==void 0&&(c.minLength=e.minLength),e.maxLength!==void 0&&(c.maxLength=e.maxLength),e.minInclusive!==void 0&&(c.minInclusive=e.minInclusive),e.maxInclusive!==void 0&&(c.maxInclusive=e.maxInclusive),e.pattern!==void 0&&(c.pattern=e.pattern),e.enumValues!==void 0&&(c.enumValues=e.enumValues),e.message!==void 0&&(c.message=e.message)}function Ot(c,e,t){let o=K(t),n=!1,r={};for(let a=e.length-1;a>=0;a--){let i=c.get(K(e[a]));if(i)for(let s of i)s.pathKey===o&&(n=!0,Fn(r,s.constraints))}if(n)return r.cardinality=r.maxCount===1?"single":"list",r.required=(r.minCount??0)>=1,r}var Wn=c=>c,Hn=new at("kanonak.org","core-rdf","Resource"),xe=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Gn(e);if(!a)return n;let i=$t(r);for(let s of r){if(!(s instanceof d)||s.namespace!==a||!y.isClassType(Wn(s)))continue;let p=A(s);if(!p)continue;let l=Y(r,p),m=K(p),f=new Set(l.map(E=>K(E)));f.delete(m),f.delete(K(Hn));let R=new Map;for(let E of pt(r,p)){if(!E.domains.some($=>f.has(K($))))continue;let j=R.get(E.uri.name);j?j.push(E):R.set(E.uri.name,[E])}for(let[E,N]of R){if(N.length<2)continue;let j=_=>Ot(i,l,_.uri)?.cardinality,$=new Set(N.map(_=>_.range?K(_.range):void 0).filter(_=>_!==void 0)),B=new Set(N.map(j).filter(_=>_!==void 0));$.size<=1&&B.size<=1||n.push(this.toError(s.name,E,N,j))}}return n}toError(e,t,o,n){let r=s=>{let p=`${s.uri.publisher}/${s.uri.package_}/${s.uri.name}`,l=s.range?`${s.range.publisher}/${s.range.package_}/${s.range.name}`:"no range",m=n(s);return`${p} (range ${l}${m?`, ${m}`:""})`},a=o.map(r).join("; "),i=new u;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=t,i.actualValue=a,i.message=`Class '${e}' inherits ${o.length} distinct properties named '${t}' with incompatible range or cardinality: ${a}. The generated interface would multiply-inherit '${t}' with conflicting types and could not compile.`,i.suggestion=`Disambiguate the diamond name-clash on '${t}':
60
+ \u2022 rename one of the properties, or
61
+ \u2022 re-domain one so it is not inherited by '${e}', or
62
+ \u2022 restructure the hierarchy so '${e}' inherits only one '${t}', or
63
+ \u2022 make the ranges/cardinalities compatible (identical) if they are meant to be the same property.`,i}};function Gn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var nt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new rt,this.documentRules=[new ne,new re,new ae,new ie,new se],this.repositoryRules=[new ce,new pe,new le,new me,new ue,new fe,new de,new ye,new ge,new ke,new he,new Re,new be,new Ve,new Ee,new ve,new De,new Ie,new Ce,new Se,new Le,new Pe,new Ue,new Ae,new xe]}async validateAsync(e,t,o){let n=new Q;for(let r of this.documentRules)try{let a=r.validate(e);this.addErrorsToResult(n,a)}catch(a){let i=new u;i.ruleType=r.ruleName,i.severity="Error",i.message=`Validation rule '${r.ruleName}' failed: ${a instanceof Error?a.message:String(a)}`,n.errors.push(i)}if(t){let r=[],a=o??new ee(new te(e,t)),i=a.repository;for(let s of this.repositoryRules)try{let p=await s.validateAsync(e,i,a);this.addErrorsToResult(n,p)}catch(p){let l=p instanceof Error?p.message:String(p);r.push({ruleName:s.ruleName,cause:l})}if(r.length>0){let s=new Map;for(let{ruleName:p,cause:l}of r){let m=s.get(l);m?m.push(p):s.set(l,[p])}for(let[p,l]of s){let m=new u;m.ruleType=l[0],m.severity="Error",l.length===1?m.message=`Validation rule '${l[0]}' failed: ${p}`:m.message=`${p} (affects ${l.length} rules: ${l.join(", ")})`,n.errors.push(m)}}}return n.isValid=n.errors.length===0,n}async validateDocumentsAsync(e,t){let o=new ee(t),n=[];for(let r of e){let a=await this.validateAsync(r,o.repository,o);n.push({document:r,result:a})}return n}async validateYamlAsync(e,t,o){let n=this.parser.parseWithErrors(e);if(!n.isValid){let r=new Q;r.isValid=!1;for(let a of n.errors){let i=new u;i.ruleType="ParseError",i.severity="Error",i.lineNumber=a.line,i.column=a.column,i.message=a.message,a.keyName&&(i.entityName=a.keyName),a.errorType==="DuplicateKey"&&(i.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),r.errors.push(i)}return r}return await this.validateAsync(n.document,t,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(o=>o instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(o=>o instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let o of t)o.severity==="Error"?e.errors.push(o):o.severity==="Info"?this.includeWarnings&&e.infos.push(o):this.includeWarnings&&e.warnings.push(o)}};export{Q as a,k as b,u as c,ze as d,ee as e,ne as f,re as g,ae as h,ie as i,se as j,ce as k,pe as l,le as m,me as n,ue as o,fe as p,de as q,ye as r,ge as s,ke as t,he as u,Re as v,be as w,Ve as x,Ee as y,ve as z,De as A,Ie as B,Ce as C,Se as D,Pe as E,Ue as F,Ae as G,$t as H,Ot as I,xe as J,nt as K};
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@ export type { IStatement } from './statements/index.js';
15
15
  export type { MarkdownLink } from './statements/index.js';
16
16
  export { Statement, ScalarStatement, StringStatement, NumberStatement, BooleanStatement, ReferenceStatement, EmbeddedStatement, ListStatement, MarkdownStatement } from './statements/index.js';
17
17
  export { extractMarkdownLinks, findMalformedReferences, type RawMarkdownLink, type MalformedMarkdownLink, } from './parsing/extractMarkdownLinks.js';
18
- export { OntologyValidationResult, OntologyValidationError, ValidationSeverity, ValidationContext, ValidationCache, KanonakObjectValidator, NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, PackageHeaderRule, EmbeddedKanonakTypeRule, ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, UnresolvedPredicateRule, DefinitionPropertyReferenceRule, XsdImportRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyImportRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyValueTypeRule, ClassDefinitionRule, MarkdownLinkRule } from './validation/index.js';
18
+ export { OntologyValidationResult, OntologyValidationError, ValidationSeverity, ValidationContext, ValidationCache, KanonakObjectValidator, NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, PackageHeaderRule, EmbeddedKanonakTypeRule, ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, UnresolvedPredicateRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyKindRangeConsistencyRule, ReservedNameShadowRule, ClassDefinitionRule, MarkdownLinkRule } from './validation/index.js';
19
19
  export type { IKanonakObjectValidator, DocumentValidationResult, IDocumentValidationRule, IRepositoryValidationRule } from './validation/index.js';
20
20
  export type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
21
21
  export type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{a as yr,b as gr,c as kr,d as hr,e as ge}from"./chunk-CR55WXIN.js";import{a as pn,c as Pe,e as _e,h as Ue,i as Fe,j as dn}from"./chunk-V72IVYR4.js";import{a as dr,b as mr,c as fr,d as L,e as M,f as l,g as mn}from"./chunk-NUXUITUC.js";import{a as un}from"./chunk-VWS25JH4.js";import"./chunk-QHABFCRC.js";import{a as Ot,b as Nt,c as _t,d as Ut,e as Ft,f as qt,g as Yt,h as Zt,i as Xt}from"./chunk-GMEPM2QQ.js";import{a as Lt,b as Mt,c as Ht,d as R,f as zt,g as Wt,h as Jt}from"./chunk-JYBKSBB5.js";import{a as Bt}from"./chunk-4NO7MHS7.js";import{a as Pr,b as wr,c as Sr,d as Rr}from"./chunk-RGOBWOBB.js";import{a as Er,b as jr}from"./chunk-PEUTCG3B.js";import{a as Cr}from"./chunk-PEJALHXK.js";import{a as Gt}from"./chunk-SC5M74NM.js";import{A as on,B as an,C as sn,D as cn,M as ln,a as Tr,b as Ar,c as Dr,d as Vr,e as Br,f as Or,g as Nr,h as _r,i as Ur,j as Fr,k as Lr,l as Mr,m as Hr,n as zr,o as Wr,p as Gr,q as Jr,r as qr,s as Yr,t as Zr,u as Xr,v as Qr,w as en,x as tn,y as rn,z as nn}from"./chunk-UBBZWWRB.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as ce,c as rr,d as U,e as Oe,f as lr,g as ur,h as K}from"./chunk-BKVPSPG4.js";import{a as x}from"./chunk-NJ3AZYQD.js";import{a as pr,b as ke,c as vr,d as g,e as xr,f as Ir,g as Kr,h as $r}from"./chunk-IEOSSSB5.js";import{f as F,k as $,l as he,m as be,n as Ne}from"./chunk-7TKJHKC2.js";import{b as nr,c as or,d as I,e as ir,f as ar,h as sr,k as cr}from"./chunk-7HRKWTBB.js";import{a as Qt,b as se,c as f,d as h,e as tr,f as le,g as ue,h as pe,i as de,j as me,k as fe,l as ye}from"./chunk-4UT2CLAT.js";import{a as er}from"./chunk-FUUTGGJS.js";import{a as Kt,b as ae,c as _,d as $t,e as k,f as jt,g as Tt,h as At,i as Dt,j as Vt}from"./chunk-2ACBWC7K.js";import{a as br}from"./chunk-ODIECDN7.js";import{VersionOperator as Oa}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Vn,readFileSync as Bn}from"fs";import{homedir as On}from"os";import{join as Nn}from"path";import{execFile as fn}from"child_process";import{promisify as yn}from"util";var H=yn(fn),gn="kanonak",z="/usr/bin/security",b=class{constructor(e=gn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await H(z,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
1
+ import{a as yr,b as gr,c as kr,d as hr,e as he}from"./chunk-TVSHIXLA.js";import{a as ln,c as Pe,e as _e,h as Ue,i as Fe,j as un}from"./chunk-IHB7UVEH.js";import{a as dr,b as mr,c as fr,d as L,e as M,f as l,g as pn}from"./chunk-VZNNI2VR.js";import{a as cn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as Ot,b as Nt,c as _t,d as Ut,e as Ft,f as qt,g as Yt,h as Zt,i as Xt}from"./chunk-GMEPM2QQ.js";import{a as Lt,b as Mt,c as Ht,d as R,f as zt,g as Wt,h as Jt}from"./chunk-JYBKSBB5.js";import{a as Vt}from"./chunk-4NO7MHS7.js";import{a as Pr,b as wr,c as Sr,d as Rr}from"./chunk-S6VSAKXB.js";import{a as vr,b as jr}from"./chunk-PEUTCG3B.js";import{a as Cr}from"./chunk-PEJALHXK.js";import{a as Gt}from"./chunk-SC5M74NM.js";import{A as on,B as an,K as sn,a as Ar,b as Tr,c as Dr,d as Br,e as Vr,f as Or,g as Nr,h as _r,i as Ur,j as Fr,k as Lr,l as Mr,m as Hr,n as zr,o as Wr,p as Gr,q as Jr,r as qr,s as Yr,t as Zr,u as Xr,v as Qr,w as en,x as tn,y as rn,z as nn}from"./chunk-ZO5IUMX6.js";import{a as y,b as ce,c as rr,h as F,i as Oe,j as lr,k as ur,l as $}from"./chunk-MX3DEXMV.js";import{a as x}from"./chunk-NJ3AZYQD.js";import{a as pr,b as be,c as Er,d as g,e as xr,f as Ir,g as Kr,h as $r}from"./chunk-WFQANMBQ.js";import{a as Ne}from"./chunk-6U26UASC.js";import{a as nr,b as or,c as K,d as ir,e as ar,g as sr,k as cr}from"./chunk-GZPLWII7.js";import{a as Qt,b as se,c as f,d as h,e as tr,f as le,g as ue,h as pe,i as de,j as me,k as fe,l as ye,r as U,w as I,x as ge,y as ke}from"./chunk-7BHDZHJY.js";import{a as er}from"./chunk-FUUTGGJS.js";import{a as Kt,b as ae,c as _,d as $t,e as k,f as jt,g as At,h as Tt,i as Dt,j as Bt}from"./chunk-2ACBWC7K.js";import{a as br}from"./chunk-ODIECDN7.js";import{VersionOperator as Ba}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Tn,readFileSync as Dn}from"fs";import{homedir as Bn}from"os";import{join as Vn}from"path";import{execFile as dn}from"child_process";import{promisify as mn}from"util";var H=mn(dn),fn="kanonak",z="/usr/bin/security",b=class{constructor(e=fn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await H(z,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(Le(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${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,t){let n=l(e),o=JSON.stringify(t);try{await H(z,["add-generic-password","-s",this.service,"-a",n,"-U","-w",o],{timeout:1e4})}catch(i){throw new Error(`macOS Keychain write failed for '${n}': ${W(i)}
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 t=l(e);try{await H(z,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(n){if(Le(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${W(n)}
7
7
  The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await H(z,["dump-keychain"],{timeout:1e4}),t=[],n=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${W(e)}`),[]}}};function Le(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function W(r){return r instanceof Error?r.message:String(r)}import{execFile as kn}from"child_process";import{promisify as hn}from"util";var bn=hn(kn),Pn="kanonak:",P=class{constructor(e=Pn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+l(e),n=`
8
+ `))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${W(e)}`),[]}}};function Le(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function W(r){return r instanceof Error?r.message:String(r)}import{execFile as yn}from"child_process";import{promisify as gn}from"util";var kn=gn(yn),hn="kanonak:",P=class{constructor(e=hn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+l(e),n=`
9
9
  ${J}
10
10
  $target = [Console]::In.ReadLine()
11
11
  $ptr = [IntPtr]::Zero
@@ -41,7 +41,7 @@ ${J}
41
41
  $target = [Console]::In.ReadLine()
42
42
  [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await G(n,t)}catch{}}async list(){let e=`
43
43
  ${J}
44
- ${wn}
44
+ ${bn}
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:t}=await G(e,this.targetPrefix);return t.trim().split(`
59
- `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function G(r,e){for(let t of["pwsh","powershell"])try{return await bn(t,["-NoProfile","-NonInteractive","-Command",r],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(t==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var J=`
59
+ `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function G(r,e){for(let t of["pwsh","powershell"])try{return await kn(t,["-NoProfile","-NonInteractive","-Command",r],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(t==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var J=`
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
- "@`,wn="";import{execFile as Sn,spawn as Rn}from"child_process";import{promisify as En}from"util";var q=En(Sn),vn="kanonak",w=class{constructor(e=vn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await q("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((i,a)=>{let s=Rn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?i():a(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",a)})}async remove(e){let t=l(e);try{await q("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await q("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
91
- `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function j(){try{return await q("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Me,mkdirSync as He,readFileSync as ze,writeFileSync as We}from"fs";import{createCipheriv as Cn,createDecipheriv as xn,randomBytes as Ge}from"crypto";import{homedir as In}from"os";import{join as Re,dirname as Je}from"path";var Ye=Re(In(),".config","kanonak"),T=Re(Ye,"keyring.key"),Kn=Re(Ye,"credentials.enc"),qe="aes-256-gcm",we=32,E=12,Se=16,S=class{constructor(e=Kn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Me(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ze(this.secretsFile);if(t.length<E+Se)return{};let n=t.subarray(0,E),o=t.subarray(E,E+Se),i=t.subarray(E+Se),a=xn(qe,e,n);a.setAuthTag(o);let s=Buffer.concat([a.update(i),a.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=Ge(E),o=Cn(qe,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),a=Buffer.concat([o.update(i),o.final()]),s=o.getAuthTag(),c=Buffer.concat([n,s,a]);He(Je(this.secretsFile),{recursive:!0}),We(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(Me(T)){let t=ze(T);if(t.length!==we)throw new Error(`Credential keyring key is corrupted (expected ${we} bytes, got ${t.length}). Delete ${T} and re-authenticate.`);return t}let e=Ge(we);return He(Je(T),{recursive:!0}),We(T,e,{mode:384}),e}};import{execFile as $n}from"child_process";import{promisify as jn}from"util";var Tn=jn($n),Ze=3e4,A=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${Y(n)}
90
+ "@`,bn="";import{execFile as Pn,spawn as wn}from"child_process";import{promisify as Sn}from"util";var q=Sn(Pn),Rn="kanonak",w=class{constructor(e=Rn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await q("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((i,a)=>{let s=wn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?i():a(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",a)})}async remove(e){let t=l(e);try{await q("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await q("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
91
+ `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function j(){try{return await q("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Me,mkdirSync as He,readFileSync as ze,writeFileSync as We}from"fs";import{createCipheriv as vn,createDecipheriv as En,randomBytes as Ge}from"crypto";import{homedir as Cn}from"os";import{join as Re,dirname as Je}from"path";var Ye=Re(Cn(),".config","kanonak"),A=Re(Ye,"keyring.key"),xn=Re(Ye,"credentials.enc"),qe="aes-256-gcm",we=32,v=12,Se=16,S=class{constructor(e=xn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Me(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ze(this.secretsFile);if(t.length<v+Se)return{};let n=t.subarray(0,v),o=t.subarray(v,v+Se),i=t.subarray(v+Se),a=En(qe,e,n);a.setAuthTag(o);let s=Buffer.concat([a.update(i),a.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=Ge(v),o=vn(qe,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),a=Buffer.concat([o.update(i),o.final()]),s=o.getAuthTag(),c=Buffer.concat([n,s,a]);He(Je(this.secretsFile),{recursive:!0}),We(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(Me(A)){let t=ze(A);if(t.length!==we)throw new Error(`Credential keyring key is corrupted (expected ${we} bytes, got ${t.length}). Delete ${A} and re-authenticate.`);return t}let e=Ge(we);return He(Je(A),{recursive:!0}),We(A,e,{mode:384}),e}};import{execFile as In}from"child_process";import{promisify as Kn}from"util";var $n=Kn(In),Ze=3e4,T=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${Y(n)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
93
93
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=l(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${Y(o)}
94
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${Y(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: ${Y(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await Tn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Ze});return n}catch(n){throw An(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Dn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Ze/1e3}s on '${e}'.
96
- The helper may be waiting for authentication to an external vault.`):n}}};function Y(r){return r instanceof Error?r.message:String(r)}function An(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function Dn(r){return r instanceof Error&&"killed"in r&&r.killed}var Ee=Nn(On(),".kanonak","config.json"),Z=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 t=_n(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!M(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Un();return e.credentialHelper?new A(e.credentialHelper):process.platform==="darwin"?new b:process.platform==="win32"?new P:await j()?new w:new S}};function _n(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Un(){if(!Vn(Ee))return{};try{return JSON.parse(Bn(Ee,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ee}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as Fn}from"os";import{join as Ln}from"path";var ve="kanonak-device",Mn=Ln(Fn(),".config","kanonak","device-credentials.enc"),X=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 get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return process.platform==="darwin"?new b(ve):process.platform==="win32"?new P(`${ve}:`):await j()?new w(ve):new S(Mn)}};import{createHash as Hn,createPrivateKey as zn,generateKeyPairSync as Wn,randomUUID as Gn,sign as Jn}from"crypto";function Qe(){let{publicKey:r,privateKey:e}=Wn("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function D(r,e,t,n,o,i){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Gn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Hn("sha256").update(o).digest("base64url")),i&&(s.nonce=i),qn(a,s,r)}function et(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function qn(r,e,t){let n=Xe(JSON.stringify(r)),o=Xe(JSON.stringify(e)),i=`${n}.${o}`,a=zn({key:t,format:"jwk"}),c=Jn("SHA256",Buffer.from(i),{key:a,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function Xe(r){return Buffer.from(r,"utf-8").toString("base64url")}function tt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return R(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return R(t,{method:o});L(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let a={};if(i.dpopKeyPair){let c=e.get(n);try{let u=D(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);a.Authorization=`DPoP ${i.accessToken}`,a.DPoP=u}catch(u){let p=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${n}': ${p}
98
- The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),a.Authorization=`Bearer ${i.accessToken}`}}else a.Authorization=`Bearer ${i.accessToken}`;let s=await R(t,{method:o,headers:a});if(s.status===401&&i.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let u=D(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);a.DPoP=u,s=await R(t,{method:o,headers:a})}catch{}}}return s}}import{readFileSync as Yn,writeFileSync as Zn,existsSync as Xn}from"fs";import{createHash as Qn}from"crypto";import rt from"js-yaml";var nt="kanonak.lock",eo=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function ot(r=nt){if(!Xn(r))return null;let e=Yn(r,"utf-8"),t=rt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function it(r,e=nt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=rt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Zn(e,eo+n,"utf-8")}function at(r){return`sha256:${Qn("sha256").update(r).digest("hex")}`}import*as Ie from"js-yaml";import{canonicalForm as to,canonicalHash as ro}from"@kanonak-protocol/canonical";function Ce(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as mt}from"@kanonak-protocol/canonical";function st(r){return to(Ce(r)?r:ct(r))}function Q(r){return ro(Ce(r)?r:ct(r))}function ct(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:ao(t),statements:xe(t.statement)});return{subjects:e}}function xe(r){let e=[];for(let t of r){let n=io(t);if(!n)continue;let o=no(t);o&&e.push({predicate:n,value:o})}return e}function no(r){if(r instanceof le&&r.carrier)return{lit:r.lexical??String(r.object),datatype:ut(r.carrier)};if(r instanceof ue)return{raw:r.object};if(r instanceof pe)return{raw:r.lexical??String(r.object)};if(r instanceof de)return{raw:r.lexical??String(r.object)};if(r instanceof me)return{ref:pt(r.object)};if(r instanceof fe)return lt(r.object);if(r instanceof ye)return{list:r.object.map(oo)}}function lt(r){let e=xe(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function oo(r){if(r instanceof h)return{ref:pt(r)};if(r instanceof y)return lt(r);if(r instanceof ce){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:ut(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof se)return{embed:{statements:xe(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function ut(r){return r===U.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function io(r){let e=r.predicate;if(e)return dt(e.subject)}function ao(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function pt(r){return dt(r.subject)}function dt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as ft}from"@kanonak-protocol/types/document/models/enums";var so="0.0.0",v=class{constructor(e,t=new x,n){this.repository=e;this.parser=t;this.objectParser=n??new K(this.parser)}repository;parser;objectParser;imports(){return new V}serializeValue(e,t){return kt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Ke(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let a={[o]:i,...e.body},s=this.dump(a);return{yaml:s,byteCount:gt(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},a=this.dump(i),s={yaml:a,byteCount:gt(a),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ie.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[yt]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ie.dump(o,{lineWidth:-1})),a=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Ne(i,this.repository))).filter(u=>u instanceof f&&u.namespace===a&&u.name!==yt);for(let u of c)u.namespace="ephemeral";return Q(c)}},yt="__pkgbuilder_probe__";function gt(r){return new TextEncoder().encode(r).length}function Ke(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var V=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=ft.Major){let a=`${e}/${t}@${n}`,s=this.byKey.get(a);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(a,{publisher:e,package_:t,version:n,alias:c,match:i}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,so,o??t,ft.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ae(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=B(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function kt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof h)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>kt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(co(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function B(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function co(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ee=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${k(o)}`,a=this.produced.get(i);if(a)return a;let{document:s}=await e.produce(t,n,o);return this.produced.set(i,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=ke(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var $e={async authorize(){return{allowed:!0}}},je={async record(){}},O=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},te=class{inner;ctx;policy;meter;constructor(e,t,n=$e,o=je){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new O(e,t.reason)}};var d="kanonak.org",m="view",ht="core-kanonak",lo={publisher:d,package_:m,name:"rootView"},uo={publisher:d,package_:m,name:"bind"},po={publisher:d,package_:m,name:"produces"},mo={publisher:d,package_:m,name:"projections"},fo={publisher:d,package_:m,name:"where"},yo={publisher:d,package_:m,name:"value"},go={publisher:d,package_:m,name:"as"},re=class{constructor(e,t=new x){this.repository=e;this.parser=t;this.objectParser=new K(this.parser),this.builder=new v(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=$(o,uo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let a=$(o,po);if(!a)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=ko(o),c=bt(n,d,ht),u=bt(n,d,m),p=this.builder.imports(),ne=p.ensure(d,ht,c,"ck"),wt=p.ensure(d,m,u,"v"),St=p.ref(a),Rt=new Fe(this.repository,this.parser,this.objectParser),Te=new _e(Rt,n),Et=this.readProjections(n,o),vt=Po(o,fo),Ct=this.findInstances(n,i,await this.reason(t)),Ae={},xt=new Set;for(let N of Ct){if(!await this.passesWhere(Te,n,vt,N))continue;let ie={type:St};for(let Ve of Et){let It=await this.evaluateValue(Te,n,Ve.value,N),Be=this.builder.serializeValue(Pt(It),p);Be!==void 0&&(ie[p.ref(Ve.as)]=Be)}let De=g(N);De&&(ie[`${wt}.derivedFrom`]=p.ref(De)),Ae[this.rowName(N,xt)]=ie}let oe={};t.resolvedAt&&(oe[`${ne}.resolvedAt`]=t.resolvedAt),t.invocationId&&(oe[`${ne}.id`]=t.invocationId);let C=await this.builder.buildContentAddressed({publisher:s,book:p,body:Ae,contentHashProperty:`${ne}.contentHash`,header:oe});return{yaml:C.yaml,contentHash:C.contentHash,packageName:C.packageName,publisher:C.publisher,rowCount:C.resourceCount}}resolveView(e,t){let n=F(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=$(n,lo);if(o){let i=F(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of be(t,mo)){let i=o instanceof y?o:o instanceof h?F(e,o.subject):void 0;if(!i)continue;let a=he(i,yo),s=$(i,go);a&&s&&n.push({value:a,as:s})}return n}async reason(e){return new ge({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=bo(e),i=[],a=new Set;for(let s of n.getInstancesOfClass(t)){if(a.has(s))continue;a.add(s);let c=o.get(s);c&&i.push(c)}return i.sort((s,c)=>{let u=I(g(s)),p=I(g(c));return u<p?-1:u>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let a=await this.evaluateValue(e,t,i,o);if(!wo(a))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ue(n,"view-projection",{catalog:t,depth:0}),a=new Map([["input",o]]);return e.evaluate(i,a)}rowName(e,t){let n=B(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Pt(r){return Pe(r)?r.value:Array.isArray(r)?r.map(Pt):r}function ko(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function bt(r,e,t){let n=ho(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function ho(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let i=g(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||_(i.version,n)>0)&&(n=i.version)}return n?k(n):void 0}function bo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let i=I(o),a=t.get(i);(!a||_(o.version,a)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function Po(r,e){let t=he(r,e);return t?[t]:be(r,e).filter(n=>n instanceof y)}function wo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Pe(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{en as AmbiguousReferenceRule,de as BooleanStatement,mt as CANONICAL_FORM_VERSION,U as Carrier,sn as ClassDefinitionRule,zr as ClassHierarchyCycleRule,_t as CompositeKanonakDocumentRepository,Z as CredentialStore,se as DefinedKanonak,Xr as DefinitionPropertyReferenceRule,X as DeviceCertificateStore,Nt as DocumentLocation,mr as EdgeType,y as EmbeddedKanonak,Lr as EmbeddedKanonakTypeRule,fe as EmbeddedStatement,O as EntitlementDeniedError,te as EntitlementProducer,Ot as FileSystemKanonakDocumentRepository,br as GitIgnoreFilter,fr as GraphBuilder,Jt as HttpKanonakDocumentRepository,V as ImportBook,Mr as ImportExistenceRule,Bt as InMemoryKanonakDocumentRepository,Lt as KANONAK_USER_AGENT,Qt as Kanonak,wr as KanonakDocumentPositions,K as KanonakObjectParser,ln as KanonakObjectValidator,x as KanonakParser,er as KanonakUri,Er as KanonakUriBuilder,Cr as KanonakUrlResolver,cr as KanonakVocabulary,ye as ListStatement,ce as LiteralKanonak,qt as LocalFirstRepository,Yt as LockAwareRepository,dn as LookRenderer,cn as MarkdownLinkRule,rr as MarkdownStatement,Yr as NamespaceImportCycleRule,Or as NamespacePrefixRule,dr as NodeType,pe as NumberStatement,kr as OWL_RL_CLASSIFICATION_RULES,rn as ObjectPropertyImportRule,nn as ObjectPropertyValueValidationRule,Dr as OntologyValidationError,Tr as OntologyValidationResult,v as PackageBuilder,Fr as PackageHeaderRule,ee as ProducerRepository,on as PropertyDomainRule,Wr as PropertyHierarchyCycleRule,Pr as PropertyMetadata,tn as PropertyRangeReferenceRule,Gr as PropertyRangeRequiredRule,_r as PropertyTypeSpecificityRule,an as PropertyValueTypeRule,zt as PublisherConfigResolver,Wt as PublisherIndex,gr as RDFS_RULES,ge as Reasoner,hr as ReasoningResult,h as ReferenceKanonak,me as ReferenceStatement,Ft as RepositoryFactory,Nr as ResourceNamingRule,nr as ResourceResolver,pr as ResourceTypeClassifier,le as ScalarStatement,tr as Statement,ue as StringStatement,Jr as SubClassOfReferenceRule,qr as SubPropertyOfReferenceRule,f as SubjectKanonak,Ur as SubjectKanonakTypeRequiredRule,yr as TripleStore,or as TypeResolver,Zr as UnresolvedPredicateRule,Hr as UnresolvedReferenceRule,Br as ValidationCache,Vr as ValidationContext,Ar as ValidationSeverity,Oa as VersionOperator,re as ViewMaterializer,Qr as XsdImportRule,$e as allowAllPolicy,Gt as assertPackageIdentity,Xt as buildLocalFirstRepository,mn as buildOntologyModel,st as canonicalForm,Q as canonicalHash,Oe as carrierOf,Zt as collectKanonakFiles,_ as compareVersions,at as computeIntegrity,Ke as contentAddressedName,$r as contextTypesOf,tt as createAuthenticatedFetch,D as createDPoPProof,jt as createVersion,ur as extractMarkdownLinks,un as findDerivation,jr as findInstancesByType,lr as findMalformedReferences,Rr as findMarkdownLinkAt,vr as formatKanonakAddress,k as formatVersion,Qe as generateDPoPKeyPair,Ut as getGlobalCachePath,Ht as getKanonakUserAgent,M as hasValidToken,At as isCompatibleVersion,L as isExpired,Dt as isMajorCompatible,R as kanonakFetch,ot as loadLockFile,ir as makeUriKey,je as noopMeter,l as normalizeHost,ke as parseKanonakAddress,Tt as parseVersionString,Sr as parseWithPositions,Vt as pickHighestDocument,Ir as propertiesInScope,pn as resolveDisplayValue,Kr as resolvePropertyStep,B as sanitizeName,it as saveLockFile,et as serverSupportsDPoP,Mt as setKanonakUserAgent,g as subjectUri,xr as superClassChain,ar as tripleKey,I as uriKey,sr as uriTriple,Kt as versionOperatorFromChar,ae as versionOperatorToChar,$t as versionsEqual};
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${Y(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: ${Y(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await $n(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Ze});return n}catch(n){throw jn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):An(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Ze/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):n}}};function Y(r){return r instanceof Error?r.message:String(r)}function jn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function An(r){return r instanceof Error&&"killed"in r&&r.killed}var ve=Vn(Bn(),".kanonak","config.json"),Z=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 t=On(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!M(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Nn();return e.credentialHelper?new T(e.credentialHelper):process.platform==="darwin"?new b:process.platform==="win32"?new P:await j()?new w:new S}};function On(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Nn(){if(!Tn(ve))return{};try{return JSON.parse(Dn(ve,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${ve}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as _n}from"os";import{join as Un}from"path";var Ee="kanonak-device",Fn=Un(_n(),".config","kanonak","device-credentials.enc"),X=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 get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return process.platform==="darwin"?new b(Ee):process.platform==="win32"?new P(`${Ee}:`):await j()?new w(Ee):new S(Fn)}};import{createHash as Ln,createPrivateKey as Mn,generateKeyPairSync as Hn,randomUUID as zn,sign as Wn}from"crypto";function Qe(){let{publicKey:r,privateKey:e}=Hn("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function D(r,e,t,n,o,i){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:zn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Ln("sha256").update(o).digest("base64url")),i&&(s.nonce=i),Gn(a,s,r)}function et(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Gn(r,e,t){let n=Xe(JSON.stringify(r)),o=Xe(JSON.stringify(e)),i=`${n}.${o}`,a=Mn({key:t,format:"jwk"}),c=Wn("SHA256",Buffer.from(i),{key:a,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function Xe(r){return Buffer.from(r,"utf-8").toString("base64url")}function tt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return R(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return R(t,{method:o});L(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let a={};if(i.dpopKeyPair){let c=e.get(n);try{let u=D(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);a.Authorization=`DPoP ${i.accessToken}`,a.DPoP=u}catch(u){let p=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${n}': ${p}
98
+ The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),a.Authorization=`Bearer ${i.accessToken}`}}else a.Authorization=`Bearer ${i.accessToken}`;let s=await R(t,{method:o,headers:a});if(s.status===401&&i.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let u=D(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);a.DPoP=u,s=await R(t,{method:o,headers:a})}catch{}}}return s}}import{readFileSync as Jn,writeFileSync as qn,existsSync as Yn}from"fs";import{createHash as Zn}from"crypto";import rt from"js-yaml";var nt="kanonak.lock",Xn=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function ot(r=nt){if(!Yn(r))return null;let e=Jn(r,"utf-8"),t=rt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function it(r,e=nt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=rt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});qn(e,Xn+n,"utf-8")}function at(r){return`sha256:${Zn("sha256").update(r).digest("hex")}`}import*as Ie from"js-yaml";import{canonicalForm as Qn,canonicalHash as eo}from"@kanonak-protocol/canonical";function Ce(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as mt}from"@kanonak-protocol/canonical";function st(r){return Qn(Ce(r)?r:ct(r))}function Q(r){return eo(Ce(r)?r:ct(r))}function ct(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:oo(t),statements:xe(t.statement)});return{subjects:e}}function xe(r){let e=[];for(let t of r){let n=no(t);if(!n)continue;let o=to(t);o&&e.push({predicate:n,value:o})}return e}function to(r){if(r instanceof le&&r.carrier)return{lit:r.lexical??String(r.object),datatype:ut(r.carrier)};if(r instanceof ue)return{raw:r.object};if(r instanceof pe)return{raw:r.lexical??String(r.object)};if(r instanceof de)return{raw:r.lexical??String(r.object)};if(r instanceof me)return{ref:pt(r.object)};if(r instanceof fe)return lt(r.object);if(r instanceof ye)return{list:r.object.map(ro)}}function lt(r){let e=xe(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function ro(r){if(r instanceof h)return{ref:pt(r)};if(r instanceof y)return lt(r);if(r instanceof ce){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:ut(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof se)return{embed:{statements:xe(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function ut(r){return r===F.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function no(r){let e=r.predicate;if(e)return dt(e.subject)}function oo(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function pt(r){return dt(r.subject)}function dt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as ft}from"@kanonak-protocol/types/document/models/enums";var io="0.0.0",E=class{constructor(e,t=new x,n){this.repository=e;this.parser=t;this.objectParser=n??new $(this.parser)}repository;parser;objectParser;imports(){return new B}serializeValue(e,t){return kt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Ke(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let a={[o]:i,...e.body},s=this.dump(a);return{yaml:s,byteCount:gt(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},a=this.dump(i),s={yaml:a,byteCount:gt(a),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ie.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[yt]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ie.dump(o,{lineWidth:-1})),a=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Ne(i,this.repository))).filter(u=>u instanceof f&&u.namespace===a&&u.name!==yt);for(let u of c)u.namespace="ephemeral";return Q(c)}},yt="__pkgbuilder_probe__";function gt(r){return new TextEncoder().encode(r).length}function Ke(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var B=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=ft.Major){let a=`${e}/${t}@${n}`,s=this.byKey.get(a);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(a,{publisher:e,package_:t,version:n,alias:c,match:i}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,io,o??t,ft.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ae(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=V(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function kt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof h)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>kt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(ao(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function V(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function ao(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ee=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${k(o)}`,a=this.produced.get(i);if(a)return a;let{document:s}=await e.produce(t,n,o);return this.produced.set(i,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=be(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var $e={async authorize(){return{allowed:!0}}},je={async record(){}},O=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},te=class{inner;ctx;policy;meter;constructor(e,t,n=$e,o=je){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new O(e,t.reason)}};var d="kanonak.org",m="view",ht="core-kanonak",so={publisher:d,package_:m,name:"rootView"},co={publisher:d,package_:m,name:"bind"},lo={publisher:d,package_:m,name:"produces"},uo={publisher:d,package_:m,name:"projections"},po={publisher:d,package_:m,name:"where"},mo={publisher:d,package_:m,name:"value"},fo={publisher:d,package_:m,name:"as"},re=class{constructor(e,t=new x){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new E(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=I(o,co);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let a=I(o,lo);if(!a)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=yo(o),c=bt(n,d,ht),u=bt(n,d,m),p=this.builder.imports(),ne=p.ensure(d,ht,c,"ck"),wt=p.ensure(d,m,u,"v"),St=p.ref(a),Rt=new Fe(this.repository,this.parser,this.objectParser),Ae=new _e(Rt,n),vt=this.readProjections(n,o),Et=ho(o,po),Ct=this.findInstances(n,i,await this.reason(t)),Te={},xt=new Set;for(let N of Ct){if(!await this.passesWhere(Ae,n,Et,N))continue;let ie={type:St};for(let Be of vt){let It=await this.evaluateValue(Ae,n,Be.value,N),Ve=this.builder.serializeValue(Pt(It),p);Ve!==void 0&&(ie[p.ref(Be.as)]=Ve)}let De=g(N);De&&(ie[`${wt}.derivedFrom`]=p.ref(De)),Te[this.rowName(N,xt)]=ie}let oe={};t.resolvedAt&&(oe[`${ne}.resolvedAt`]=t.resolvedAt),t.invocationId&&(oe[`${ne}.id`]=t.invocationId);let C=await this.builder.buildContentAddressed({publisher:s,book:p,body:Te,contentHashProperty:`${ne}.contentHash`,header:oe});return{yaml:C.yaml,contentHash:C.contentHash,packageName:C.packageName,publisher:C.publisher,rowCount:C.resourceCount}}resolveView(e,t){let n=U(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=I(n,so);if(o){let i=U(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of ke(t,uo)){let i=o instanceof y?o:o instanceof h?U(e,o.subject):void 0;if(!i)continue;let a=ge(i,mo),s=I(i,fo);a&&s&&n.push({value:a,as:s})}return n}async reason(e){return new he({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=ko(e),i=[],a=new Set;for(let s of n.getInstancesOfClass(t)){if(a.has(s))continue;a.add(s);let c=o.get(s);c&&i.push(c)}return i.sort((s,c)=>{let u=K(g(s)),p=K(g(c));return u<p?-1:u>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let a=await this.evaluateValue(e,t,i,o);if(!bo(a))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ue(n,"view-projection",{catalog:t,depth:0}),a=new Map([["input",o]]);return e.evaluate(i,a)}rowName(e,t){let n=V(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Pt(r){return Pe(r)?r.value:Array.isArray(r)?r.map(Pt):r}function yo(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function bt(r,e,t){let n=go(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function go(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let i=g(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||_(i.version,n)>0)&&(n=i.version)}return n?k(n):void 0}function ko(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let i=K(o),a=t.get(i);(!a||_(o.version,a)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function ho(r,e){let t=ge(r,e);return t?[t]:ke(r,e).filter(n=>n instanceof y)}function bo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Pe(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{Xr as AmbiguousReferenceRule,de as BooleanStatement,mt as CANONICAL_FORM_VERSION,F as Carrier,on as ClassDefinitionRule,zr as ClassHierarchyCycleRule,_t as CompositeKanonakDocumentRepository,Z as CredentialStore,se as DefinedKanonak,X as DeviceCertificateStore,Nt as DocumentLocation,mr as EdgeType,y as EmbeddedKanonak,Lr as EmbeddedKanonakTypeRule,fe as EmbeddedStatement,O as EntitlementDeniedError,te as EntitlementProducer,Ot as FileSystemKanonakDocumentRepository,br as GitIgnoreFilter,fr as GraphBuilder,Jt as HttpKanonakDocumentRepository,B as ImportBook,Mr as ImportExistenceRule,Vt as InMemoryKanonakDocumentRepository,Lt as KANONAK_USER_AGENT,Qt as Kanonak,wr as KanonakDocumentPositions,$ as KanonakObjectParser,sn as KanonakObjectValidator,x as KanonakParser,er as KanonakUri,vr as KanonakUriBuilder,Cr as KanonakUrlResolver,cr as KanonakVocabulary,ye as ListStatement,ce as LiteralKanonak,qt as LocalFirstRepository,Yt as LockAwareRepository,un as LookRenderer,an as MarkdownLinkRule,rr as MarkdownStatement,Yr as NamespaceImportCycleRule,Or as NamespacePrefixRule,dr as NodeType,pe as NumberStatement,kr as OWL_RL_CLASSIFICATION_RULES,en as ObjectPropertyValueValidationRule,Dr as OntologyValidationError,Ar as OntologyValidationResult,E as PackageBuilder,Fr as PackageHeaderRule,ee as ProducerRepository,tn as PropertyDomainRule,Wr as PropertyHierarchyCycleRule,rn as PropertyKindRangeConsistencyRule,Pr as PropertyMetadata,Qr as PropertyRangeReferenceRule,Gr as PropertyRangeRequiredRule,_r as PropertyTypeSpecificityRule,zt as PublisherConfigResolver,Wt as PublisherIndex,gr as RDFS_RULES,he as Reasoner,hr as ReasoningResult,h as ReferenceKanonak,me as ReferenceStatement,Ft as RepositoryFactory,nn as ReservedNameShadowRule,Nr as ResourceNamingRule,nr as ResourceResolver,pr as ResourceTypeClassifier,le as ScalarStatement,tr as Statement,ue as StringStatement,Jr as SubClassOfReferenceRule,qr as SubPropertyOfReferenceRule,f as SubjectKanonak,Ur as SubjectKanonakTypeRequiredRule,yr as TripleStore,or as TypeResolver,Zr as UnresolvedPredicateRule,Hr as UnresolvedReferenceRule,Vr as ValidationCache,Br as ValidationContext,Tr as ValidationSeverity,Ba as VersionOperator,re as ViewMaterializer,$e as allowAllPolicy,Gt as assertPackageIdentity,Xt as buildLocalFirstRepository,pn as buildOntologyModel,st as canonicalForm,Q as canonicalHash,Oe as carrierOf,Zt as collectKanonakFiles,_ as compareVersions,at as computeIntegrity,Ke as contentAddressedName,$r as contextTypesOf,tt as createAuthenticatedFetch,D as createDPoPProof,jt as createVersion,ur as extractMarkdownLinks,cn as findDerivation,jr as findInstancesByType,lr as findMalformedReferences,Rr as findMarkdownLinkAt,Er as formatKanonakAddress,k as formatVersion,Qe as generateDPoPKeyPair,Ut as getGlobalCachePath,Ht as getKanonakUserAgent,M as hasValidToken,Tt as isCompatibleVersion,L as isExpired,Dt as isMajorCompatible,R as kanonakFetch,ot as loadLockFile,ir as makeUriKey,je as noopMeter,l as normalizeHost,be as parseKanonakAddress,At as parseVersionString,Sr as parseWithPositions,Bt as pickHighestDocument,Ir as propertiesInScope,ln as resolveDisplayValue,Kr as resolvePropertyStep,V as sanitizeName,it as saveLockFile,et as serverSupportsDPoP,Mt as setKanonakUserAgent,g as subjectUri,xr as superClassChain,ar as tripleKey,K as uriKey,sr as uriTriple,Kt as versionOperatorFromChar,ae as versionOperatorToChar,$t as versionsEqual};
@@ -27,4 +27,16 @@ export declare abstract class DefinedKanonak extends Kanonak {
27
27
  * parser populates this where it would otherwise silently drop the property.
28
28
  */
29
29
  unresolvedPredicates: UnresolvedPredicate[];
30
+ /**
31
+ * Identifier (`publisher/package@version`) of the document that AUTHORED this
32
+ * kanonak. Set by the parser on every subject and (recursively) every embedded
33
+ * it builds. After the open-world merge folds several documents' assertions
34
+ * onto one subject URI, a subject's own `sourceDoc` is whichever loaded first,
35
+ * but each EMBEDDED retains the document that authored it — so a per-document
36
+ * rule can walk the single shared catalog and attribute an embedded back to its
37
+ * author (the same role {@link UnresolvedPredicate.sourceDoc} plays for
38
+ * predicates), instead of re-parsing the document on its own. Empty for a
39
+ * hand-built kanonak the parser never stamped.
40
+ */
41
+ sourceDoc: string;
30
42
  }
@@ -4,7 +4,9 @@ import { Kanonak } from '../kanonaks/Kanonak.js';
4
4
  import type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
5
5
  export declare class KanonakObjectParser implements IKanonakObjectParser {
6
6
  constructor(_kanonakParser?: IKanonakParser);
7
- parseKanonaks(documentRepository: IKanonakDocumentRepository): Promise<Kanonak[]>;
7
+ parseKanonaks(documentRepository: IKanonakDocumentRepository, out?: {
8
+ authored?: Kanonak[];
9
+ }): Promise<Kanonak[]>;
8
10
  /**
9
11
  * Walk a statement list, canonicalizing built-in URIs on every
10
12
  * predicate and reference target (recursing into embeddeds and list
@@ -62,6 +64,17 @@ export declare class KanonakObjectParser implements IKanonakObjectParser {
62
64
  */
63
65
  private parseSubstitutableValue;
64
66
  private parseObjectValue;
67
+ /**
68
+ * Build the embedded `tx.StringLiteral` that a `tx.Expression`-ranged object
69
+ * property's string value coerces to: `{ type: tx.StringLiteral,
70
+ * tx.stringLiteral: <value> }`. The `tx` URIs are stamped from the resolved
71
+ * range's coordinates (publisher/package/version) so they match the
72
+ * transformations version the property's range resolved to; the `type`
73
+ * predicate is the canonical `core-rdf/type`, re-canonicalized post-parse like
74
+ * every other built-in. Downstream (`TransformationLoaderV3`, `LookRenderer`)
75
+ * already reads this exact shape via `hasType(emb, TX_V3.StringLiteral)`.
76
+ */
77
+ private coerceExpressionLiteral;
65
78
  private parseListValue;
66
79
  /**
67
80
  * Resolve a bare name or aliased reference to a full ReferenceKanonak.
@@ -1 +1 @@
1
- import{a as c,b as d,c as e,d as f}from"../chunk-RGOBWOBB.js";import{h as b}from"../chunk-BKVPSPG4.js";import{a}from"../chunk-NJ3AZYQD.js";import"../chunk-7HRKWTBB.js";import"../chunk-4UT2CLAT.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.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-S6VSAKXB.js";import{l as b}from"../chunk-MX3DEXMV.js";import{a}from"../chunk-NJ3AZYQD.js";import"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
@@ -9,6 +9,17 @@ import type { Vocabulary } from './Vocabulary.js';
9
9
  * imported — and therefore must never be treated as an "unresolved predicate."
10
10
  */
11
11
  export declare function isBuiltinTerm(name: string): boolean;
12
+ /**
13
+ * The canonical home package of a reserved built-in term (`Class` → core-rdf,
14
+ * `ObjectProperty` → core-owl, `Package` → core-kanonak, …), or `undefined` for
15
+ * a non-built-in name. A package that defines a LOCAL entity with a built-in
16
+ * name whose home is a DIFFERENT package shadows the built-in — see the
17
+ * reserved-name shadow check.
18
+ */
19
+ export declare function builtinHome(name: string): {
20
+ publisher: string;
21
+ package_: string;
22
+ } | undefined;
12
23
  /**
13
24
  * Canonicalize a built-in URI in place against {@link BUILTIN_HOMES}.
14
25
  *
@@ -1 +1 @@
1
- import{a as g,b as h,c as i,d as j,e as k}from"../chunk-CR55WXIN.js";import"../chunk-BKVPSPG4.js";import"../chunk-NJ3AZYQD.js";import{d as a,e as b,f as c,h as d,j as e,k as f}from"../chunk-7HRKWTBB.js";import"../chunk-4UT2CLAT.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.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};
1
+ import{a as g,b as h,c as i,d as j,e as k}from"../chunk-TVSHIXLA.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import{c as a,d as b,e as c,g as d,j as e,k as f}from"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.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};
@@ -20,8 +20,4 @@ export declare class ResourceResolver {
20
20
  private findDocumentForAlias;
21
21
  clearCache(): void;
22
22
  clearCacheForDocument(documentKey: string): void;
23
- isSubclassOfAsync(className: string, parentClassName: string, document: KanonakDocument): Promise<boolean>;
24
- private isSubclassOfRecursiveAsync;
25
- isSubpropertyOfAsync(propertyName: string, parentPropertyName: string, document: KanonakDocument): Promise<boolean>;
26
- private isSubpropertyOfRecursiveAsync;
27
23
  }
@@ -1 +1 @@
1
- import{a as p,b as y}from"../chunk-PEUTCG3B.js";import{a as s}from"../chunk-PEJALHXK.js";import{a as k}from"../chunk-SC5M74NM.js";import{a as o,b as q,c as r,d as t,e as u,f as v,g as w,h as x}from"../chunk-IEOSSSB5.js";import"../chunk-7TKJHKC2.js";import{b as m,c as n}from"../chunk-7HRKWTBB.js";import"../chunk-4UT2CLAT.js";import{a as l}from"../chunk-FUUTGGJS.js";import{a,b,c,d,e,f,g,h,i,j}from"../chunk-2ACBWC7K.js";export{l as KanonakUri,p as KanonakUriBuilder,s as KanonakUrlResolver,m as ResourceResolver,o as ResourceTypeClassifier,n as TypeResolver,k as assertPackageIdentity,c as compareVersions,x as contextTypesOf,f as createVersion,y as findInstancesByType,r as formatKanonakAddress,e as formatVersion,h as isCompatibleVersion,i as isMajorCompatible,q as parseKanonakAddress,g as parseVersionString,j as pickHighestDocument,v as propertiesInScope,w as resolvePropertyStep,t as subjectUri,u as superClassChain,a as versionOperatorFromChar,b as versionOperatorToChar,d as versionsEqual};
1
+ import{a as p,b as y}from"../chunk-PEUTCG3B.js";import{a as s}from"../chunk-PEJALHXK.js";import{a as k}from"../chunk-SC5M74NM.js";import{a as o,b as q,c as r,d as t,e as u,f as v,g as w,h as x}from"../chunk-WFQANMBQ.js";import"../chunk-6U26UASC.js";import{a as m,b as n}from"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import{a as l}from"../chunk-FUUTGGJS.js";import{a,b,c,d,e,f,g,h,i,j}from"../chunk-2ACBWC7K.js";export{l as KanonakUri,p as KanonakUriBuilder,s as KanonakUrlResolver,m as ResourceResolver,o as ResourceTypeClassifier,n as TypeResolver,k as assertPackageIdentity,c as compareVersions,x as contextTypesOf,f as createVersion,y as findInstancesByType,r as formatKanonakAddress,e as formatVersion,h as isCompatibleVersion,i as isMajorCompatible,q as parseKanonakAddress,g as parseVersionString,j as pickHighestDocument,v as propertiesInScope,w as resolvePropertyStep,t as subjectUri,u as superClassChain,a as versionOperatorFromChar,b as versionOperatorToChar,d as versionsEqual};
@@ -1,4 +1,4 @@
1
- import{a as g}from"../chunk-V72IVYR4.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-BKVPSPG4.js";import"../chunk-NJ3AZYQD.js";import{d as m,h as S}from"../chunk-IEOSSSB5.js";import{a as p,f as E}from"../chunk-7TKJHKC2.js";import"../chunk-7HRKWTBB.js";import{c as v}from"../chunk-4UT2CLAT.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import{a as g}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import{d as m,h as S}from"../chunk-WFQANMBQ.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as v,m as p,r as E}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
2
2
  Install it with:
3
3
  npm install @huggingface/transformers
4
4
  (underlying import error: ${e.message})`)}return F({transformers:r})})()),y}function H(r,e){let t=0;for(let n=0;n<r.length;n++)t+=r[n]*e[n];return t}function R(r,e){return e?r.version?e.version?x(r.version,e.version)>0:!0:!1:!0}function K(r,e){let t=g(r,e),n=[t.label],s=S(e);if(s.length>0){let i=E(r,s[0]),a=i?g(r,i).label:s[0].name;a&&n.push(`\u2014 a ${a}.`)}return t.summary&&n.push(t.summary),n.join(" ")}function q(r){let e=new Map;for(let t of r){if(!(t instanceof v))continue;let n=m(t);if(!n)continue;let s=p(n),i=e.get(s);(!i||R(n,m(i)))&&e.set(s,t)}return[...e.values()].sort((t,n)=>{let s=m(t)?p(m(t)):t.name,i=m(n)?p(m(n)):n.name;return s.localeCompare(i)})}var k=class{entries=[];embedder;constructor(e={}){this.embedder=e.embedder}resolveEmbedder(){return this.embedder?Promise.resolve(this.embedder):U()}get size(){return this.entries.length}async build(e,t={}){let n=q(e);if(t.include&&(n=n.filter(t.include)),n.length===0)return this.entries=[],{size:0,cached:!1};let s=n.map(o=>K(e,o)),i=t.cacheDir,a;if(i){let o=C("sha256").update(h+"|"+w+`