@kanonak-protocol/sdk 4.3.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/chunk-7GAOBCNZ.js +1 -0
- package/dist/{chunk-JE4ZJ3OB.js → chunk-BH5TB6XY.js} +1 -1
- package/dist/chunk-EP7CJSV2.js +1 -0
- package/dist/{chunk-YWUKDEZA.js → chunk-FFMZ7GQM.js} +1 -1
- package/dist/{chunk-MJZSHLWI.js → chunk-FXFZZCCD.js} +1 -1
- package/dist/{chunk-HJQGBT7M.js → chunk-G7XXA2JL.js} +1 -1
- package/dist/chunk-KARUKDEM.js +86 -0
- package/dist/{chunk-YCV4H6H5.js → chunk-NNUV6K3C.js} +1 -1
- package/dist/{chunk-O27W3OKK.js → chunk-TC4MITSK.js} +1 -1
- package/dist/{chunk-NC3FSY3R.js → chunk-UK2OIPAB.js} +1 -1
- package/dist/{chunk-JSHJ4ZDB.js → chunk-UV6CLM2Y.js} +1 -1
- package/dist/chunk-VKTFLHCW.js +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +12 -12
- package/dist/parsing/KanonakParser.d.ts +15 -3
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/KanonakVocabulary.d.ts +15 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/resolution/index.js +1 -1
- package/dist/search/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/transformations/index.js +1 -1
- package/dist/validation/index.d.ts +1 -1
- package/dist/validation/index.js +1 -1
- package/dist/validation/rules/document/PackageHeaderRule.d.ts +24 -0
- package/dist/validation/rules/document/index.d.ts +1 -0
- package/package.json +2 -2
- package/dist/chunk-5DXJ5B5T.js +0 -84
- package/dist/chunk-CEFXZIHB.js +0 -1
- package/dist/chunk-XYEY6HUC.js +0 -1
- package/dist/chunk-ZYAABYDS.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as j,b as x,i as _}from"./chunk-
|
|
1
|
+
import{a as j,b as x,i as _}from"./chunk-7GAOBCNZ.js";import{d as l,e as u,f as b,g as $,h as s,j as h}from"./chunk-VKTFLHCW.js";import{c as S,d as O,g as I,h as T,i as g,j as v,k as L,l as q}from"./chunk-T3JR2SV6.js";var d=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=b(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),P(this.byPIdx,e.p,e),P(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&P(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(b(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let a of r)n.add(a.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let a of r)a.o.kind==="uri"&&n.add(a.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${$(r)}`)}};function P(o,e,t){let r=o.get(e);r?r.push(t):o.set(e,[t])}var w={name:"rdfs2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},C={name:"rdfs3",apply(o,e){let t=!1;for(let r of o.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,e.type,a))&&(t=!0)}return t}},A={name:"rdfs5",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subPropertyOf))i.o.kind==="uri"&&o.add(s(n,e.subPropertyOf,i.o.key))&&(t=!0)}return t}},V={name:"rdfs7",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n)){let f={s:i.s,p:a,o:i.o};o.add(f)&&(t=!0)}}return t}},W={name:"rdfs9",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},F={name:"rdfs11",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subClassOf))i.o.kind==="uri"&&o.add(s(n,e.subClassOf,i.o.key))&&(t=!0)}return t}},k=[w,C,A,V,W,F];var N={name:"prp-trp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let a=o.byPredicate(n);for(let i of a){if(i.o.kind!=="uri")continue;let f=i.o.key;for(let c of o.bySubjectPredicate(f,n))c.o.kind==="uri"&&i.s!==c.o.key&&o.add(s(i.s,n,c.o.key))&&(t=!0)}}return t}},D={name:"prp-symp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let a of o.byPredicate(n))a.o.kind==="uri"&&o.add(s(a.o.key,n,a.s))&&(t=!0);return t}},z={name:"prp-inv1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,a,i.s))&&(t=!0)}return t}},B={name:"prp-inv2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(a))i.o.kind==="uri"&&o.add(s(i.o.key,n,i.s))&&(t=!0)}return t}},M={name:"prp-eqp1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n))o.add({s:i.s,p:a,o:i.o})&&(t=!0)}return t}},G={name:"prp-eqp2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(a))o.add({s:i.s,p:n,o:i.o})&&(t=!0)}return t}},H={name:"cax-eqc1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},J={name:"cax-eqc2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,a))o.add(s(i.s,e.type,n))&&(t=!0)}return t}},Q={name:"eq-rep-s",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a){for(let i of o.snapshot())i.s===n&&o.add({s:a,p:i.p,o:i.o})&&(t=!0);for(let i of o.snapshot())i.s===a&&o.add({s:n,p:i.p,o:i.o})&&(t=!0)}}return t}},X={name:"eq-rep-o",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.snapshot())i.o.kind==="uri"&&(i.o.key===n?o.add(s(i.s,i.p,a))&&(t=!0):i.o.key===a&&o.add(s(i.s,i.p,n))&&(t=!0))}return t}},K=[N,D,z,B,M,G,H,J,Q,X];var y=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=p(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(p(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(p(e),this.vocabulary.type,p(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function p(o){return typeof o=="string"?o:u(o.publisher,o.package_,o.name)}var R=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new h,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new d,n=await new _().parseKanonaks(e),a=new U;for(let c of n)if(c instanceof S){let m=Y(c);if(!m)continue;for(let E of c.statement)this.emitStatement(m,E,t,a)}let i=[...k];this.profile==="owl-rl-classification"&&i.push(...K);let f=0;for(;f<this.maxIterations;){let c=!1;for(let m of i)m.apply(t,this.vocabulary)&&(c=!0);if(!c)break;f++}return new y(t,this.vocabulary)}emitStatement(e,t,r,n){let a=Z(t);if(a){if(t instanceof I){r.add({s:e,p:a,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof T){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof g){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof v){let i=l(t.object.subject);r.add(s(e,a,i));return}if(t instanceof L){let i=n.next();r.add({s:e,p:a,o:{kind:"blank",id:i}}),this.emitEmbedded(i,t.object,r,n);return}if(t instanceof q){for(let i of t.object??[])this.emitListItem(e,a,i,r,n);return}}}emitListItem(e,t,r,n,a){if(r instanceof O)n.add(s(e,t,l(r.subject)));else if(r instanceof j){let i=a.next();n.add({s:e,p:t,o:{kind:"blank",id:i}}),this.emitEmbedded(i,r,n,a)}else if(r instanceof x){let i=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:i}})}}emitEmbedded(e,t,r,n){let a=`_:${e}`;for(let i of t.statement)this.emitStatement(a,i,r,n)}},U=class{counter=0;next(){return`b${this.counter++}`}};function Y(o){let e=o.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let a=r.substring(0,n),i=r.substring(n+1);return!a||!i||!o.name?null:u(a,i,o.name)}function Z(o){let e=o.predicate;return e?.subject?l(e.subject):null}export{d as a,k as b,K as c,y as d,R as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u,f as _,j as g,k as d,m as j}from"./chunk-PBNVHBS3.js";import{i as m}from"./chunk-
|
|
1
|
+
import{a as u,f as _,j as g,k as d,m as j}from"./chunk-PBNVHBS3.js";import{i as m}from"./chunk-VKTFLHCW.js";import{c as U,d as S}from"./chunk-T3JR2SV6.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 m(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 m(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=d(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:g(o,x),comment:g(o,D),kind:y.isObjectPropertyType(s)?"object":y.isDatatypePropertyType(s)?"datatype":"other",range:d(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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as V}from"./chunk-
|
|
1
|
+
import{h as V}from"./chunk-7GAOBCNZ.js";import{a as E}from"./chunk-EP7CJSV2.js";var L=class{propertyUri;propertyType;range;rangeUri;isImported;definedInNamespace};import{parseDocument as O,LineCounter as R,isMap as h,isPair as f,isScalar as g,isSeq as I}from"yaml";var K=class i{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new i,n=new R,r=O(e,{lineCounter:n});if(r.errors.length>0||!h(r.contents))return t;N(r.contents,[],n,t);for(let o of r.contents.items){if(!f(o)||!g(o.key))continue;let a=String(o.key.value),u=o.key.range;if(!u)continue;t.entities.set(a,d(u,n));let s=o.value,c=s&&typeof s=="object"&&"range"in s?s.range:void 0;if(c?t.entityBlocks.set(a,d([u[0],u[1],c[2]],n)):t.entityBlocks.set(a,d(u,n)),h(o.value)){let k=new Map,m=new Map,l=new Map;for(let P of o.value.items){if(!f(P)||!g(P.key))continue;let b=String(P.key.value),p=P.key.range;p&&k.set(b,d(p,n));let S=P.value;if(S&&typeof S=="object"&&"range"in S&&Array.isArray(S.range)){let v=S.range;m.set(b,d(v,n))}if(I(S)){let v=[];for(let M of S.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&v.push(d(M.range,n));v.length>0&&l.set(b,v)}}k.size>0&&t.properties.set(a,k),m.size>0&&t.propertyValues.set(a,m),l.size>0&&t.valueListItems.set(a,l);let y=j(o.value,n);y.length>0&&t.importPackages.set(a,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[n,r]of this.entityBlocks)if(w(r,e,t))return n}findPropertyAtPosition(e,t){let n=this.findEntityAtPosition(e,t);if(!n)return;let r=this.properties.get(n),o=this.propertyValues.get(n);if(!r&&!o)return{entityName:n};let a,u;if(o)for(let[s,c]of o)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);if(r)for(let[s,c]of r)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);return a?{entityName:n,propertyName:a}:{entityName:n}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,n]of this.importPackages)for(let r of n)e.push({entityName:t,entry:r});return e}findPropertySourceName(e,t){let n=this.properties.get(e);if(n){if(n.has(t))return t;for(let r of n.keys()){let o=r.lastIndexOf(".");if((o===-1?r:r.substring(o+1))===t)return r}}}getListItemPosition(e,t,n){let r=this.valueListItems.get(e)?.get(t);if(!(!r||n<0||n>=r.length))return r[n]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,n){if(e){if(t!==void 0){if(n!==void 0){let a=this.getListItemPosition(e,t,n);if(a)return a}let r=this.getPropertyValuePosition(e,t);if(r)return r;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function j(i,e){let t=[];if(!h(i))return t;let n=i.items.find(r=>f(r)&&g(r.key)&&String(r.key.value)==="imports");if(!n||!f(n)||!I(n.value))return t;for(let r of n.value.items){if(!h(r))continue;let o=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="publisher");if(!o||!f(o)||!g(o.value))continue;let a=String(o.value.value),u=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="packages");if(!(!u||!f(u)||!I(u.value)))for(let s of u.value.items){if(!h(s))continue;let c=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="package");if(!c||!f(c)||!g(c.value)||!c.value.range)continue;let k=String(c.value.value),m=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="version"),l=m&&f(m)&&g(m.value)?String(m.value.value):"",y=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="alias"),P=y&&f(y)&&g(y.value)?String(y.value.value):void 0,b=P!==void 0?{publisher:a,package_:k,version:l,alias:P,position:d(c.value.range,e)}:{publisher:a,package_:k,version:l,position:d(c.value.range,e)};t.push(b)}}return t}function w(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function C(i,e){let t=i.endLine-i.line,n=e.endLine-e.line;if(t!==n)return t<n;let r=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return r<o}function N(i,e,t,n){if(h(i)){for(let r of i.items){if(!f(r)||!g(r.key))continue;let o=String(r.key.value),a=[...e,o],u=JSON.stringify(a);r.key.range&&n.setNestedKeyPosition(u,d(r.key.range,t));let s=r.value,c=D(s);c&&n.setNestedValuePosition(u,d(c,t)),N(s,a,t,n)}return}if(I(i)){for(let r=0;r<i.items.length;r++){let o=i.items[r],a=[...e,r],u=JSON.stringify(a),s=D(o);s&&n.setNestedValuePosition(u,d(s,t)),N(o,a,t,n)}return}}function D(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function d(i,e){let t=e.linePos(i[0]),n=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:n.line-1,endColumn:n.col-1}}function x(i,e){let n=(e??new E).parse(i),r=K.fromContent(i);return{document:n,positions:r}}function W(i,e,t,n,r){if(e<n.line||e>n.endLine||e===n.line&&t<n.column||e===n.endLine&&t>=n.endColumn)return;let o=A(r,n.line,n.column),a=A(r,n.endLine,n.endColumn);if(o<0||a<0)return;let u=r.substring(o,a),s=V(u);if(s.length!==i.links.length)return;let c=e-n.line,k=e===n.line?t-n.column:t,m=A(u,c,k);if(!(m<0))for(let l=0;l<s.length;l++){let y=s[l];if(m>=y.startOffset&&m<y.endOffset)return i.links[l]}}function A(i,e,t){let n=0,r=0;for(let o=0;o<i.length;o++){if(n===e)return Math.min(r+t,i.length);i[o]===`
|
|
2
2
|
`&&(n++,r=o+1)}return n===e?Math.min(r+t,i.length):-1}export{L as a,K as b,x as c,W as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as w}from"./chunk-FUUTGGJS.js";function K(n){if(Array.isArray(n))return n.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=n?.toString();return e?[e]:[]}var S=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let a=t.metadata?.namespace_?.toString()??"unknown",s=this.cache.get(a);if(s){let o=s.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"",new Map);return this.cache.set(a,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let a=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let s=e.split("."),r=s[0],o=s[1],g=await this.findDocumentForAlias(t,r);return g?await this.resolveAllEntitiesAsync(o,g):[]}return a.filter(s=>s.entityName===e)}async buildAllEntitiesIndexAsync(e,t,a){let s=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),s;t.add(r);let o=a.length===0?r:`${a} \u2192 ${r}`;for(let[g,u]of Object.entries(e.body))if(!g.includes(".")&&u&&typeof u=="object"&&!Array.isArray(u)){if(!e.metadata.namespace_)continue;let f=e.metadata.namespace_.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};s.push({entityName:g,uri:new w(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,g,f),entity:u,definedInNamespace:r,isImported:a.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${s.length} entities from ${r}`),e.metadata?.imports){let g=Object.values(e.metadata.imports).reduce((u,f)=>u+f.length,0);this.logger?.debug?.(`Processing ${g} import(s) for ${r}`);for(let[u,f]of Object.entries(e.metadata.imports))for(let d of f)try{this.logger?.debug?.(`Resolving import: ${u}/${d.packageName}`);let p=await this.repository.getHighestCompatibleVersionAsync(u,d);if(p){this.logger?.debug?.(`Successfully loaded import: ${p.metadata?.namespace_?.toString()}`);let m=await this.buildAllEntitiesIndexAsync(p,t,o);s.push(...m),this.logger?.debug?.(`Added ${m.length} entities from import ${p.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${u}/${d.packageName}`)}catch(p){let m=p;throw this.logger?.error?.(`Failed to process import ${u}/${d.packageName} for namespace ${r}. Error: ${m.message}`,m),new Error(`Failed to process import ${u}/${d.packageName} for namespace ${r}. See inner exception for details.`,{cause:p})}}return s}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"",new Map)}async buildEntityIndexAsyncInternal(e,t,a,s){let r=new Map,o=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${o}`),t.has(o))return this.logger?.debug?.(`Skipping ${o} - circular import in progress`),r;let g=s.get(o);if(g)return g;t.add(o);let u=a.length===0?o:`${a} \u2192 ${o}`,f=0;for(let[d,p]of Object.entries(e.body))if(!d.includes(".")&&p&&typeof p=="object"&&!Array.isArray(p)){if(!e.metadata.namespace_)continue;if(!r.has(d)){let m=e.metadata.namespace_.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};r.set(d,{entityName:d,uri:new w(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,d,m),entity:p,definedInNamespace:o,isImported:a.length>0,importPath:u}),f++}}if(this.logger?.debug?.(`Indexed ${f} entities from ${o}`),e.metadata?.imports){let d=Object.values(e.metadata.imports).reduce((p,m)=>p+m.length,0);this.logger?.debug?.(`Processing ${d} import(s) for ${o}`);for(let[p,m]of Object.entries(e.metadata.imports))for(let h of m)try{this.logger?.debug?.(`Resolving import: ${p}/${h.packageName}`);let k=await this.repository.getHighestCompatibleVersionAsync(p,h);if(k){this.logger?.debug?.(`Successfully loaded import: ${k.metadata?.namespace_?.toString()}`);let P=await this.buildEntityIndexAsyncInternal(k,t,u,s),v=0;for(let[$,R]of P.entries()){let b=r.get($);if(!b)r.set($,R),v++;else if(b.isImported&&R.isImported&&(b.uri.publisher!==R.uri.publisher||b.uri.package_!==R.uri.package_)){let A=b.isAmbiguous?b:{...b,isAmbiguous:!0,ambiguousNamespaces:[b.definedInNamespace]};A.ambiguousNamespaces.includes(R.definedInNamespace)||A.ambiguousNamespaces.push(R.definedInNamespace),r.set($,A),this.logger?.warn?.(`Ambiguous reference '${$}': defined in ${A.ambiguousNamespaces.join(", ")}`)}if(h.alias&&!$.includes(".")){let A=`${h.alias}.${$}`;r.has(A)||(r.set(A,R),v++)}}this.logger?.debug?.(`Merged ${v} entities from import ${k.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${p}/${h.packageName}`)}catch(k){let P=k;throw this.logger?.error?.(`Failed to process import ${p}/${h.packageName} for namespace ${o}. Error: ${P.message}`,P),new Error(`Failed to process import ${p}/${h.packageName} for namespace ${o}. See inner exception for details.`,{cause:k})}}return t.delete(o),s.set(o,r),r}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[a,s]of Object.entries(e.metadata.imports))for(let r of s){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(a,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(a,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,a){if(e===t)return!0;let s=new Set;return await this.isSubclassOfRecursiveAsync(e,t,a,s)}async isSubclassOfRecursiveAsync(e,t,a,s){if(s.has(e))return!1;s.add(e);let r=await this.resolveEntityAsync(e,a);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let g=K(o);for(let u of g)if(u===t||await this.isSubclassOfRecursiveAsync(u,t,a,s))return!0}return!1}async isSubpropertyOfAsync(e,t,a){if(e===t)return!0;let s=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,a,s)}async isSubpropertyOfRecursiveAsync(e,t,a,s){if(s.has(e))return!1;s.add(e);let r=await this.resolveEntityAsync(e,a);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let g=K(o);for(let u of g)if(u===t||await this.isSubpropertyOfRecursiveAsync(u,t,a,s))return!0}return!1}};var D=class n{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-xsd"&&n.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-rdf"&&e.name==="Literal":!1}isMarkdownDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-prose"&&e.name==="Markdown":!1}isSubstitutableDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core-prose"&&(e.name==="SubstitutableString"||e.name==="Markdown"):!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return n.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let a=await this.resourceResolver.resolveEntityAsync(e,t);if(a){let s=a.entity.type;if(s){let r=String(s);return r==="Class"||r==="rdfs.Class"||r.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};function L(n){return`${n.publisher}/${n.package_}/${n.name}`}function c(n,e,t){return`${n}/${e}/${t}`}function M(n){return`${n.s}|${n.p}|${x(n.o)}`}function x(n){switch(n.kind){case"uri":return`u:${n.key}`;case"literal":return`l:${n.datatype}:${n.lexical}`;case"blank":return`b:${n.id}`}}function F(n,e,t){return{s:n,p:e,o:{kind:"uri",key:t}}}var l="kanonak.org",i="core-rdf",y="core-owl",_="core-kanonak",I=new Map([["type",i],["subClassOf",i],["subPropertyOf",i],["domain",i],["range",i],["label",i],["comment",i],["seeAlso",i],["isDefinedBy",i],["member",i],["Resource",i],["Class",i],["Property",i],["Datatype",i],["Literal",i],["List",i],["ObjectProperty",y],["DatatypeProperty",y],["AnnotationProperty",y],["Thing",y],["Nothing",y],["Package",_]]),E=new Set(["type","subClassOf","subPropertyOf","domain","range"]);function X(n,e,t){if(!n||!n.name)return;let a=I.get(n.name);if(!a)return;let s=()=>{n.publisher=l,n.package_=a,t&&(n.version=t.get(a))};if(E.has(n.name)){let r=n.publisher===l&&n.package_===a;n.publisher=l,n.package_=a,!r&&t&&(n.version=t.get(a));return}n.publisher===l&&n.package_===a||n.publisher&&n.publisher.length>0&&(!e||e(n))||s()}var O=class{type=c(l,i,"type");subClassOf=c(l,i,"subClassOf");subPropertyOf=c(l,i,"subPropertyOf");domain=c(l,i,"domain");range=c(l,i,"range");label=c(l,i,"label");comment=c(l,i,"comment");resource=c(l,i,"Resource");class_=c(l,i,"Class");datatype=c(l,i,"Datatype");literal=c(l,i,"Literal");equivalentClass=c(l,y,"equivalentClass");equivalentProperty=c(l,y,"equivalentProperty");inverseOf=c(l,y,"inverseOf");sameAs=c(l,y,"sameAs");transitiveProperty=c(l,y,"TransitiveProperty");symmetricProperty=c(l,y,"SymmetricProperty");objectProperty=c(l,y,"ObjectProperty");datatypeProperty=c(l,y,"DatatypeProperty");annotationProperty=c(l,y,"AnnotationProperty");package_=c(l,_,"Package")};export{K as a,S as b,D as c,L as d,c as e,M as f,x as g,F as h,X as i,O as j};
|
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, EmbeddedKanonakTypeRule, ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, InstancePropertyReferenceRule, 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, InstancePropertyReferenceRule, DefinitionPropertyReferenceRule, XsdImportRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyImportRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyValueTypeRule, 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 bn,b as Pn,c as wn,d as Sn,e as be}from"./chunk-
|
|
1
|
+
import{a as bn,b as Pn,c as wn,d as Sn,e as be}from"./chunk-TC4MITSK.js";import{a as fr,c as Ce,e as He,h as ze,i as We,j as yr}from"./chunk-BH5TB6XY.js";import{a as gn,b as hn,c as kn,d as W,e as G,f as l,g as gr}from"./chunk-FXFZZCCD.js";import{a as mr}from"./chunk-G7XXA2JL.js";import"./chunk-QHABFCRC.js";import{a as zt,b as Wt,c as Gt,d as Jt,e as qt,f as en,g as tn,h as nn}from"./chunk-FFMZ7GQM.js";import{b as Yt,c as Zt,d as Qt}from"./chunk-NNUV6K3C.js";import{a as Ht}from"./chunk-4NO7MHS7.js";import{a as Rn,b as En,c as xn,d as In}from"./chunk-UV6CLM2Y.js";import{a as vn,b as On}from"./chunk-PEUTCG3B.js";import{a as $n}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as cr,B as lr,C as ur,D as pr,M as dr,a as Dn,b as Nn,c as Tn,d as _n,e as Ln,f as Un,g as Fn,h as Mn,i as Hn,j as zn,k as Wn,l as Gn,m as Jn,n as qn,o as Yn,p as Zn,q as Xn,r as Qn,s as er,t as tr,u as nr,v as rr,w as or,x as ar,y as ir,z as sr}from"./chunk-KARUKDEM.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as C,c as an,d as Fe,e as v,f as ke,g as mn,h as fn,i as $}from"./chunk-7GAOBCNZ.js";import{a as S}from"./chunk-EP7CJSV2.js";import{a as yn,b as Pe,c as Kn,d as h,e as jn,f as Vn,g as An,h as Bn}from"./chunk-UK2OIPAB.js";import{f as z,k as j,l as we,m as Se,n as Me}from"./chunk-PBNVHBS3.js";import{b as sn,c as cn,d as K,e as ln,f as un,h as pn,j as dn}from"./chunk-VKTFLHCW.js";import{a as rn,b as fe,c as f,d as p,e as on,f as ye,g as R,h as ge,i as he,j as E,k as x,l as I}from"./chunk-T3JR2SV6.js";import{a as H}from"./chunk-FUUTGGJS.js";import{a as Nt,b as me,c as M,d as Tt,e as k,f as _t,g as Lt,h as Ut,i as Ft,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Cn}from"./chunk-ODIECDN7.js";import{VersionOperator as Di}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Br,readFileSync as Or}from"fs";import{homedir as Dr}from"os";import{join as Nr}from"path";import{execFile as hr}from"child_process";import{promisify as kr}from"util";var J=kr(hr),q="kanonak",Y="/usr/bin/security",V=class{async get(e){let t=l(e);try{let{stdout:r}=await J(Y,["find-generic-password","-s",q,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.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(r){if(Ge(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${Z(r)}
|
|
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 r=l(e),o=JSON.stringify(t);try{await J(Y,["add-generic-password","-s",q,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${Z(a)}
|
|
5
5
|
Ensure the Keychain is unlocked and the CLI has write permission.
|
|
6
6
|
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await J(Y,["delete-generic-password","-s",q,"-a",t],{timeout:1e4})}catch(r){if(Ge(r,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${Z(r)}
|
|
7
7
|
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await J(Y,["dump-keychain"],{timeout:1e4}),t=[],r=!1;for(let o of e.split(`
|
|
8
|
-
`))if(o.includes(`"svce"<blob>="${q}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${Z(e)}`),[]}}};function Ge(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function Z(n){return n instanceof Error?n.message:String(n)}import{execFile as
|
|
8
|
+
`))if(o.includes(`"svce"<blob>="${q}"`)&&(r=!0),r&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),r=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${Z(e)}`),[]}}};function Ge(n,e){return typeof n=="object"&&n!==null&&"code"in n&&n.code===e}function Z(n){return n instanceof Error?n.message:String(n)}import{execFile as br}from"child_process";import{promisify as Pr}from"util";var wr=Pr(br),X="kanonak:",A=class{async get(e){let t=X+l(e),r=`
|
|
9
9
|
${ee}
|
|
10
10
|
$target = [Console]::In.ReadLine()
|
|
11
11
|
$ptr = [IntPtr]::Zero
|
|
@@ -41,7 +41,7 @@ ${ee}
|
|
|
41
41
|
$target = [Console]::In.ReadLine()
|
|
42
42
|
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await Q(r,t)}catch{}}async list(){let e=`
|
|
43
43
|
${ee}
|
|
44
|
-
${
|
|
44
|
+
${Sr}
|
|
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 Q(e,X);return t.trim().split(`
|
|
59
|
-
`).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function Q(n,e){for(let t of["pwsh","powershell"])try{return await
|
|
59
|
+
`).map(r=>r.trim()).filter(Boolean)}catch{return[]}}};async function Q(n,e){for(let t of["pwsh","powershell"])try{return await wr(t,["-NoProfile","-NonInteractive","-Command",n],{timeout:15e3,...e!==void 0&&{input:e}})}catch(r){if(t==="powershell")throw r}throw new Error("Neither pwsh nor powershell found")}var ee=`
|
|
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
|
-
"@`,
|
|
91
|
-
`)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Re(){try{return await ne("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Je,mkdirSync as qe,readFileSync as Ye,writeFileSync as Ze}from"fs";import{createCipheriv as
|
|
90
|
+
"@`,Sr="";import{execFile as Cr,spawn as Rr}from"child_process";import{promisify as Er}from"util";var ne=Er(Cr),te="kanonak",B=class{async get(e){let t=l(e);try{let{stdout:r}=await ne("secret-tool",["lookup","service",te,"publisher",t],{timeout:1e4}),o=r.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let r=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Rr("secret-tool",["store","--label",`Kanonak: ${r}`,"service",te,"publisher",r],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(e);try{await ne("secret-tool",["clear","service",te,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await ne("secret-tool",["search","service",te],{timeout:1e4}),t=[];for(let r of e.split(`
|
|
91
|
+
`)){let o=r.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Re(){try{return await ne("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Je,mkdirSync as qe,readFileSync as Ye,writeFileSync as Ze}from"fs";import{createCipheriv as xr,createDecipheriv as Ir,randomBytes as Xe}from"crypto";import{homedir as vr}from"os";import{join as Ie,dirname as Qe}from"path";var tt=Ie(vr(),".config","kanonak"),O=Ie(tt,"keyring.key"),re=Ie(tt,"credentials.enc"),et="aes-256-gcm",Ee=32,b=12,xe=16,D=class{async get(e){let t=this.loadStore(),r=l(e);return t[r]??null}async store(e,t){let r=this.loadStore(),o=l(e);r[o]=t,this.saveStore(r)}async remove(e){let t=this.loadStore(),r=l(e);delete t[r],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Je(re))return{};try{let e=this.getOrCreateKey(),t=Ye(re);if(t.length<b+xe)return{};let r=t.subarray(0,b),o=t.subarray(b,b+xe),a=t.subarray(b+xe),i=Ir(et,e,r);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),r=Xe(b),o=xr(et,t,r),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([r,s,i]);qe(Qe(re),{recursive:!0}),Ze(re,c,{mode:384})}getOrCreateKey(){if(Je(O)){let t=Ye(O);if(t.length!==Ee)throw new Error(`Credential keyring key is corrupted (expected ${Ee} bytes, got ${t.length}). Delete ${O} and re-authenticate.`);return t}let e=Xe(Ee);return qe(Qe(O),{recursive:!0}),Ze(O,e,{mode:384}),e}};import{execFile as Kr}from"child_process";import{promisify as $r}from"util";var jr=$r(Kr),nt=3e4,N=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(r){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${oe(r)}
|
|
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 r=l(e);try{await this.runHelper("store",{publisher:r,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${r}': ${oe(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(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${oe(r)}`)}}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: ${oe(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await
|
|
95
|
-
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):
|
|
96
|
-
The helper may be waiting for authentication to an external vault.`):r}}};function oe(n){return n instanceof Error?n.message:String(n)}function
|
|
97
|
-
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as
|
|
98
|
-
The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as
|
|
99
|
-
`;function lt(n=ct){if(!Gr(n))return null;let e=zr(n,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(n,e=ct){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=st.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Wr(e,qr+r,"utf-8")}function pt(n){return`sha256:${Jr("sha256").update(n).digest("hex")}`}import*as Ae from"js-yaml";import{createHash as Zr}from"crypto";function Ke(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function $e(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>mt(o.predicate,o.value)),t})}function dt(n,e,t){let r=new R;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function mt(n,e){if("lit"in e)return dt(n,v(H.parse(e.datatype)),e.lit);if("raw"in e)return dt(n,void 0,e.raw);if("ref"in e){let t=new E;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new x;return t.predicate=p.parse(n),t.object=ft(e.embed),t}if("list"in e){let t=new I;return t.predicate=p.parse(n),t.object=e.list.map(Yr),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function ft(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>mt(t.predicate,t.value)),e}function Yr(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return ft(n.embed);let e=new C;if("lit"in n){e.value=n.lit;let t=v(H.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var gt="1",yt=new TextEncoder;function ht(n,e){let t=yt.encode(n),r=yt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function je(n){let e=Ke(n)?$e(n):n,t=[];for(let o of e)o instanceof f&&t.push(Xr(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function ie(n){let e=Ke(n)?$e(n):n,t=je(e);return`sha256:${Zr("sha256").update(t,"utf8").digest("hex")}`}function Xr(n){let e=oo(n),t=Ve(n.statement);return{uri:e,statements:t}}function Ve(n){let e=[];for(let t of n){let r=Qr(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function Qr(n){let e=ro(n);if(!e)return;let t=eo(n);if(t)return no(e,t)}function eo(n){if(n instanceof ye&&n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.object))};if(n instanceof R)return{type:"string",value:n.object};if(n instanceof ge)return{type:"number",value:wt(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof E)return{type:"ref",value:bt(n.object)};if(n instanceof x){let e=n.object;return kt(e)}if(n instanceof I)return{type:"list",items:n.object.map(to)}}function kt(n){let e=Ve(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function to(n){if(n instanceof p)return{type:"ref",value:bt(n)};if(n instanceof y)return kt(n);if(n instanceof C){if(n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:wt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof fe)return{type:"embedded",statements:Ve(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function no(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function ro(n){let e=n.predicate;if(e)return Pt(e.subject)}function oo(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bt(n){return Pt(n.subject)}function Pt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function wt(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as St}from"@kanonak-protocol/types/document/models/enums";var ao="0.0.0",P=class{constructor(e,t=new S,r){this.repository=e;this.parser=t;this.objectParser=r??new $(this.parser)}repository;parser;objectParser;imports(){return new _}serializeValue(e,t){return Et(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Be(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Rt(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Rt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ae.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Ae.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Me(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Ct);for(let u of c)u.namespace="ephemeral";return ie(c)}},Ct="__pkgbuilder_probe__";function Rt(n){return new TextEncoder().encode(n).length}function Be(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var _=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=St.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),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,r,o){return`${this.ensure(e,t,ao,o??t,St.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:me(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=L(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function Et(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>Et(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n 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(io(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function L(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function io(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var se=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${k(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=Pe(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.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 Oe={async authorize(){return{allowed:!0}}},De={async record(){}},U=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},ce=class{inner;ctx;policy;meter;constructor(e,t,r=Oe,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new U(e,t.reason)}};var m="kanonak.org",g="view",xt="core-kanonak",so={publisher:m,package_:g,name:"rootView"},co={publisher:m,package_:g,name:"bind"},lo={publisher:m,package_:g,name:"produces"},uo={publisher:m,package_:g,name:"projections"},po={publisher:m,package_:g,name:"where"},mo={publisher:m,package_:g,name:"value"},fo={publisher:m,package_:g,name:"as"},le=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new P(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=j(o,co);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=j(o,lo);if(!i)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=It(r,m,xt),u=It(r,m,g),d=this.builder.imports(),ue=d.ensure(m,xt,c,"ck"),Kt=d.ensure(m,g,u,"v"),$t=d.ref(i),jt=new We(this.repository,this.parser,this.objectParser),Ne=new He(jt,r),Vt=this.readProjections(r,o),At=ko(o,po),Bt=this.findInstances(r,a,await this.reason(t)),Te={},Ot=new Set;for(let F of Bt){if(!await this.passesWhere(Ne,r,At,F))continue;let de={type:$t};for(let Le of Vt){let Dt=await this.evaluateValue(Ne,r,Le.value,F),Ue=this.builder.serializeValue(vt(Dt),d);Ue!==void 0&&(de[d.ref(Le.as)]=Ue)}let _e=h(F);_e&&(de[`${Kt}.derivedFrom`]=d.ref(_e)),Te[this.rowName(F,Ot)]=de}let pe={};t.resolvedAt&&(pe[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(pe[`${ue}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:Te,contentHashProperty:`${ue}.contentHash`,header:pe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let r=z(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=j(r,so);if(o){let a=z(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Se(t,uo)){let a=o instanceof y?o:o instanceof p?z(e,o.subject):void 0;if(!a)continue;let i=we(a,mo),s=j(a,fo);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=ho(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=K(h(s)),d=K(h(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!bo(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=ze(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=L(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function vt(n){return Ce(n)?n.value:Array.isArray(n)?n.map(vt):n}function yo(n){let e=h(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function It(n,e,t){let r=go(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function go(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=h(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||M(a.version,r)>0)&&(r=a.version)}return r?k(r):void 0}function ho(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=h(r);if(!o||!o.version)continue;let a=K(o),i=t.get(a);(!i||M(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function ko(n,e){let t=we(n,e);return t?[t]:Se(n,e).filter(r=>r instanceof y)}function bo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ce(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{rr as AmbiguousReferenceRule,he as BooleanStatement,gt as CANONICAL_FORM_VERSION,Fe as Carrier,lr as ClassDefinitionRule,Jn as ClassHierarchyCycleRule,Gt as CompositeKanonakDocumentRepository,ae as CredentialStore,fe as DefinedKanonak,tr as DefinitionPropertyReferenceRule,Wt as DocumentLocation,hn as EdgeType,y as EmbeddedKanonak,zn as EmbeddedKanonakTypeRule,x as EmbeddedStatement,U as EntitlementDeniedError,ce as EntitlementProducer,zt as FileSystemKanonakDocumentRepository,Cn as GitIgnoreFilter,kn as GraphBuilder,Qt as HttpKanonakDocumentRepository,_ as ImportBook,Wn as ImportExistenceRule,Ht as InMemoryKanonakDocumentRepository,er as InstancePropertyReferenceRule,rn as Kanonak,En as KanonakDocumentPositions,$ as KanonakObjectParser,pr as KanonakObjectValidator,S as KanonakParser,H as KanonakUri,vn as KanonakUriBuilder,$n as KanonakUrlResolver,dn as KanonakVocabulary,I as ListStatement,C as LiteralKanonak,en as LocalFirstRepository,fr as LookRenderer,ur as MarkdownLinkRule,an as MarkdownStatement,Qn as NamespaceImportCycleRule,Un as NamespacePrefixRule,gn as NodeType,ge as NumberStatement,wn as OWL_RL_CLASSIFICATION_RULES,ar as ObjectPropertyImportRule,ir as ObjectPropertyValueValidationRule,Tn as OntologyValidationError,Dn as OntologyValidationResult,P as PackageBuilder,se as ProducerRepository,sr as PropertyDomainRule,qn as PropertyHierarchyCycleRule,Rn as PropertyMetadata,or as PropertyRangeReferenceRule,Yn as PropertyRangeRequiredRule,Mn as PropertyTypeSpecificityRule,cr as PropertyValueTypeRule,Yt as PublisherConfigResolver,Zt as PublisherIndex,Pn as RDFS_RULES,be as Reasoner,Sn as ReasoningResult,p as ReferenceKanonak,E as ReferenceStatement,qt as RepositoryFactory,Fn as ResourceNamingRule,sn as ResourceResolver,yn as ResourceTypeClassifier,ye as ScalarStatement,on as Statement,R as StringStatement,Zn as SubClassOfReferenceRule,Xn as SubPropertyOfReferenceRule,f as SubjectKanonak,Hn as SubjectKanonakTypeRequiredRule,bn as TripleStore,cn as TypeResolver,Gn as UnresolvedReferenceRule,Ln as ValidationCache,_n as ValidationContext,Nn as ValidationSeverity,Oi as VersionOperator,le as ViewMaterializer,nr as XsdImportRule,Oe as allowAllPolicy,Xt as assertPackageIdentity,nn as buildLocalFirstRepository,yr as buildOntologyModel,je as canonicalForm,ie as canonicalHash,v as carrierOf,tn as collectKanonakFiles,M as compareVersions,pt as computeIntegrity,Be as contentAddressedName,Bn as contextTypesOf,it as createAuthenticatedFetch,T as createDPoPProof,_t as createVersion,fn as extractMarkdownLinks,dr as findDerivation,On as findInstancesByType,mn as findMalformedReferences,In as findMarkdownLinkAt,Kn as formatKanonakAddress,k as formatVersion,ot as generateDPoPKeyPair,Jt as getGlobalCachePath,G as hasValidToken,Ut as isCompatibleVersion,W as isExpired,Ft as isMajorCompatible,lt as loadLockFile,ln as makeUriKey,De as noopMeter,l as normalizeHost,Pe as parseKanonakAddress,Lt as parseVersionString,xn as parseWithPositions,Mt as pickHighestDocument,Vn as propertiesInScope,mr as resolveDisplayValue,An as resolvePropertyStep,L as sanitizeName,ut as saveLockFile,at as serverSupportsDPoP,h as subjectUri,jn as superClassChain,un as tripleKey,K as uriKey,pn as uriTriple,Nt as versionOperatorFromChar,me as versionOperatorToChar,Tt 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(r){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${oe(r)}`)}}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: ${oe(e)}`),[]}}async runHelper(e,t){try{let{stdout:r}=await jr(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:nt});return r}catch(r){throw Vr(r)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
95
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Ar(r)?new Error(`Credential helper '${this.helperPath}' timed out after ${nt/1e3}s on '${e}'.
|
|
96
|
+
The helper may be waiting for authentication to an external vault.`):r}}};function oe(n){return n instanceof Error?n.message:String(n)}function Vr(n){return n instanceof Error&&"code"in n&&n.code==="ENOENT"}function Ar(n){return n instanceof Error&&"killed"in n&&n.killed}var ve=Nr(Dr(),".kanonak","config.json"),ae=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=Tr(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!G(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=_r();return e.credentialHelper?new N(e.credentialHelper):process.platform==="darwin"?new V:process.platform==="win32"?new A:await Re()?new B:new D}};function Tr(n){let t="KANONAK_TOKEN_"+l(n).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function _r(){if(!Br(ve))return{};try{return JSON.parse(Or(ve,"utf-8"))}catch(n){let e=n instanceof Error?n.message:String(n);return console.warn(` Warning: Failed to parse ${ve}: ${e}
|
|
97
|
+
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Lr,createPrivateKey as Ur,generateKeyPairSync as Fr,randomUUID as Mr,sign as Hr}from"crypto";function ot(){let{publicKey:n,privateKey:e}=Fr("ec",{namedCurve:"P-256"});return{publicKey:n.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function T(n,e,t,r,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Mr(),htm:t.toUpperCase(),htu:r,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Lr("sha256").update(o).digest("base64url")),a&&(s.nonce=a),zr(i,s,n)}function at(n){return!n||n.length===0?!1:n.some(e=>e.toUpperCase()==="ES256")}function zr(n,e,t){let r=rt(JSON.stringify(n)),o=rt(JSON.stringify(e)),a=`${r}.${o}`,i=Ur({key:t,format:"jwk"}),c=Hr("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function rt(n){return Buffer.from(n,"utf-8").toString("base64url")}function it(n){let e=new Map;return async(t,r,o="GET")=>{if(!n)return fetch(t,{method:o});let a=await n.getCredential(r);if(!a?.accessToken)return fetch(t,{method:o});W(a)&&console.warn(` Warning: Access token for '${r}' is expired. Run 'kanonak login ${r}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(r);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let d=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${r}': ${d}
|
|
98
|
+
The stored key pair may be corrupted. Run 'kanonak login ${r}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await fetch(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(r,c);try{let u=T(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await fetch(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as Wr,writeFileSync as Gr,existsSync as Jr}from"fs";import{createHash as qr}from"crypto";import st from"js-yaml";var ct="kanonak.lock",Yr=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
99
|
+
`;function lt(n=ct){if(!Jr(n))return null;let e=Wr(n,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(n,e=ct){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=st.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Gr(e,Yr+r,"utf-8")}function pt(n){return`sha256:${qr("sha256").update(n).digest("hex")}`}import*as Ae from"js-yaml";import{createHash as Xr}from"crypto";function Ke(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function $e(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>mt(o.predicate,o.value)),t})}function dt(n,e,t){let r=new R;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function mt(n,e){if("lit"in e)return dt(n,v(H.parse(e.datatype)),e.lit);if("raw"in e)return dt(n,void 0,e.raw);if("ref"in e){let t=new E;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new x;return t.predicate=p.parse(n),t.object=ft(e.embed),t}if("list"in e){let t=new I;return t.predicate=p.parse(n),t.object=e.list.map(Zr),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function ft(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>mt(t.predicate,t.value)),e}function Zr(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return ft(n.embed);let e=new C;if("lit"in n){e.value=n.lit;let t=v(H.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var gt="1",yt=new TextEncoder;function ht(n,e){let t=yt.encode(n),r=yt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function je(n){let e=Ke(n)?$e(n):n,t=[];for(let o of e)o instanceof f&&t.push(Qr(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function ie(n){let e=Ke(n)?$e(n):n,t=je(e);return`sha256:${Xr("sha256").update(t,"utf8").digest("hex")}`}function Qr(n){let e=ao(n),t=Ve(n.statement);return{uri:e,statements:t}}function Ve(n){let e=[];for(let t of n){let r=eo(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function eo(n){let e=oo(n);if(!e)return;let t=to(n);if(t)return ro(e,t)}function to(n){if(n instanceof ye&&n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.object))};if(n instanceof R)return{type:"string",value:n.object};if(n instanceof ge)return{type:"number",value:wt(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof E)return{type:"ref",value:bt(n.object)};if(n instanceof x){let e=n.object;return kt(e)}if(n instanceof I)return{type:"list",items:n.object.map(no)}}function kt(n){let e=Ve(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function no(n){if(n instanceof p)return{type:"ref",value:bt(n)};if(n instanceof y)return kt(n);if(n instanceof C){if(n.carrier)return{type:"typed",carrier:n.carrier,value:ke(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:wt(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof fe)return{type:"embedded",statements:Ve(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function ro(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function oo(n){let e=n.predicate;if(e)return Pt(e.subject)}function ao(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function bt(n){return Pt(n.subject)}function Pt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function wt(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as St}from"@kanonak-protocol/types/document/models/enums";var io="0.0.0",P=class{constructor(e,t=new S,r){this.repository=e;this.parser=t;this.objectParser=r??new $(this.parser)}repository;parser;objectParser;imports(){return new _}serializeValue(e,t){return Et(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Be(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Rt(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Rt(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ae.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Ct]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Ae.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Me(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Ct);for(let u of c)u.namespace="ephemeral";return ie(c)}},Ct="__pkgbuilder_probe__";function Rt(n){return new TextEncoder().encode(n).length}function Be(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var _=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=St.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),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,r,o){return`${this.ensure(e,t,io,o??t,St.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:me(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=L(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function Et(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>Et(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n 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(so(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function L(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function so(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var se=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${k(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=Pe(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.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 Oe={async authorize(){return{allowed:!0}}},De={async record(){}},U=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},ce=class{inner;ctx;policy;meter;constructor(e,t,r=Oe,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new U(e,t.reason)}};var m="kanonak.org",g="view",xt="core-kanonak",co={publisher:m,package_:g,name:"rootView"},lo={publisher:m,package_:g,name:"bind"},uo={publisher:m,package_:g,name:"produces"},po={publisher:m,package_:g,name:"projections"},mo={publisher:m,package_:g,name:"where"},fo={publisher:m,package_:g,name:"value"},yo={publisher:m,package_:g,name:"as"},le=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new P(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=j(o,lo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=j(o,uo);if(!i)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=go(o),c=It(r,m,xt),u=It(r,m,g),d=this.builder.imports(),ue=d.ensure(m,xt,c,"ck"),Kt=d.ensure(m,g,u,"v"),$t=d.ref(i),jt=new We(this.repository,this.parser,this.objectParser),Ne=new He(jt,r),Vt=this.readProjections(r,o),At=bo(o,mo),Bt=this.findInstances(r,a,await this.reason(t)),Te={},Ot=new Set;for(let F of Bt){if(!await this.passesWhere(Ne,r,At,F))continue;let de={type:$t};for(let Le of Vt){let Dt=await this.evaluateValue(Ne,r,Le.value,F),Ue=this.builder.serializeValue(vt(Dt),d);Ue!==void 0&&(de[d.ref(Le.as)]=Ue)}let _e=h(F);_e&&(de[`${Kt}.derivedFrom`]=d.ref(_e)),Te[this.rowName(F,Ot)]=de}let pe={};t.resolvedAt&&(pe[`${ue}.resolvedAt`]=t.resolvedAt),t.invocationId&&(pe[`${ue}.id`]=t.invocationId);let w=await this.builder.buildContentAddressed({publisher:s,book:d,body:Te,contentHashProperty:`${ue}.contentHash`,header:pe});return{yaml:w.yaml,contentHash:w.contentHash,packageName:w.packageName,publisher:w.publisher,rowCount:w.resourceCount}}resolveView(e,t){let r=z(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=j(r,co);if(o){let a=z(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Se(t,po)){let a=o instanceof y?o:o instanceof p?z(e,o.subject):void 0;if(!a)continue;let i=we(a,fo),s=j(a,yo);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=ko(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=K(h(s)),d=K(h(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!Po(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=ze(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=L(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function vt(n){return Ce(n)?n.value:Array.isArray(n)?n.map(vt):n}function go(n){let e=h(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function It(n,e,t){let r=ho(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function ho(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=h(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||M(a.version,r)>0)&&(r=a.version)}return r?k(r):void 0}function ko(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=h(r);if(!o||!o.version)continue;let a=K(o),i=t.get(a);(!i||M(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function bo(n,e){let t=we(n,e);return t?[t]:Se(n,e).filter(r=>r instanceof y)}function Po(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ce(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{or as AmbiguousReferenceRule,he as BooleanStatement,gt as CANONICAL_FORM_VERSION,Fe as Carrier,ur as ClassDefinitionRule,qn as ClassHierarchyCycleRule,Gt as CompositeKanonakDocumentRepository,ae as CredentialStore,fe as DefinedKanonak,nr as DefinitionPropertyReferenceRule,Wt as DocumentLocation,hn as EdgeType,y as EmbeddedKanonak,Wn as EmbeddedKanonakTypeRule,x as EmbeddedStatement,U as EntitlementDeniedError,ce as EntitlementProducer,zt as FileSystemKanonakDocumentRepository,Cn as GitIgnoreFilter,kn as GraphBuilder,Qt as HttpKanonakDocumentRepository,_ as ImportBook,Gn as ImportExistenceRule,Ht as InMemoryKanonakDocumentRepository,tr as InstancePropertyReferenceRule,rn as Kanonak,En as KanonakDocumentPositions,$ as KanonakObjectParser,dr as KanonakObjectValidator,S as KanonakParser,H as KanonakUri,vn as KanonakUriBuilder,$n as KanonakUrlResolver,dn as KanonakVocabulary,I as ListStatement,C as LiteralKanonak,en as LocalFirstRepository,yr as LookRenderer,pr as MarkdownLinkRule,an as MarkdownStatement,er as NamespaceImportCycleRule,Un as NamespacePrefixRule,gn as NodeType,ge as NumberStatement,wn as OWL_RL_CLASSIFICATION_RULES,ir as ObjectPropertyImportRule,sr as ObjectPropertyValueValidationRule,Tn as OntologyValidationError,Dn as OntologyValidationResult,P as PackageBuilder,zn as PackageHeaderRule,se as ProducerRepository,cr as PropertyDomainRule,Yn as PropertyHierarchyCycleRule,Rn as PropertyMetadata,ar as PropertyRangeReferenceRule,Zn as PropertyRangeRequiredRule,Mn as PropertyTypeSpecificityRule,lr as PropertyValueTypeRule,Yt as PublisherConfigResolver,Zt as PublisherIndex,Pn as RDFS_RULES,be as Reasoner,Sn as ReasoningResult,p as ReferenceKanonak,E as ReferenceStatement,qt as RepositoryFactory,Fn as ResourceNamingRule,sn as ResourceResolver,yn as ResourceTypeClassifier,ye as ScalarStatement,on as Statement,R as StringStatement,Xn as SubClassOfReferenceRule,Qn as SubPropertyOfReferenceRule,f as SubjectKanonak,Hn as SubjectKanonakTypeRequiredRule,bn as TripleStore,cn as TypeResolver,Jn as UnresolvedReferenceRule,Ln as ValidationCache,_n as ValidationContext,Nn as ValidationSeverity,Di as VersionOperator,le as ViewMaterializer,rr as XsdImportRule,Oe as allowAllPolicy,Xt as assertPackageIdentity,nn as buildLocalFirstRepository,gr as buildOntologyModel,je as canonicalForm,ie as canonicalHash,v as carrierOf,tn as collectKanonakFiles,M as compareVersions,pt as computeIntegrity,Be as contentAddressedName,Bn as contextTypesOf,it as createAuthenticatedFetch,T as createDPoPProof,_t as createVersion,fn as extractMarkdownLinks,mr as findDerivation,On as findInstancesByType,mn as findMalformedReferences,In as findMarkdownLinkAt,Kn as formatKanonakAddress,k as formatVersion,ot as generateDPoPKeyPair,Jt as getGlobalCachePath,G as hasValidToken,Ut as isCompatibleVersion,W as isExpired,Ft as isMajorCompatible,lt as loadLockFile,ln as makeUriKey,De as noopMeter,l as normalizeHost,Pe as parseKanonakAddress,Lt as parseVersionString,xn as parseWithPositions,Mt as pickHighestDocument,Vn as propertiesInScope,fr as resolveDisplayValue,An as resolvePropertyStep,L as sanitizeName,ut as saveLockFile,at as serverSupportsDPoP,h as subjectUri,jn as superClassChain,un as tripleKey,K as uriKey,pn as uriTriple,Nt as versionOperatorFromChar,me as versionOperatorToChar,Tt as versionsEqual};
|
|
@@ -9,11 +9,24 @@ export declare class KanonakParser implements IKanonakParser {
|
|
|
9
9
|
private createVersion;
|
|
10
10
|
private extractMetadata;
|
|
11
11
|
private extractBody;
|
|
12
|
-
private parseNamespace;
|
|
13
12
|
private parseVersion;
|
|
14
13
|
private parseImportsV3;
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Parse one authored import object (`{ package, match, version, alias? }`)
|
|
16
|
+
* into an {@link Import}. Validates the required fields — a missing
|
|
17
|
+
* `package`/`match`/`version` is an error (never a fabricated default), then
|
|
18
|
+
* delegates to the single {@link makeImport} builder.
|
|
19
|
+
*/
|
|
16
20
|
private parseImportFromEmbeddedObject;
|
|
21
|
+
/**
|
|
22
|
+
* THE single {@link Import} constructor — every import, whether parsed from a
|
|
23
|
+
* document or built by parts ({@link buildImport}), is produced here, so the
|
|
24
|
+
* operator/version/min-max/identity fields are computed one way. `operator`
|
|
25
|
+
* is the character form (`= ~ ^ *`); `version` is a `major.minor.patch`
|
|
26
|
+
* string. No fabricated defaults: callers supply the operator and version
|
|
27
|
+
* (the parser rejects an authored import that omits them).
|
|
28
|
+
*/
|
|
29
|
+
private makeImport;
|
|
17
30
|
/**
|
|
18
31
|
* Build a single {@link Import} from its parts — the canonical way to
|
|
19
32
|
* construct one OUTSIDE parsing a document (e.g. to request a seed package
|
|
@@ -23,7 +36,6 @@ export declare class KanonakParser implements IKanonakParser {
|
|
|
23
36
|
* the character form (`= ~ ^ *`); `version` is a `major.minor.patch` string.
|
|
24
37
|
*/
|
|
25
38
|
buildImport(packageName: string, operator: string, version: string, publisher?: string): Import;
|
|
26
|
-
private parseImport;
|
|
27
39
|
private parseVersionOperator;
|
|
28
40
|
private calculateMaxVersion;
|
|
29
41
|
private serializeImports;
|
package/dist/parsing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c,b as d,c as e,d as f}from"../chunk-
|
|
1
|
+
import{a as c,b as d,c as e,d as f}from"../chunk-UV6CLM2Y.js";import{i as b}from"../chunk-7GAOBCNZ.js";import{a}from"../chunk-EP7CJSV2.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.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,4 +1,5 @@
|
|
|
1
1
|
import type { KanonakUri } from '../resolution/KanonakUri.js';
|
|
2
|
+
import type { Version } from '@kanonak-protocol/types/document/models/types';
|
|
2
3
|
import type { Vocabulary } from './Vocabulary.js';
|
|
3
4
|
/**
|
|
4
5
|
* Canonicalize a built-in URI in place against {@link BUILTIN_HOMES}.
|
|
@@ -16,8 +17,21 @@ import type { Vocabulary } from './Vocabulary.js';
|
|
|
16
17
|
* unaffected whether or not the check is provided.
|
|
17
18
|
*
|
|
18
19
|
* No-op for non-built-in names.
|
|
20
|
+
*
|
|
21
|
+
* VERSION on re-home. A dangling built-in reference (not in the import closure)
|
|
22
|
+
* arrives carrying the importing document's OWN namespace — including its
|
|
23
|
+
* version. Re-homing must therefore also correct the version, or the built-in's
|
|
24
|
+
* URI would fabricate a non-existent core version equal to the document's own
|
|
25
|
+
* (typescript#58 — e.g. a bare `type: Package` with no `core-kanonak` import
|
|
26
|
+
* stamped `core-kanonak@<doc version>/Package`). When `coreVersions` is supplied
|
|
27
|
+
* (keyed by core package name), a re-home stamps the resolved core version — so
|
|
28
|
+
* the un-imported built-in matches what the imported one would resolve to, and
|
|
29
|
+
* is independent of the document's own version. A core package absent from the
|
|
30
|
+
* map (or repo) clears the version (version-agnostic) rather than fabricate one.
|
|
31
|
+
* Callers that only need type/identity classification omit the map and leave the
|
|
32
|
+
* version untouched, preserving prior behavior.
|
|
19
33
|
*/
|
|
20
|
-
export declare function canonicalizeBuiltinUri(uri: KanonakUri | undefined | null, isDefinedLocally?: (uri: KanonakUri) => boolean): void;
|
|
34
|
+
export declare function canonicalizeBuiltinUri(uri: KanonakUri | undefined | null, isDefinedLocally?: (uri: KanonakUri) => boolean, coreVersions?: ReadonlyMap<string, Version | undefined>): void;
|
|
21
35
|
/**
|
|
22
36
|
* Default `Vocabulary` for the Kanonak ontology — binds the W3C
|
|
23
37
|
* semantic roles to the URIs published in `kanonak.org/core-rdf`
|
package/dist/reasoning/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as g,b as h,c as i,d as j,e as k}from"../chunk-
|
|
1
|
+
import{a as g,b as h,c as i,d as j,e as k}from"../chunk-TC4MITSK.js";import"../chunk-7GAOBCNZ.js";import"../chunk-EP7CJSV2.js";import{d as a,e as b,f as c,h as d,i as e,j as f}from"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.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 +1 @@
|
|
|
1
|
-
import{b as e,c as r,d as n}from"../chunk-
|
|
1
|
+
import{b as e,c as r,d as n}from"../chunk-NNUV6K3C.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-EP7CJSV2.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-
|
|
1
|
+
import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-FFMZ7GQM.js";import{a as g,b as h,c as i,d as j}from"../chunk-NNUV6K3C.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-EP7CJSV2.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
|
package/dist/resolution/index.js
CHANGED
|
@@ -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-
|
|
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-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import{b as m,c as n}from"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.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};
|
package/dist/search/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as g}from"../chunk-
|
|
1
|
+
import{a as g}from"../chunk-BH5TB6XY.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-7GAOBCNZ.js";import"../chunk-EP7CJSV2.js";import{d as m,h as S}from"../chunk-UK2OIPAB.js";import{a as p,f as E}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as v}from"../chunk-T3JR2SV6.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+`
|
package/dist/server/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as E}from"../chunk-
|
|
1
|
+
import{j as E}from"../chunk-BH5TB6XY.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,g as N}from"../chunk-FFMZ7GQM.js";import{a as ee,b as re,c as V,d as I}from"../chunk-NNUV6K3C.js";import{a as X}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as oe}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as L}from"../chunk-7GAOBCNZ.js";import{a as D}from"../chunk-EP7CJSV2.js";import{b as O}from"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as ne}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as F,e as z,f as K,g as Q}from"../chunk-2ACBWC7K.js";import{readFileSync as ue,existsSync as de,readdirSync as me,writeFileSync as ge,mkdirSync as fe}from"fs";import{join as q}from"path";function se(n){let e=n.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function M(n,e){let t=new Set,r=[...n];for(;r.length>0;){let o=r.shift(),i=se(o);if(!i||t.has(i))continue;t.add(i);let d=o.metadata?.imports;if(d)for(let[c,f]of Object.entries(d))for(let g of f)try{let l=await e.getHighestCompatibleVersionAsync(c,g);l&&r.push(l)}catch{}}return t}var j=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=se(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var ae=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function C(n){let e=n?.render;if(e&&e.length>0){let t=[];for(let r of e)try{let o=O(r);o.kind==="package"?t.push({publisher:o.publisher,package_:o.package_}):o.kind==="resource"&&t.push({publisher:o.uri.publisher,package_:o.uri.package_})}catch{}if(t.length>0)return t}return ae}function H(n){return`${n.publisher}/${n.package_}`}function B(n){let{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,producers:c}=n,f=new Map,g=new Map,l=new Map,a=new Set;for(let m of r){if(!(m instanceof ne))continue;let y=m.namespace||"";if(!i.has(y))continue;f.set(`${y}/${m.name}`,m);let v=y.split("/")[1]??"",[x,p]=v.split("@");if(!x||!p)continue;let b=Q(p);b&&(a.has(v)||(a.add(v),g.has(x)||g.set(x,[]),g.get(x).push({verStr:p,version:b})),m.name===x&&l.set(v,m))}for(let m of g.values())m.sort((y,v)=>F(v.version,y.version));return{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,bySubject:f,pkgVersions:g,pkgSelfByVer:l,...c?{producers:c}:{}}}async function T(n,e={}){let t=new D,r=new X(t),o=[],i=[];for(let p of N(n)){let b;try{b=ue(p,"utf-8")}catch{continue}let w;try{w=t.parse(b).metadata?.namespace_}catch{continue}if(!w?.version)continue;let $=w.version;i.push({publisher:w.publisher,package_:w.package_,verStr:`${$.major}.${$.minor}.${$.patch}`,version:$,source:b})}i.sort((p,b)=>F(b.version,p.version));for(let p of i)await r.saveDocumentAsync(t.parse(p.source),`${p.publisher}/${p.package_}@${p.verStr}`),o.push({publisher:p.publisher,package_:p.package_,verStr:p.verStr,source:p.source});let d=[...new Set(o.map(p=>p.publisher))].sort(),c=e.publisher;if(c){if(!d.includes(c))throw new Error(`Publisher "${c}" not found in workspace. Available: ${d.join(", ")||"(none)"}`)}else if(d.length===1)c=d[0];else throw d.length===0?new Error(`No Kanonak packages found under ${n}`):new Error(`Workspace has multiple publishers (${d.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,g=new Map;for(let p of o)p.publisher===c&&(f.add(`${p.publisher}/${p.package_}@${p.verStr}`),g.set(`${p.package_}@${p.verStr}`,p.source));let l=new Z(A(),!0,t),a=e.repository??new te(r,l,new I(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),m=C(void 0);if(!e.repository){let p=A(),b=s=>{let h=q(p,s);return de(h)?new Set(me(h).filter(k=>k.endsWith(".kan.yml")).map(k=>k.split("@")[0])):new Set},w=(s,h)=>o.some(k=>k.publisher===s&&k.package_===h),$=new V,u=new Map;for(let s of m)if(u.has(s.publisher)||u.set(s.publisher,b(s.publisher)),!(u.get(s.publisher).has(s.package_)||w(s.publisher,s.package_)))try{let h=await $.getHighestVersion(s.publisher,s.package_);if(!h)continue;let k=await $.getPackageUrl(s.publisher,s.package_,h),_=await fetch(k);if(!_.ok)continue;let le=await _.text(),J=q(p,s.publisher);fe(J,{recursive:!0}),ge(q(J,`${s.package_}@${h}.kan.yml`),le,"utf-8")}catch{}}let y=a;if(!e.repository){let p=(await r.getAllDocumentsAsync()).filter(w=>w.metadata.namespace_?.publisher===c),b=await M(p,a);for(let w of m)b.add(H(w));y=new j(a,b)}let v=await new L(t).parseKanonaks(y),x=new E(v);return B({publisher:c,availablePublishers:d,catalog:v,lookRenderer:x,localNamespaces:f,rawByNsKey:g})}import{existsSync as he,readFileSync as ke,writeFileSync as ye,mkdirSync as ve}from"fs";import{join as ie}from"path";async function U(n,e={}){let t=new D,r=O(n),o=r.kind==="resource"?r.uri.publisher:r.publisher,i=e.cacheRoot??A(),d=(u,s,h)=>ie(i,u,`${s}@${h}.kan.yml`),c=new I({getFromCache:(u,s,h)=>{let k=d(u,s,h);return he(k)?ke(k,"utf-8"):null},onFetch:(u,s,h,k)=>{let _=ie(i,u);ve(_,{recursive:!0}),ye(d(u,s,h),k,"utf-8")},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),f=new V(e.fetchFn?{fetchFn:e.fetchFn}:void 0),g;if(r.kind==="resource"){let u=r.uri.version;g=[u?{package_:r.uri.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let u=r.version;g=[u?{package_:r.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.package_}]}else g=(await f.listLatestPackages(o)).map(s=>({package_:s.packageName}));let l=async(u,s,h)=>{try{let k=h?t.buildImport(s,"=",h,u):t.buildImport(s,"*","0.0.0",u);return await c.getHighestCompatibleVersionAsync(u,k)}catch{return null}},a=[];for(let u of g){let s=await l(o,u.package_,u.version);s&&a.push(s)}if(a.length===0)throw new Error(`Could not fetch any package for address "${n}" from publisher "${o}".`);let m=await new re().getConfig(o).catch(()=>{}),y=[];for(let u of C(m)){let s=await l(u.publisher,u.package_,void 0);s&&y.push(s)}let v=await M([...a,...y],c),x=new j(c,v),p=await new L(t).parseKanonaks(x),b=new E(p),w=new Set,$=new Map;for(let u of await c.getAllDocumentsAsync()){let s=u.metadata.namespace_;if(!s||s.publisher!==o)continue;let h=`${s.version.major}.${s.version.minor}.${s.version.patch}`,k=`${s.publisher}/${s.package_}@${h}`;w.add(k);let _=await c.getDocumentContentAsync(k);_!==null&&$.set(`${s.package_}@${h}`,_)}return B({publisher:o,availablePublishers:[o],catalog:p,lookRenderer:b,localNamespaces:w,rawByNsKey:$})}import{VersionOperator as W}from"@kanonak-protocol/types/document/models/enums";var S={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},R=(n,e,t,r)=>({status:n,headers:{"Content-Type":e,...r||{}},body:t}),P=n=>R(404,S[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${n}</p>`),be=n=>({status:301,headers:{Location:n},body:""}),we=n=>({status:302,headers:{Location:n},body:""});function Se(n){switch(n.kind){case"exact":return{operator:W.Exact,version:K(n.major,n.minor,n.patch)};case"minor-pin":return{operator:W.Compatible,version:K(n.major,n.minor,0)};case"major-pin":return{operator:W.Major,version:K(n.major,0,0)};default:return{operator:W.Any,version:K(0,0,0)}}}async function Re(n,e,t,r){if(!r)return null;let o=n.producers?.find(f=>f.canProduce(n.publisher,e));if(!o)return null;let i=await o.resolveVersion(n.publisher,e,Se(t));if(!i)return null;let d=z(i);if(t.kind!=="exact")return we(`/${e}/${d}.kan.yml`);let{source:c}=await o.produce(n.publisher,e,i);return R(200,S[".kan.yml"],c)}function ce(n,e,t){let r=n.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(o=>o.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor&&o.version.patch===t.patch)?.verStr??null;default:return null}}async function G(n,e,t=""){let{lookRenderer:r,publisher:o}=n;if(e==="/.well-known/kanonak.json"){let a=ee(o);return n.producers&&n.producers.length>0&&(a.resolveByRedirect=!0),R(200,S[".json"],JSON.stringify(a,null,2))}if(e==="/index.txt"){let a=[...n.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return R(200,S[".txt"],a.join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`)}if(e==="/"||e==="/index.html"||e==="/index.css"){let a=r.publisherSubject(o);return e==="/index.css"?R(200,S[".css"],r.renderStylesheet(a)):R(200,S[".html"],await r.renderDocument(a,{rootIndex:!0}))}let i=".html",d=!1,c=e;for(let a of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(a)){i=a,d=!0,c=e.slice(0,-a.length);break}let f=!d&&/application\/yaml|text\/yaml/i.test(t),g=c.endsWith("/");g&&c!=="/"&&(c=c.slice(0,-1));let l=oe.parse(c,o);if(!l)return P(e);if(l.kind==="package"){let a=ce(n,l.package_,l.versionSpec);if(!a)return await Re(n,l.package_,l.versionSpec,i===".kan.yml"||f)??P(e);if(i===".kan.yml"||f){let v=n.rawByNsKey.get(`${l.package_}@${a}`);return v!==void 0?R(200,S[".kan.yml"],v):P(e)}let m=n.pkgSelfByVer.get(`${l.package_}@${a}`);if(!m)return P(e);if(i===".css")return R(200,S[".css"],r.renderStylesheet(m));if(!g)return be(c+"/");let y=l.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(m)){let v=(n.pkgVersions.get(l.package_)||[]).map(x=>x.verStr);return R(200,S[".html"],r.renderPackageVersionList(l.package_,v,m))}return R(200,S[".html"],await r.renderDocument(m,y?{bareOverview:!0}:void 0))}if(l.kind==="resource"){let a=ce(n,l.package_,l.versionSpec);if(!a)return P(e);let m=n.bySubject.get(`${o}/${l.package_}@${a}/${l.name}`);if(!m)return P(e);switch(i){case".css":return R(200,S[".css"],r.renderStylesheet(m));case".svg":return R(200,S[".svg"],await r.renderSvg(m));case".md":{let y=r.renderRawMarkdown(m);return y===void 0?P(e):R(200,S[".md"],y)}default:return R(200,S[".html"],await r.renderDocument(m))}}return P(e)}import{readFileSync as xe}from"fs";var Y=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,t=new Set;if(this.options.root!==void 0){let r=new D;for(let o of N(this.options.root))try{let i=r.parse(xe(o,"utf-8")).metadata?.namespace_;if(!i?.version)continue;let d=i.version;e.add(`${i.publisher}/${i.package_}@${d.major}.${d.minor}.${d.patch}`),t.add(`${i.publisher}/${i.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:t},this.workspaceIndex}async modelFor(e,t,r){let o=this.getWorkspaceIndex(),i=this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},d=t?r?o.exact.has(`${e}/${t}@${r}`):o.pkgs.has(`${e}/${t}`):[...o.pkgs].some(a=>a.startsWith(`${e}/`)),c,f;if(d&&this.options.root!==void 0){let a=this.options.root;c=`ws:${e}`,f=()=>T(a,{publisher:e})}else{let a=t?r?`${e}/${t}@${r}`:`${e}/${t}`:e;c=`rm:${a}`,f=()=>U(a,i)}let g=this.models.get(c);if(g)return g;let l=await f();return l.lookRenderer.setLinkMode("open-world"),this.models.set(c,l),l}async handle(e,t=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:pe()};let o=r[0];if(!o.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let i=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),d=!i&&r.length>=2?r[1]:void 0,c=!i&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(o,d,c),g=e.endsWith("/")&&r.length>1?"/":"",l="/"+r.slice(1).join("/")+g,a=await G(f,l,t);return a.headers.Location?{...a,headers:{...a.headers,Location:`/${o}${a.headers.Location}`}}:a}};function pe(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{j as ClosureScopedRepository,Y as RequestRouter,ae as UNIVERSAL_RENDER_BASE,M as deriveImportClosure,pe as landingPage,U as loadResourceModel,T as loadServerModel,H as renderRefKey,C as resolveRenderContract,G as route};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-
|
|
1
|
+
import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-BH5TB6XY.js";import{a as se}from"../chunk-G7XXA2JL.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-UV6CLM2Y.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{i as ie}from"../chunk-7GAOBCNZ.js";import{a as ae}from"../chunk-EP7CJSV2.js";import{b as L,c as A,f as S}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{b as N,c as D,d as K,g as M,h as P,i as F,j as W,l as H}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{g as oe}from"../chunk-2ACBWC7K.js";var $e="kanonak.org",Ue="document-ast",i=e=>({publisher:$e,package_:Ue,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ue(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var j=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=xe(n.metadata,t),o=Le(n.children),s=["---",...r,"---","",o].join(`
|
|
2
2
|
`);return t?.trailingNewline&&(s.endsWith(`
|
|
3
3
|
`)||(s+=`
|
|
4
4
|
`)),s}};function xe(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(I(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(I(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(I),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=I(f??c),d=me(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function I(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function me(e,n){switch(e.kind){case"StringScalar":return Ve(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=me(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function Ve(e,n){return!n||ue(n,m.ESC_RAW)?e:ue(n,m.ESC_YAML_SAFE)?ve(e):e}function ve(e){return e.includes(`
|
|
@@ -7,5 +7,5 @@ export type { IKanonakObjectValidator, DocumentValidationResult } from './IKanon
|
|
|
7
7
|
export { KanonakObjectValidator } from './KanonakObjectValidator.js';
|
|
8
8
|
export type { IDocumentValidationRule } from './rules/document/IDocumentValidationRule.js';
|
|
9
9
|
export type { IRepositoryValidationRule } from './rules/repository/IRepositoryValidationRule.js';
|
|
10
|
-
export { NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule } from './rules/document/index.js';
|
|
10
|
+
export { NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, PackageHeaderRule } from './rules/document/index.js';
|
|
11
11
|
export { ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, InstancePropertyReferenceRule, DefinitionPropertyReferenceRule, XsdImportRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyImportRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyValueTypeRule, ClassDefinitionRule, EmbeddedKanonakTypeRule, MarkdownLinkRule, DisplayLensScopeRule, LookSemanticSvgPathRule, TxExpressionPathRule, ShaclShapeRule, OwlOneOfRule, DiamondNameClashRule } from './rules/repository/index.js';
|
package/dist/validation/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,C,D,E,F,G,H,
|
|
1
|
+
import{A,B,C,D,E,F,G,H,I,L as J,M as K,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-KARUKDEM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-7GAOBCNZ.js";import"../chunk-EP7CJSV2.js";import"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{w as AmbiguousReferenceRule,C as ClassDefinitionRule,n as ClassHierarchyCycleRule,u as DefinitionPropertyReferenceRule,J as DiamondNameClashRule,E as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,t as InstancePropertyReferenceRule,K as KanonakObjectValidator,F as LookSemanticSvgPathRule,D as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,y as ObjectPropertyImportRule,z as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,I as OwlOneOfRule,j as PackageHeaderRule,A as PropertyDomainRule,o as PropertyHierarchyCycleRule,x as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,g as ResourceNamingRule,H as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,G as TxExpressionPathRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,v as XsdImportRule};
|