@kanonak-protocol/sdk 3.77.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/browser.js +1 -1
  2. package/dist/canonical/CanonicalHash.d.ts +8 -0
  3. package/dist/canonical/Datatypes.d.ts +98 -0
  4. package/dist/canonical/index.d.ts +2 -1
  5. package/dist/{chunk-RVOMWGIN.js → chunk-4OSNT57C.js} +1 -1
  6. package/dist/{chunk-KXVSGB6Q.js → chunk-6I4BYZVA.js} +1 -1
  7. package/dist/{chunk-Z5ELOT2C.js → chunk-NC3FSY3R.js} +1 -1
  8. package/dist/{chunk-XQS5LDSO.js → chunk-PBNVHBS3.js} +1 -1
  9. package/dist/chunk-T3JR2SV6.js +1 -0
  10. package/dist/chunk-V3YPCUA6.js +84 -0
  11. package/dist/chunk-VNKX52D5.js +2 -0
  12. package/dist/chunk-WUAKDYY6.js +1 -0
  13. package/dist/{chunk-IOMNZBK4.js → chunk-XYEY6HUC.js} +1 -1
  14. package/dist/{chunk-LKBG2MK6.js → chunk-YCV4H6H5.js} +1 -1
  15. package/dist/{chunk-PJMOM5H7.js → chunk-YI5GLYMB.js} +1 -1
  16. package/dist/{chunk-ATH6636H.js → chunk-YWUKDEZA.js} +1 -1
  17. package/dist/{chunk-XWRVENU6.js → chunk-ZRMF5QLN.js} +1 -1
  18. package/dist/chunk-ZYAABYDS.js +1 -0
  19. package/dist/index.d.ts +3 -2
  20. package/dist/index.js +26 -26
  21. package/dist/kanonaks/LiteralKanonak.d.ts +4 -0
  22. package/dist/parsing/KanonakObjectParser.d.ts +13 -0
  23. package/dist/parsing/index.js +1 -1
  24. package/dist/reasoning/index.js +1 -1
  25. package/dist/repositories/browser.js +1 -1
  26. package/dist/repositories/index.js +1 -1
  27. package/dist/resolution/index.js +1 -1
  28. package/dist/search/index.js +1 -1
  29. package/dist/server/index.js +1 -1
  30. package/dist/statements/ScalarStatement.d.ts +14 -0
  31. package/dist/transformations/index.js +1 -1
  32. package/dist/uri-helpers/index.js +1 -1
  33. package/dist/validation/IKanonakObjectValidator.d.ts +6 -0
  34. package/dist/validation/KanonakObjectValidator.d.ts +20 -2
  35. package/dist/validation/index.d.ts +1 -1
  36. package/dist/validation/index.js +1 -1
  37. package/dist/validation/rules/repository/DiamondNameClashRule.d.ts +8 -0
  38. package/package.json +2 -2
  39. package/dist/chunk-CG43Z65M.js +0 -2
  40. package/dist/chunk-IUZZDC2U.js +0 -1
  41. package/dist/chunk-NPEGVH4R.js +0 -84
  42. package/dist/chunk-TJPQETHV.js +0 -1
  43. package/dist/chunk-W6T7MOKY.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as g}from"../chunk-XWRVENU6.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-IUZZDC2U.js";import"../chunk-TJPQETHV.js";import{d as m,h as S}from"../chunk-Z5ELOT2C.js";import{a as p,f as E}from"../chunk-XQS5LDSO.js";import"../chunk-IOMNZBK4.js";import{c as v}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import{a as g}from"../chunk-ZRMF5QLN.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-WUAKDYY6.js";import"../chunk-ZYAABYDS.js";import{d as m,h as S}from"../chunk-NC3FSY3R.js";import{a as p,f as E}from"../chunk-PBNVHBS3.js";import"../chunk-XYEY6HUC.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+`
@@ -1,3 +1,3 @@
1
- import{j as E}from"../chunk-XWRVENU6.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,g as N}from"../chunk-ATH6636H.js";import{a as ee,b as re,c as V,d as I}from"../chunk-LKBG2MK6.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{f as L}from"../chunk-IUZZDC2U.js";import{a as D}from"../chunk-TJPQETHV.js";import{b as O}from"../chunk-Z5ELOT2C.js";import"../chunk-XQS5LDSO.js";import"../chunk-IOMNZBK4.js";import{c as ne}from"../chunk-W6T7MOKY.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(`
1
+ import{j as E}from"../chunk-ZRMF5QLN.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,g as N}from"../chunk-YWUKDEZA.js";import{a as ee,b as re,c as V,d as I}from"../chunk-YCV4H6H5.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{w as L}from"../chunk-WUAKDYY6.js";import{a as D}from"../chunk-ZYAABYDS.js";import{b as O}from"../chunk-NC3FSY3R.js";import"../chunk-PBNVHBS3.js";import"../chunk-XYEY6HUC.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,3 +1,17 @@
1
1
  import { Statement } from './Statement.js';
2
2
  export declare abstract class ScalarStatement<TScalar> extends Statement<TScalar> {
3
+ /**
4
+ * Canonical-form datatype carrier (a `Carrier` value, held as its string)
5
+ * when the value was typed by its property's resolved range. Drives
6
+ * datatype-precise canonicalization; absent for untyped/open-world values,
7
+ * which canonicalize as their raw lexical token. Stored as a plain string to
8
+ * avoid a statements→canonical import cycle.
9
+ */
10
+ carrier?: string;
11
+ /**
12
+ * The raw lexical token as authored — the precise, lossless input to
13
+ * canonicalization (e.g. `1.10`, a full-precision epoch-nanosecond integer).
14
+ * `object` may be a lossy native projection of this; `lexical` is exact.
15
+ */
16
+ lexical?: string;
3
17
  }
@@ -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-XWRVENU6.js";import{a as se}from"../chunk-RVOMWGIN.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PJMOM5H7.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{f as ie}from"../chunk-IUZZDC2U.js";import{a as ae}from"../chunk-TJPQETHV.js";import{b as L,c as A,f as S}from"../chunk-XQS5LDSO.js";import"../chunk-IOMNZBK4.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-W6T7MOKY.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(`
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-ZRMF5QLN.js";import{a as se}from"../chunk-4OSNT57C.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-YI5GLYMB.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{w as ie}from"../chunk-WUAKDYY6.js";import{a as ae}from"../chunk-ZYAABYDS.js";import{b as L,c as A,f as S}from"../chunk-PBNVHBS3.js";import"../chunk-XYEY6HUC.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(`
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"../chunk-XQS5LDSO.js";import"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{n as SingleDocumentRepository,g as findAllResourcesByCanonicalUri,f as findSubjectByUri,e as findSubjectsByType,i as getDatatypeValue,l as getEmbeddedValue,m as getListValues,k as getReferenceUri,j as getStringValue,h as hasProperty,d as hasType,c as toCanonicalUrl,a as uriKey,b as uriMatches};
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"../chunk-PBNVHBS3.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{n as SingleDocumentRepository,g as findAllResourcesByCanonicalUri,f as findSubjectByUri,e as findSubjectsByType,i as getDatatypeValue,l as getEmbeddedValue,m as getListValues,k as getReferenceUri,j as getStringValue,h as hasProperty,d as hasType,c as toCanonicalUrl,a as uriKey,b as uriMatches};
@@ -2,7 +2,13 @@ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/documen
2
2
  import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
3
3
  import type { OntologyValidationResult } from './OntologyValidationResult.js';
4
4
  import type { ValidationCache } from './ValidationCache.js';
5
+ /** One document's result within a batch validation pass. */
6
+ export interface DocumentValidationResult {
7
+ document: KanonakDocument;
8
+ result: OntologyValidationResult;
9
+ }
5
10
  export interface IKanonakObjectValidator {
6
11
  validateAsync(document: KanonakDocument, repository?: IKanonakDocumentRepository | null, cache?: ValidationCache): Promise<OntologyValidationResult>;
12
+ validateDocumentsAsync(documents: KanonakDocument[], repository: IKanonakDocumentRepository): Promise<DocumentValidationResult[]>;
7
13
  validateYamlAsync(yamlText: string, repository?: IKanonakDocumentRepository | null, cache?: ValidationCache): Promise<OntologyValidationResult>;
8
14
  }
@@ -1,11 +1,11 @@
1
1
  import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
2
2
  import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
3
3
  import type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
4
- import type { IKanonakObjectValidator } from './IKanonakObjectValidator.js';
4
+ import type { IKanonakObjectValidator, DocumentValidationResult } from './IKanonakObjectValidator.js';
5
5
  import type { IDocumentValidationRule } from './rules/document/IDocumentValidationRule.js';
6
6
  import type { IRepositoryValidationRule } from './rules/repository/IRepositoryValidationRule.js';
7
7
  import { OntologyValidationResult } from './OntologyValidationResult.js';
8
- import type { ValidationCache } from './ValidationCache.js';
8
+ import { ValidationCache } from './ValidationCache.js';
9
9
  export declare class KanonakObjectValidator implements IKanonakObjectValidator {
10
10
  private readonly parser;
11
11
  private readonly documentRules;
@@ -13,6 +13,24 @@ export declare class KanonakObjectValidator implements IKanonakObjectValidator {
13
13
  includeWarnings: boolean;
14
14
  constructor(parser?: IKanonakParser);
15
15
  validateAsync(document: KanonakDocument, repository?: IKanonakDocumentRepository | null, cache?: ValidationCache): Promise<OntologyValidationResult>;
16
+ /**
17
+ * Validate a SET of documents that share one repository — the single
18
+ * blessed entry point for any multi-document pass (a `kanonak validate
19
+ * <dir>`, a VS Code workspace refresh, a CI gate over a catalog).
20
+ *
21
+ * It owns the `ValidationCache` lifecycle so no caller can forget it: a
22
+ * single cache is built for the whole pass and threaded through every
23
+ * per-document `validateAsync`, memoizing the import-closure walks,
24
+ * repo lookups, and full-repo `parseKanonaks` that the repository rules
25
+ * would otherwise redo from scratch for every document. Validating a
26
+ * directory without this cache is O(documents x catalog) and does not
27
+ * finish on a real catalog; with it, the catalog is parsed once.
28
+ *
29
+ * Per-document `validateAsync(doc, repo, cache)` remains the low-level
30
+ * primitive; clients that validate more than one document MUST come
31
+ * through here rather than re-deriving the cache + loop themselves.
32
+ */
33
+ validateDocumentsAsync(documents: KanonakDocument[], repository: IKanonakDocumentRepository): Promise<DocumentValidationResult[]>;
16
34
  validateYamlAsync(yamlText: string, repository?: IKanonakDocumentRepository | null, cache?: ValidationCache): Promise<OntologyValidationResult>;
17
35
  addDocumentRule(rule: IDocumentValidationRule): void;
18
36
  addRepositoryRule(rule: IRepositoryValidationRule): void;
@@ -3,7 +3,7 @@ export { OntologyValidationError } from './OntologyValidationError.js';
3
3
  export { ValidationSeverity } from './ValidationSeverity.js';
4
4
  export { ValidationContext } from './ValidationContext.js';
5
5
  export { ValidationCache } from './ValidationCache.js';
6
- export type { IKanonakObjectValidator } from './IKanonakObjectValidator.js';
6
+ export type { IKanonakObjectValidator, DocumentValidationResult } from './IKanonakObjectValidator.js';
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';
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,K as I,L as J,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-NPEGVH4R.js";import"../chunk-SHDHMKMJ.js";import"../chunk-IUZZDC2U.js";import"../chunk-TJPQETHV.js";import"../chunk-Z5ELOT2C.js";import"../chunk-XQS5LDSO.js";import"../chunk-IOMNZBK4.js";import"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,m as ClassHierarchyCycleRule,t as DefinitionPropertyReferenceRule,I as DiamondNameClashRule,D as DisplayLensScopeRule,j as EmbeddedKanonakTypeRule,k as ImportExistenceRule,s as InstancePropertyReferenceRule,J as KanonakObjectValidator,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,r as NamespaceImportCycleRule,f as NamespacePrefixRule,x as ObjectPropertyImportRule,y as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,H as OwlOneOfRule,z as PropertyDomainRule,n as PropertyHierarchyCycleRule,w as PropertyRangeReferenceRule,o as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,A as PropertyValueTypeRule,g as ResourceNamingRule,G as ShaclShapeRule,p as SubClassOfReferenceRule,q as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,F as TxExpressionPathRule,l as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,u as XsdImportRule};
1
+ import{A,B,C,D,E,F,G,H,K as I,L as J,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-V3YPCUA6.js";import"../chunk-SHDHMKMJ.js";import"../chunk-WUAKDYY6.js";import"../chunk-ZYAABYDS.js";import"../chunk-NC3FSY3R.js";import"../chunk-PBNVHBS3.js";import"../chunk-XYEY6HUC.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{v as AmbiguousReferenceRule,B as ClassDefinitionRule,m as ClassHierarchyCycleRule,t as DefinitionPropertyReferenceRule,I as DiamondNameClashRule,D as DisplayLensScopeRule,j as EmbeddedKanonakTypeRule,k as ImportExistenceRule,s as InstancePropertyReferenceRule,J as KanonakObjectValidator,E as LookSemanticSvgPathRule,C as MarkdownLinkRule,r as NamespaceImportCycleRule,f as NamespacePrefixRule,x as ObjectPropertyImportRule,y as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,H as OwlOneOfRule,z as PropertyDomainRule,n as PropertyHierarchyCycleRule,w as PropertyRangeReferenceRule,o as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,A as PropertyValueTypeRule,g as ResourceNamingRule,G as ShaclShapeRule,p as SubClassOfReferenceRule,q as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,F as TxExpressionPathRule,l as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,u as XsdImportRule};
@@ -13,6 +13,14 @@ import type { ValidationCache } from '../../ValidationCache.js';
13
13
  * generated interface uncompilable. Catching it at validate time turns a
14
14
  * cryptic downstream compile failure into a loud, actionable design-time error.
15
15
  *
16
+ * The clash is only ever between properties contributed by two DISTINCT
17
+ * PROPER super-classes. A property the class DECLARES on itself shadows any
18
+ * same-named inherited one (specialization, not a diamond), and a property
19
+ * domained on the universal `rdfs.Resource` floor — which every class inherits
20
+ * (e.g. core `value`/`members`) — is ambient, never a competing parent. So a
21
+ * publisher refining a universal-core local name on its own class does not
22
+ * fire; only two genuinely-inherited, incompatible same-named members do.
23
+ *
16
24
  * Benign cases do NOT fire: one property reached through multiple diamond paths
17
25
  * (same URI — deduped), two parents referencing the same property (same URI),
18
26
  * two distinct same-named properties whose range AND cardinality agree (the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.77.0",
3
+ "version": "4.0.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -122,7 +122,7 @@
122
122
  "yaml-parser"
123
123
  ],
124
124
  "dependencies": {
125
- "@kanonak-protocol/types": "^3.77.0",
125
+ "@kanonak-protocol/types": "^4.0.0",
126
126
  "ignore": "^7.0.5",
127
127
  "js-yaml": "^4.1.0",
128
128
  "yaml": "^2.7.0"
@@ -1,2 +0,0 @@
1
- import{I as W,J as X}from"./chunk-NPEGVH4R.js";import{b as B,c as V,f as w}from"./chunk-IUZZDC2U.js";import{a as b,d as K,e as q,f as z}from"./chunk-Z5ELOT2C.js";import{a as D,f as E,h as F,j as N,k as Y,m as v}from"./chunk-XQS5LDSO.js";import{c as G,d as x}from"./chunk-W6T7MOKY.js";import{a as L}from"./chunk-FUUTGGJS.js";import{d as U}from"./chunk-2ACBWC7K.js";var Q=(t=>(t.Class="Class",t.DatatypeProperty="DatatypeProperty",t.ObjectProperty="ObjectProperty",t.AnnotationProperty="AnnotationProperty",t.Instance="Instance",t.Datatype="Datatype",t.Unknown="Unknown",t))(Q||{}),Z=(p=>(p.InstanceOf="instanceOf",p.SubClassOf="subClassOf",p.Domain="domain",p.Range="range",p.ObjectRelationship="objectRelationship",p.SubPropertyOf="subPropertyOf",p.PropertyValue="propertyValue",p.EmbeddedLink="embeddedLink",p))(Z||{}),I=class{static async buildFromRepository(e){let a=await new w().parseKanonaks(e),o=await e.getAllDocumentsAsync(),s=[],i=[],t=new Set,p=new Set,g=new Map;for(let u of a){let l=u;l.name&&(b.isClassType(l)&&t.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&p.add(l.name))}for(let u of o)for(let[l,f]of Object.entries(u.body))p.has(l)&&f?.range&&typeof f.range=="string"&&g.set(l,f.range);let y=new Map;for(let u of a){let l=u;l.name&&y.set(l.name,l)}for(let u of o){let l=u.metadata.namespace_,f=l?`${l.publisher}/${l.package_}`:"",c=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",d=H(u);for(let[k,m]of Object.entries(u.body)){if(!m||typeof m!="object")continue;let P=y.get(k),h="Unknown";if(P){let T=P;b.isClassType(T)?h="Class":b.isObjectPropertyType(T)?h="ObjectProperty":b.isDatatypePropertyType(T)?h="DatatypeProperty":b.isAnnotationPropertyType(T)?h="AnnotationProperty":b.isDatatypeType(T)?h="Datatype":b.isGenericPropertyType(T)?h="ObjectProperty":b.isInstanceOfKnownClass(T,t)&&(h="Instance")}let j=f&&c?`${f}/${k}@${c}`:k,A={};for(let[T,$]of Object.entries(m))T!=="type"&&(typeof $!="object"||$===null)&&(A[T]=$);s.push({id:j,label:m.label??k,type:h,namespace:f,properties:A}),J(j,m,h,t,p,i,f,c,d),_(j,m,p,g,s,i,f,c,d),ue(j,P,i)}}return{nodes:s,edges:i}}static buildFromDocument(e){let r=[],a=[],o=e.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",i=o?`${o.publisher}/${o.package_}`:"",t=new Set,p=new Set,g=new Map,y=H(e);for(let[f,c]of Object.entries(e.body)){let d=c?.type;d&&(pe(d,y)&&t.add(f),ce(d,y)&&(p.add(f),c.range&&typeof c.range=="string"&&g.set(f,c.range)))}for(let[f,c]of Object.entries(e.body)){if(!c||typeof c!="object")continue;let d=c.type,k=le(d,f,t,y),m=i&&s?`${i}/${f}@${s}`:f,P={};for(let[h,j]of Object.entries(c))h!=="type"&&(typeof j!="object"||j===null)&&(P[h]=j);r.push({id:m,label:c.label??f,type:k,namespace:i,properties:P}),J(m,c,k,t,p,a,i,s,y),_(m,c,p,g,r,a,i,s,y)}let u=new Set(r.map(f=>f.id)),l=a.filter(f=>u.has(f.source)&&u.has(f.target));return{nodes:r,edges:l}}};function H(n,e){let r=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let s of o){let i=s.alias??s.packageName,t=s.version,p=`${t.major}.${t.minor}.${t.patch}`;r.set(i,{publisher:a,package_:s.packageName,version:p})}return r}var ee={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ie=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function M(n,e){if(n.includes(".")){let r=n.indexOf("."),a=n.substring(0,r),o=n.substring(r+1),s=e.get(a);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function pe(n,e){let r=M(n,e);return r?ee[r]==="Class":!1}function ce(n,e){let r=M(n,e);return r?ie.has(r):!1}function le(n,e,r,a){if(!n||n==="Package")return"Unknown";let o=M(n,a);if(o){let i=ee[o];if(i)return i;let t=o.split("/").pop()?.split("@")[0]??"";return r.has(t)?"Instance":"Unknown"}let s=n.split(".").pop()??n;return r.has(s)?"Instance":"Unknown"}var ne=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function J(n,e,r,a,o,s,i,t,p){let g=e.type,y=e.subClassOf;if(y){let c=Array.isArray(y)?y:[y];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let c=Array.isArray(u)?u:[u];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subPropertyOf",label:"subPropertyOf"})}if(r==="Instance"&&g){let c=g.split(".").pop()??g;s.push({source:n,target:O(c,i,t,p),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[c,d]of Object.entries(e)){if(ne.has(c)||!o.has(c))continue;let k=Array.isArray(d)?d:[d];for(let m of k)typeof m=="string"&&fe(m)&&s.push({source:n,target:O(m,i,t,p),type:"propertyValue",label:c,propertyId:O(c,i,t,p)})}let l=r==="ObjectProperty"||r==="DatatypeProperty",f=e.domain&&e.range;if((l||f)&&e.domain&&e.range){let c=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;c&&d&&s.push({source:O(c,i,t,p),target:O(d,i,t,p),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function _(n,e,r,a,o,s,i,t,p){for(let[g,y]of Object.entries(e)){if(ne.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let u=y,l=`${n}/${g}`,f=a.get(g),c=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,P]of Object.entries(u))(typeof P!="object"||P===null)&&(d[m]=P);o.push({id:l,label:`${c} (embedded)`,type:"Instance",namespace:i,properties:d});let k=i&&t?`${i}/${g}@${t}`:g;s.push({source:n,target:l,type:"propertyValue",label:g,propertyId:r.has(g)?k:void 0}),f&&s.push({source:l,target:O(c,i,t,p),type:"instanceOf",label:"type (inferred)"}),_(l,u,r,a,o,s,i,t,p)}}function ue(n,e,r){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof V))continue;let s=o.predicate?.subject?.name??"";for(let i of o.links){let t=i.target?.subject;if(!t)continue;let p=t.version,g=p&&typeof p.major=="number"?`@${p.major}.${p.minor}.${p.patch}`:"";r.push({source:n,target:`${t.publisher}/${t.package_}/${t.name}${g}`,type:"embeddedLink",label:s})}}}function fe(n){return!(!n||n.includes(" ")||n.includes(`
2
- `)||n.startsWith("http://")||n.startsWith("https://")||/^\d{4}-\d{2}/.test(n)||/^\d+(\.\d+)?$/.test(n))}function O(n,e,r,a){if(n.includes("@")&&n.includes("/"))return n;if(n.includes(".")){let o=n.indexOf("."),s=n.substring(0,o),i=n.substring(o+1);if(a){let t=a.get(s);if(t)return`${t.publisher}/${t.package_}/${i}@${t.version}`}return e&&r?`${e}/${i}@${r}`:i}return e&&r?`${e}/${n}@${r}`:n}function de(n){if(!n.expiresAt)return!1;let e=new Date(n.expiresAt),r=300*1e3;return e.getTime()<=Date.now()+r}function Re(n){return!!n.accessToken&&!de(n)}function Se(n){let e=n.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}var C="kanonak.org",S="core-rdf",re="core-xsd",te={publisher:C,package_:S,name:"subClassOf"},oe={publisher:C,package_:S,name:"label"},ye={publisher:C,package_:S,name:"comment"},se={publisher:C,package_:"core-owl",name:"oneOf"},ae=n=>n;function ge(n){let e=Y(n,te);if(e)return[e];let r=[];for(let a of v(n,te))a instanceof x&&r.push(a.subject);return r}function me(n,e,r){if(e.publisher===C&&e.package_===S&&e.name==="Literal")return{kind:"datatype",uri:e};let o=E(n,e);if(o){let s=ae(o);if(b.isDatatypeType(s))return{kind:"datatype",uri:e};if(b.isClassType(s))return{kind:"class",uri:K(o)??e,localName:o.name}}return e.publisher===C&&e.package_===re?{kind:"datatype",uri:e}:r==="datatype"?{kind:"datatype",uri:e}:{kind:"class",uri:e,localName:e.name}}function be(n,e,r){if(!e.range)throw new Error(`Property ${e.uri.publisher}/${e.uri.package_}/${e.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let a=me(n,e.range,e.kind),o=e.kind==="object"?"object":e.kind==="datatype"?"datatype":a.kind==="class"?"object":"datatype";return{uri:e.uri,localName:e.uri.name,kind:o,range:a,...e.label!==void 0?{label:e.label}:{},...e.comment!==void 0?{comment:e.comment}:{},...r??{}}}var R=n=>new L(C,re,n);function ke(n){return typeof n=="boolean"?R("boolean"):typeof n=="number"?Number.isInteger(n)?R("integer"):R("decimal"):R("string")}function he(n,e){let r=[];for(let a of v(e,se))if(a instanceof x){let o=E(n,a.subject),s=(o?K(o):void 0)??a.subject,i=o?N(o,oe):void 0;r.push({kind:"individual",uri:s,localName:s.name,...i!==void 0?{label:i}:{}})}else a instanceof B&&r.push({kind:"literal",value:a.value,datatype:ke(a.value)});return r}function Pe(n,e,r,a){let o=q(n,e),s=D(e);return z(n,e).filter(t=>r?!0:t.domains.some(p=>D(p)===s)).map(t=>be(n,t,X(a,o,t.uri)))}async function Te(n,e,r){let a=n.metadata?.namespace_;if(!a)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=r?.includeInherited??!1,s=await new w().parseKanonaks(e),i=W(s),t=[],p=[],g=new Set;for(let y of s){if(!(y instanceof G)||!b.isClassType(ae(y)))continue;let u=K(y);if(!u||u.publisher!==a.publisher||u.package_!==a.package_||u.version&&a.version&&!U(u.version,a.version))continue;let l=D(u);if(g.has(l))continue;g.add(l);let f=ge(y).map(k=>({uri:k,localName:k.name})),c=N(y,oe),d=N(y,ye);t.push({uri:u,localName:u.name,superClasses:f,properties:Pe(s,u,o,i),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}}),F(y,se)&&p.push({uri:u,localName:u.name,members:he(s,y),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}})}return{classes:t,enums:p}}export{Q as a,Z as b,I as c,de as d,Re as e,Se as f,Te as g};
@@ -1 +0,0 @@
1
- import{a as A}from"./chunk-TJPQETHV.js";import{b as N,c as _,i as M}from"./chunk-IOMNZBK4.js";import{a as $,b as L,c as j,d as k,g as S,h as D,i as O,j as P,k as K,l as R}from"./chunk-W6T7MOKY.js";var b=class extends L{name};var w=class extends ${value};var I=class extends S{links=[]};var U=/\[\[([^\[\]\n]+)\]\]/g,B=/\[\[/g,V=/```[\s\S]*?```|`[^`\n]*`/g;function z(f){let e=[];for(let t of f.matchAll(V))e.push([t.index,t.index+t[0].length]);return e}function Q(f){if(!f||!f.includes("[["))return[];let e=z(f),t=a=>e.some(([n,p])=>a>=n&&a<p),r=new Set(T(f).map(a=>a.startOffset)),o=[];for(let a of f.matchAll(B)){let n=a.index;if(t(n)||r.has(n))continue;let p=f.slice(n,n+48).replace(/\s+/g," ").trim();o.push({startOffset:n,snippet:p})}return o}function T(f){if(!f||!f.includes("[["))return[];let e=[];for(let o of f.matchAll(V))e.push([o.index,o.index+o[0].length]);let t=o=>e.some(([a,n])=>o>=a&&o<n),r=[];for(let o of f.matchAll(U)){let a=o.index;if(t(a))continue;let n=o[1],p=n.indexOf("|"),s=(p===-1?n:n.slice(0,p)).trim();if(s.length===0)continue;let m=p===-1?"":n.slice(p+1).trim(),y={reference:s,startOffset:a,endOffset:a+o[0].length};m.length>0&&(y.displayText=m),r.push(y)}return r}var C=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),o=new N(e),a=new _(o);for(let i of r){let c=i.metadata.namespace_?.toString()??"";for(let[l,u]of Object.entries(i.body)){let d=new j,g=this.resolveCanonicalEntity(l,i,c);d.namespace=g.namespace,d.name=g.name,d.statement=[];let h=await this.parseStatements(u,i,o,a,e);d.statement.push(...h),t.push(d)}}let n=new Map,p=new Map,s=[];for(let i of t)if(i instanceof j){let c=`${i.namespace}/${i.name}`,l=n.get(c);if(l){let u=p.get(c);for(let d of i.statement){let g=E(d);u.has(g)||(u.add(g),l.statement.push(d))}}else{let u=new Set,d=[];for(let g of i.statement){let h=E(g);u.has(h)||(u.add(h),d.push(g))}i.statement=d,p.set(c,u),n.set(c,i),s.push(i)}}else s.push(i);let m=new Set;for(let i of s)if(i instanceof j){let c=i.namespace||"",l=c.indexOf("/"),u=l>=0?c.slice(0,l):"",d=l>=0?c.slice(l+1):"",g=d.indexOf("@"),h=g>=0?d.slice(0,g):d;m.add(`${u}/${h}/${i.name}`)}let y=i=>m.has(`${i.publisher}/${i.package_}/${i.name}`);for(let i of s)i instanceof j&&this.canonicalizeStatementBuiltins(i.statement,y);return s}canonicalizeStatementBuiltins(e,t){for(let r of e){let o=r.predicate?.subject;if(M(o,t),r instanceof P)r.object instanceof k&&M(r.object.subject,t);else if(r instanceof K)r.object&&this.canonicalizeStatementBuiltins(r.object.statement,t);else if(r instanceof R)for(let a of r.object??[])a instanceof k?M(a.subject,t):a instanceof b&&this.canonicalizeStatementBuiltins(a.statement,t)}}resolveCanonicalEntity(e,t,r){if(!e.includes(".")||!t.metadata?.imports)return{namespace:r,name:e};let o=e.indexOf("."),a=e.substring(0,o),n=e.substring(o+1);for(let[p,s]of Object.entries(t.metadata.imports))for(let m of s)if((m.alias??m.packageName)===a){let i=m.version;return{namespace:`${p}/${m.packageName}@${i.major}.${i.minor}.${i.patch}`,name:n}}return{namespace:r,name:e}}async parseStatements(e,t,r,o,a){let n=[];if(typeof e!="object"||e===null||Array.isArray(e))return n;for(let[p,s]of Object.entries(e))try{let m=await this.getPropertyMetadata(p,t,r,a,o);if(!m)continue;let y=await this.parsePropertyValue(p,s,m,t,r,o,a);y&&n.push(y)}catch(m){throw new Error(`Failed to parse property '${p}': ${m.message}`,{cause:m})}return n}async getPropertyMetadata(e,t,r,o,a){let n=await r.resolveEntityAsync(e,t);if(!n)return;let p=n.entity,s=p.type?.toString()??"",m=s.includes(".")?s.substring(s.lastIndexOf(".")+1):s;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(m))return;let i=a.getPropertyTypeClassification(s),c=p.range?.toString(),l;if(i==="ObjectProperty")l="ObjectProperty";else if(i==="DatatypeProperty")l="DatatypeProperty";else{let g=c&&c.includes(".")?c.substring(c.lastIndexOf(".")+1):c??"";(c?a.isKnownXsdDatatypeName(c):!1)||g==="Literal"?l="DatatypeProperty":l="ObjectProperty"}let u;if(c){let g=t;if(n.isImported&&n.definedInNamespace){if(typeof o.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${e}': the parse repository cannot fetch defining document '${n.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let x=await o.getDocumentAsync(n.definedInNamespace);if(!x)throw new Error(`Cannot resolve the range of imported property '${e}': defining document '${n.definedInNamespace}' was not found in the repository.`);g=x}u=(await r.resolveEntityAsync(c,g))?.uri}return{propertyUri:n.uri.toString(),propertyType:l,range:c,rangeUri:u,isImported:n.isImported,definedInNamespace:n.definedInNamespace}}async parsePropertyValue(e,t,r,o,a,n,p){let s=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(s,t,r,o,a,n,p);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(s,t,r,o,a,n);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(s,t,r,o,a,n,p)}}async parseDatatypeValue(e,t,r,o,a,n){if(t instanceof Date)return S.parse(e,t.toISOString());if(typeof t=="string")return n.isSubstitutableDatatype(r.rangeUri)?await this.parseSubstitutableValue(e,t,o,a):S.parse(e,t);if(typeof t=="number")return D.parse(e,t);if(typeof t=="boolean"){let p=new O;return p.predicate=k.parse(e),p.object=t,p}}async parseSubstitutableValue(e,t,r,o){let a=new I;a.predicate=k.parse(e),a.object=t;for(let n of T(t)){let p=await o.resolveEntityAsync(n.reference,r),s;p&&(s=new k,s.subject=p.uri);let m={reference:n.reference,startOffset:n.startOffset,endOffset:n.endOffset};n.displayText!==void 0&&(m.displayText=n.displayText),s!==void 0&&(m.target=s),a.links.push(m)}return a}async parseObjectValue(e,t,r,o,a,n,p){if(typeof t=="string"){let s=await this.resolveReference(t,o,a);if(!s)return;let m=new P;return m.predicate=k.parse(e),m.object=s,m}if(typeof t=="object"&&!Array.isArray(t)){let s=new b;if(s.statement=await this.parseStatements(t,o,a,n,p),s.statement.length>0){let i=new K;return i.predicate=k.parse(e),i.object=s,i}let m=[];for(let[i,c]of Object.entries(t))if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let l=new b;l.name=i,l.statement=await this.parseStatements(c,o,a,n,p),m.push(l)}else if(typeof c=="string"){let l=await this.resolveReference(c,o,a);l&&m.push(l)}if(m.length>0){let i=new R;return i.predicate=k.parse(e),i.object=m,i}let y=new K;return y.predicate=k.parse(e),y.object=s,y}}async parseListValue(e,t,r,o,a,n,p){let s=[],m=r.propertyType==="DatatypeProperty",y=r.rangeUri?.publisher==="kanonak.org"&&r.rangeUri?.package_==="core-rdf"&&r.rangeUri?.name==="List"||!r.rangeUri&&(r.range?.includes(".")?r.range.substring(r.range.lastIndexOf(".")+1):r.range)==="List";for(let c of t){let l=typeof c=="string"||typeof c=="number"||typeof c=="boolean";if(m&&l){let u=new w;u.value=c,s.push(u);continue}if((m||y)&&c instanceof Date){let u=new w;u.value=c.toISOString(),s.push(u);continue}if(y&&l){if(typeof c=="string"){let u=await a.resolveEntityAsync(c,o);if(u){let d=new k;d.subject=u.uri,s.push(d)}else{let d=new w;d.value=c,s.push(d)}}else{let u=new w;u.value=c,s.push(u)}continue}if(typeof c=="string"){let u=await this.resolveReference(c,o,a);u&&s.push(u)}else if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let u=new b;u.statement=await this.parseStatements(c,o,a,n,p),s.push(u)}}let i=new R;return i.predicate=k.parse(e),i.object=s,i}async resolveReference(e,t,r){let o=await r.resolveEntityAsync(e,t);if(o){let n=new k;return n.subject=o.uri,n}let a=t.metadata?.namespace_;if(a){let{KanonakUri:n}=await import("./KanonakUri-4VJGV3FN.js"),p=a.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let m=e.indexOf("."),y=e.substring(0,m),i=e.substring(m+1);if(t.metadata?.imports){for(let[c,l]of Object.entries(t.metadata.imports))for(let u of l)if((u.alias??u.packageName)===y){let g=new k;return g.subject=new n(c,u.packageName,i,u.version),g}}}let s=new k;return s.subject=new n(a.publisher,a.package_,e,p),s}return null}async saveKanonaks(e,t){let r=new Map;for(let o of e)o instanceof j&&o.namespace&&(r.has(o.namespace)||r.set(o.namespace,[]),r.get(o.namespace).push(o));for(let[o,a]of r){let n=await this.convertKanonaksToDocument(o,a),p=`${o.split("@")[0]}.yml`;await t.saveDocumentAsync(n,p)}}async serializeToYaml(e,t){let r=e.filter(n=>n instanceof j&&n.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let o=await this.convertKanonaksToDocument(t,r);return new A().save(o)}async convertKanonaksToDocument(e,t){let o={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let n=[];for(let p of Object.values(this.imports))n.push(...p);return n}},body:{}},a=new Map;for(let n of t){let p={};for(let s of n.statement){let[m,y]=this.convertStatementToProperty(s);m&&y!==null&&y!==void 0&&(p[m]=y),this.collectImportsFromStatement(s,e,a)}o.body[n.name]=p}return o}convertStatementToProperty(e){if(e instanceof S)return[e.predicate.subject.name,e.object];if(e instanceof D)return[e.predicate.subject.name,e.object];if(e instanceof O)return[e.predicate.subject.name,e.object];if(e instanceof P)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof R){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof K){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof k?t.push(r.subject.name):r instanceof b&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[o,a]=this.convertStatementToProperty(r);o&&a!==null&&a!==void 0&&(t[o]=a)}return t}collectImportsFromStatement(e,t,r){}};function E(f){let e=f.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+X(f)}function X(f){return f instanceof I?"m:"+String(f.object):f instanceof S?"s:"+String(f.object):f instanceof D?"n:"+String(f.object):f instanceof O?"b:"+String(f.object):f instanceof P?"r:"+v(f.object):f instanceof K?"e:"+v(f.object):f instanceof R?"l:["+(f.object??[]).map(v).join("|")+"]":"x"}function v(f){if(!f)return"";if(f instanceof k){let e=f.subject;return"R("+(e?`${e.publisher}/${e.package_}/${e.name}`:"")+")"}return f instanceof b?"E("+(f.statement??[]).map(E).join(";")+")":f instanceof w?"L("+String(f.value)+")":"N"}export{b as a,w as b,I as c,Q as d,T as e,C as f};