@kanonak-protocol/sdk 4.14.0 → 4.16.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/auth/DeviceCertificateStore.d.ts +20 -1
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +2 -2
- package/dist/{chunk-HQQ4OAZ2.js → chunk-EZSHR3CB.js} +1 -1
- package/dist/{chunk-WGKIRLMA.js → chunk-GZPLWII7.js} +1 -1
- package/dist/{chunk-H37TY5AQ.js → chunk-IHB7UVEH.js} +1 -1
- package/dist/{chunk-R73T4RUO.js → chunk-MX3DEXMV.js} +1 -1
- package/dist/{chunk-OR3F4WIF.js → chunk-S6VSAKXB.js} +1 -1
- package/dist/{chunk-VDVJJ62W.js → chunk-TVSHIXLA.js} +1 -1
- package/dist/{chunk-QDSN5VM3.js → chunk-VZNNI2VR.js} +1 -1
- package/dist/{chunk-2HNPPYSK.js → chunk-WFQANMBQ.js} +1 -1
- package/dist/{chunk-MRNELSJF.js → chunk-ZO5IUMX6.js} +13 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.js +26 -26
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/KanonakVocabulary.d.ts +11 -0
- package/dist/reasoning/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/OntologyValidationResult.d.ts +12 -0
- package/dist/validation/ValidationSeverity.d.ts +7 -0
- package/dist/validation/index.d.ts +1 -1
- package/dist/validation/index.js +1 -1
- package/dist/validation/rules/repository/ReservedNameShadowRule.d.ts +24 -0
- package/dist/validation/rules/repository/index.d.ts +1 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(
|
|
1
|
+
import{a as br,b as Pr,c as wr,d as Sr,e as be}from"./chunk-TVSHIXLA.js";import{a as mn,c as we,e as Ue,h as Fe,i as Le,j as fn}from"./chunk-IHB7UVEH.js";import{a as gr,b as kr,c as hr,d as M,e as H,f as c,g as yn}from"./chunk-VZNNI2VR.js";import{a as dn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as Ft,b as Lt,c as Mt,d as Ht,e as zt,f as Qt,g as er,h as tr,i as rr}from"./chunk-GMEPM2QQ.js";import{a as Wt,b as Gt,c as Jt,d as R,f as qt,g as Zt,h as Xt}from"./chunk-JYBKSBB5.js";import{a as Ut}from"./chunk-4NO7MHS7.js";import{a as Rr,b as Cr,c as Er,d as xr}from"./chunk-S6VSAKXB.js";import{a as Ir,b as Br}from"./chunk-PEUTCG3B.js";import{a as $r}from"./chunk-PEJALHXK.js";import{a as Yt}from"./chunk-SC5M74NM.js";import{A as ln,B as un,K as pn,a as Vr,b as Or,c as Nr,d as _r,e as Ur,f as Fr,g as Lr,h as Mr,i as Hr,j as zr,k as Wr,l as Gr,m as Jr,n as qr,o as Zr,p as Yr,q as Xr,r as Qr,s as en,t as tn,u as rn,v as nn,w as on,x as an,y as sn,z as cn}from"./chunk-ZO5IUMX6.js";import{a as y,b as le,c as ar,h as L,i as Ne,j as mr,k as fr,l as j}from"./chunk-MX3DEXMV.js";import{a as I}from"./chunk-NJ3AZYQD.js";import{a as yr,b as Pe,c as Kr,d as g,e as jr,f as Dr,g as Ar,h as Tr}from"./chunk-WFQANMBQ.js";import{a as _e}from"./chunk-6U26UASC.js";import{a as sr,b as cr,c as $,d as lr,e as ur,g as pr,k as dr}from"./chunk-GZPLWII7.js";import{a as nr,b as ce,c as f,d as h,e as ir,f as ue,g as pe,h as de,i as me,j as fe,k as ye,l as ge,r as F,w as K,x as ke,y as he}from"./chunk-7BHDZHJY.js";import{a as or}from"./chunk-FUUTGGJS.js";import{a as At,b as se,c as U,d as Tt,e as k,f as Bt,g as Vt,h as Ot,i as Nt,j as _t}from"./chunk-2ACBWC7K.js";import{a as vr}from"./chunk-ODIECDN7.js";import{VersionOperator as Fa}from"@kanonak-protocol/types/document/models/enums";import{existsSync as On,readFileSync as Nn}from"fs";import{homedir as _n}from"os";import{join as Un}from"path";import{execFile as gn}from"child_process";import{promisify as kn}from"util";var z=kn(gn),hn="kanonak",W="/usr/bin/security",b=class{constructor(e=hn){this.service=e}service;async get(e){let t=c(e);try{let{stdout:n}=await z(W,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
|
|
2
|
+
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(Me(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${G(n)}
|
|
3
3
|
The Keychain may be locked or inaccessible.
|
|
4
|
-
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=
|
|
4
|
+
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=c(e),o=JSON.stringify(t);try{await z(W,["add-generic-password","-s",this.service,"-a",n,"-U","-w",o],{timeout:1e4})}catch(i){throw new Error(`macOS Keychain write failed for '${n}': ${G(i)}
|
|
5
5
|
Ensure the Keychain is unlocked and the CLI has write permission.
|
|
6
|
-
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=
|
|
7
|
-
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await
|
|
8
|
-
`))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${
|
|
9
|
-
${
|
|
6
|
+
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=c(e);try{await z(W,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(n){if(Me(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${G(n)}
|
|
7
|
+
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await z(W,["dump-keychain"],{timeout:1e4}),t=[],n=!1;for(let o of e.split(`
|
|
8
|
+
`))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${G(e)}`),[]}}};function Me(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function G(r){return r instanceof Error?r.message:String(r)}import{execFile as bn}from"child_process";import{promisify as Pn}from"util";var wn=Pn(bn),Sn="kanonak:",P=class{constructor(e=Sn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+c(e),n=`
|
|
9
|
+
${q}
|
|
10
10
|
$target = [Console]::In.ReadLine()
|
|
11
11
|
$ptr = [IntPtr]::Zero
|
|
12
12
|
$result = [CredMan]::CredRead($target, 1, 0, [ref]$ptr)
|
|
@@ -18,8 +18,8 @@ try {
|
|
|
18
18
|
[System.Text.Encoding]::Unicode.GetString($bytes)
|
|
19
19
|
} finally {
|
|
20
20
|
[CredMan]::CredFree($ptr)
|
|
21
|
-
}`;try{let{stdout:o}=await
|
|
22
|
-
${
|
|
21
|
+
}`;try{let{stdout:o}=await J(n,t),i=o.trim();return i?JSON.parse(i):null}catch{return null}}async store(e,t){let n=this.targetPrefix+c(e),o=JSON.stringify(t),i=`
|
|
22
|
+
${q}
|
|
23
23
|
$target = [Console]::In.ReadLine()
|
|
24
24
|
$json = [Console]::In.ReadLine()
|
|
25
25
|
$bytes = [System.Text.Encoding]::Unicode.GetBytes($json)
|
|
@@ -35,13 +35,13 @@ try {
|
|
|
35
35
|
if (-not $result) { throw "CredWrite failed" }
|
|
36
36
|
} finally {
|
|
37
37
|
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
|
|
38
|
-
}`;try{await
|
|
39
|
-
${o}`)}catch(a){throw new Error(`Windows Credential Manager write failed: ${String(a)}`)}}async remove(e){let t=this.targetPrefix+
|
|
40
|
-
${
|
|
38
|
+
}`;try{await J(i,`${n}
|
|
39
|
+
${o}`)}catch(a){throw new Error(`Windows Credential Manager write failed: ${String(a)}`)}}async remove(e){let t=this.targetPrefix+c(e),n=`
|
|
40
|
+
${q}
|
|
41
41
|
$target = [Console]::In.ReadLine()
|
|
42
|
-
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await
|
|
43
|
-
${
|
|
44
|
-
${
|
|
42
|
+
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await J(n,t)}catch{}}async list(){let e=`
|
|
43
|
+
${q}
|
|
44
|
+
${vn}
|
|
45
45
|
$prefix = [Console]::In.ReadLine()
|
|
46
46
|
$count = 0
|
|
47
47
|
$pCreds = [IntPtr]::Zero
|
|
@@ -55,8 +55,8 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
[CredMan]::CredFree($pCreds)
|
|
58
|
-
}`;try{let{stdout:t}=await
|
|
59
|
-
`).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function
|
|
58
|
+
}`;try{let{stdout:t}=await J(e,this.targetPrefix);return t.trim().split(`
|
|
59
|
+
`).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function J(r,e){for(let t of["pwsh","powershell"])try{return await wn(t,["-NoProfile","-NonInteractive","-Command",r],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(t==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var q=`
|
|
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=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function
|
|
90
|
+
"@`,vn="";import{execFile as Rn,spawn as Cn}from"child_process";import{promisify as En}from"util";var Z=En(Rn),xn="kanonak",w=class{constructor(e=xn){this.service=e}service;async get(e){let t=c(e);try{let{stdout:n}=await Z("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=c(e),o=JSON.stringify(t);await new Promise((i,a)=>{let s=Cn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",l=>{l===0?i():a(new Error(`secret-tool store exited with code ${l}`))}),s.on("error",a)})}async remove(e){let t=c(e);try{await Z("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await Z("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
|
|
91
|
+
`)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function D(){try{return await Z("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as He,mkdirSync as ze,readFileSync as We,writeFileSync as Ge}from"fs";import{createCipheriv as In,createDecipheriv as Kn,randomBytes as Je}from"crypto";import{homedir as $n}from"os";import{join as Re,dirname as qe}from"path";var Ye=Re($n(),".config","kanonak"),A=Re(Ye,"keyring.key"),jn=Re(Ye,"credentials.enc"),Ze="aes-256-gcm",Se=32,C=12,ve=16,S=class{constructor(e=jn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=c(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=c(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=c(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!He(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=We(this.secretsFile);if(t.length<C+ve)return{};let n=t.subarray(0,C),o=t.subarray(C,C+ve),i=t.subarray(C+ve),a=Kn(Ze,e,n);a.setAuthTag(o);let s=Buffer.concat([a.update(i),a.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=Je(C),o=In(Ze,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),a=Buffer.concat([o.update(i),o.final()]),s=o.getAuthTag(),l=Buffer.concat([n,s,a]);ze(qe(this.secretsFile),{recursive:!0}),Ge(this.secretsFile,l,{mode:384})}getOrCreateKey(){if(He(A)){let t=We(A);if(t.length!==Se)throw new Error(`Credential keyring key is corrupted (expected ${Se} bytes, got ${t.length}). Delete ${A} and re-authenticate.`);return t}let e=Je(Se);return ze(qe(A),{recursive:!0}),Ge(A,e,{mode:384}),e}};import{execFile as Dn}from"child_process";import{promisify as An}from"util";var Tn=An(Dn),Xe=3e4,T=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=c(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${Y(n)}
|
|
92
92
|
Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
|
|
93
|
-
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=
|
|
94
|
-
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=
|
|
95
|
-
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):
|
|
96
|
-
The helper may be waiting for authentication to an external vault.`):n}}};function Y(r){return r instanceof Error?r.message:String(r)}function
|
|
97
|
-
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as
|
|
98
|
-
The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),a.Authorization=`Bearer ${i.accessToken}`}}else a.Authorization=`Bearer ${i.accessToken}`;let s=await R(t,{method:o,headers:a});if(s.status===401&&i.dpopKeyPair){let
|
|
99
|
-
`;function ot(r=nt){if(!qn(r))return null;let e=Gn(r,"utf-8"),t=rt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function it(r,e=nt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=rt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Jn(e,Zn+n,"utf-8")}function at(r){return`sha256:${Yn("sha256").update(r).digest("hex")}`}import*as Ie from"js-yaml";import{canonicalForm as Xn,canonicalHash as Qn}from"@kanonak-protocol/canonical";function Ce(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as mt}from"@kanonak-protocol/canonical";function st(r){return Xn(Ce(r)?r:ct(r))}function Q(r){return Qn(Ce(r)?r:ct(r))}function ct(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:no(t),statements:xe(t.statement)});return{subjects:e}}function xe(r){let e=[];for(let t of r){let n=ro(t);if(!n)continue;let o=eo(t);o&&e.push({predicate:n,value:o})}return e}function eo(r){if(r instanceof le&&r.carrier)return{lit:r.lexical??String(r.object),datatype:ut(r.carrier)};if(r instanceof ue)return{raw:r.object};if(r instanceof pe)return{raw:r.lexical??String(r.object)};if(r instanceof de)return{raw:r.lexical??String(r.object)};if(r instanceof me)return{ref:pt(r.object)};if(r instanceof fe)return lt(r.object);if(r instanceof ye)return{list:r.object.map(to)}}function lt(r){let e=xe(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function to(r){if(r instanceof h)return{ref:pt(r)};if(r instanceof y)return lt(r);if(r instanceof ce){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:ut(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof se)return{embed:{statements:xe(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function ut(r){return r===F.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function ro(r){let e=r.predicate;if(e)return dt(e.subject)}function no(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function pt(r){return dt(r.subject)}function dt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as ft}from"@kanonak-protocol/types/document/models/enums";var oo="0.0.0",v=class{constructor(e,t=new x,n){this.repository=e;this.parser=t;this.objectParser=n??new $(this.parser)}repository;parser;objectParser;imports(){return new B}serializeValue(e,t){return kt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Ke(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let a={[o]:i,...e.body},s=this.dump(a);return{yaml:s,byteCount:gt(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},a=this.dump(i),s={yaml:a,byteCount:gt(a),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ie.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[yt]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ie.dump(o,{lineWidth:-1})),a=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Ne(i,this.repository))).filter(u=>u instanceof f&&u.namespace===a&&u.name!==yt);for(let u of c)u.namespace="ephemeral";return Q(c)}},yt="__pkgbuilder_probe__";function gt(r){return new TextEncoder().encode(r).length}function Ke(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var B=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=ft.Major){let a=`${e}/${t}@${n}`,s=this.byKey.get(a);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(a,{publisher:e,package_:t,version:n,alias:c,match:i}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,oo,o??t,ft.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ae(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=V(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function kt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof h)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>kt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(io(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function V(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function io(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ee=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${k(o)}`,a=this.produced.get(i);if(a)return a;let{document:s}=await e.produce(t,n,o);return this.produced.set(i,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=be(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var $e={async authorize(){return{allowed:!0}}},je={async record(){}},O=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},te=class{inner;ctx;policy;meter;constructor(e,t,n=$e,o=je){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new O(e,t.reason)}};var d="kanonak.org",m="view",ht="core-kanonak",ao={publisher:d,package_:m,name:"rootView"},so={publisher:d,package_:m,name:"bind"},co={publisher:d,package_:m,name:"produces"},lo={publisher:d,package_:m,name:"projections"},uo={publisher:d,package_:m,name:"where"},po={publisher:d,package_:m,name:"value"},mo={publisher:d,package_:m,name:"as"},re=class{constructor(e,t=new x){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new v(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=I(o,so);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let a=I(o,co);if(!a)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=fo(o),c=bt(n,d,ht),u=bt(n,d,m),p=this.builder.imports(),ne=p.ensure(d,ht,c,"ck"),wt=p.ensure(d,m,u,"v"),St=p.ref(a),Rt=new Fe(this.repository,this.parser,this.objectParser),Ae=new _e(Rt,n),Et=this.readProjections(n,o),vt=ko(o,uo),Ct=this.findInstances(n,i,await this.reason(t)),Te={},xt=new Set;for(let N of Ct){if(!await this.passesWhere(Ae,n,vt,N))continue;let ie={type:St};for(let Be of Et){let It=await this.evaluateValue(Ae,n,Be.value,N),Ve=this.builder.serializeValue(Pt(It),p);Ve!==void 0&&(ie[p.ref(Be.as)]=Ve)}let De=g(N);De&&(ie[`${wt}.derivedFrom`]=p.ref(De)),Te[this.rowName(N,xt)]=ie}let oe={};t.resolvedAt&&(oe[`${ne}.resolvedAt`]=t.resolvedAt),t.invocationId&&(oe[`${ne}.id`]=t.invocationId);let C=await this.builder.buildContentAddressed({publisher:s,book:p,body:Te,contentHashProperty:`${ne}.contentHash`,header:oe});return{yaml:C.yaml,contentHash:C.contentHash,packageName:C.packageName,publisher:C.publisher,rowCount:C.resourceCount}}resolveView(e,t){let n=U(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=I(n,ao);if(o){let i=U(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of ke(t,lo)){let i=o instanceof y?o:o instanceof h?U(e,o.subject):void 0;if(!i)continue;let a=ge(i,po),s=I(i,mo);a&&s&&n.push({value:a,as:s})}return n}async reason(e){return new he({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=go(e),i=[],a=new Set;for(let s of n.getInstancesOfClass(t)){if(a.has(s))continue;a.add(s);let c=o.get(s);c&&i.push(c)}return i.sort((s,c)=>{let u=K(g(s)),p=K(g(c));return u<p?-1:u>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let a=await this.evaluateValue(e,t,i,o);if(!ho(a))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ue(n,"view-projection",{catalog:t,depth:0}),a=new Map([["input",o]]);return e.evaluate(i,a)}rowName(e,t){let n=V(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Pt(r){return Pe(r)?r.value:Array.isArray(r)?r.map(Pt):r}function fo(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function bt(r,e,t){let n=yo(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function yo(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let i=g(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||_(i.version,n)>0)&&(n=i.version)}return n?k(n):void 0}function go(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let i=K(o),a=t.get(i);(!a||_(o.version,a)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function ko(r,e){let t=ge(r,e);return t?[t]:ke(r,e).filter(n=>n instanceof y)}function ho(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Pe(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{Xr as AmbiguousReferenceRule,de as BooleanStatement,mt as CANONICAL_FORM_VERSION,F as Carrier,nn as ClassDefinitionRule,zr as ClassHierarchyCycleRule,_t as CompositeKanonakDocumentRepository,Z as CredentialStore,se as DefinedKanonak,X as DeviceCertificateStore,Nt as DocumentLocation,mr as EdgeType,y as EmbeddedKanonak,Lr as EmbeddedKanonakTypeRule,fe as EmbeddedStatement,O as EntitlementDeniedError,te as EntitlementProducer,Ot as FileSystemKanonakDocumentRepository,br as GitIgnoreFilter,fr as GraphBuilder,Jt as HttpKanonakDocumentRepository,B as ImportBook,Mr as ImportExistenceRule,Vt as InMemoryKanonakDocumentRepository,Lt as KANONAK_USER_AGENT,Qt as Kanonak,wr as KanonakDocumentPositions,$ as KanonakObjectParser,an as KanonakObjectValidator,x as KanonakParser,er as KanonakUri,Er as KanonakUriBuilder,Cr as KanonakUrlResolver,cr as KanonakVocabulary,ye as ListStatement,ce as LiteralKanonak,qt as LocalFirstRepository,Yt as LockAwareRepository,ln as LookRenderer,on as MarkdownLinkRule,rr as MarkdownStatement,Yr as NamespaceImportCycleRule,Or as NamespacePrefixRule,dr as NodeType,pe as NumberStatement,kr as OWL_RL_CLASSIFICATION_RULES,en as ObjectPropertyValueValidationRule,Dr as OntologyValidationError,Ar as OntologyValidationResult,v as PackageBuilder,Fr as PackageHeaderRule,ee as ProducerRepository,tn as PropertyDomainRule,Wr as PropertyHierarchyCycleRule,rn as PropertyKindRangeConsistencyRule,Pr as PropertyMetadata,Qr as PropertyRangeReferenceRule,Gr as PropertyRangeRequiredRule,_r as PropertyTypeSpecificityRule,zt as PublisherConfigResolver,Wt as PublisherIndex,gr as RDFS_RULES,he as Reasoner,hr as ReasoningResult,h as ReferenceKanonak,me as ReferenceStatement,Ft as RepositoryFactory,Nr as ResourceNamingRule,nr as ResourceResolver,pr as ResourceTypeClassifier,le as ScalarStatement,tr as Statement,ue as StringStatement,Jr as SubClassOfReferenceRule,qr as SubPropertyOfReferenceRule,f as SubjectKanonak,Ur as SubjectKanonakTypeRequiredRule,yr as TripleStore,or as TypeResolver,Zr as UnresolvedPredicateRule,Hr as UnresolvedReferenceRule,Vr as ValidationCache,Br as ValidationContext,Tr as ValidationSeverity,Da as VersionOperator,re as ViewMaterializer,$e as allowAllPolicy,Gt as assertPackageIdentity,Xt as buildLocalFirstRepository,un as buildOntologyModel,st as canonicalForm,Q as canonicalHash,Oe as carrierOf,Zt as collectKanonakFiles,_ as compareVersions,at as computeIntegrity,Ke as contentAddressedName,$r as contextTypesOf,tt as createAuthenticatedFetch,D as createDPoPProof,jt as createVersion,ur as extractMarkdownLinks,sn as findDerivation,jr as findInstancesByType,lr as findMalformedReferences,Rr as findMarkdownLinkAt,vr as formatKanonakAddress,k as formatVersion,Qe as generateDPoPKeyPair,Ut as getGlobalCachePath,Ht as getKanonakUserAgent,M as hasValidToken,Tt as isCompatibleVersion,L as isExpired,Dt as isMajorCompatible,R as kanonakFetch,ot as loadLockFile,ir as makeUriKey,je as noopMeter,l as normalizeHost,be as parseKanonakAddress,At as parseVersionString,Sr as parseWithPositions,Bt as pickHighestDocument,Ir as propertiesInScope,cn as resolveDisplayValue,Kr as resolvePropertyStep,V as sanitizeName,it as saveLockFile,et as serverSupportsDPoP,Mt as setKanonakUserAgent,g as subjectUri,xr as superClassChain,ar as tripleKey,K as uriKey,sr as uriTriple,Kt as versionOperatorFromChar,ae as versionOperatorToChar,$t as versionsEqual};
|
|
93
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=c(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${Y(o)}
|
|
94
|
+
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=c(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${Y(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${Y(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await Tn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Xe});return n}catch(n){throw Bn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
95
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Vn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Xe/1e3}s on '${e}'.
|
|
96
|
+
The helper may be waiting for authentication to an external vault.`):n}}};function Y(r){return r instanceof Error?r.message:String(r)}function Bn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function Vn(r){return r instanceof Error&&"killed"in r&&r.killed}var Ce=Un(_n(),".kanonak","config.json"),X=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Fn(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!H(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=Ln();return e.credentialHelper?new T(e.credentialHelper):process.platform==="darwin"?new b:process.platform==="win32"?new P:await D()?new w:new S}};function Fn(r){let t="KANONAK_TOKEN_"+c(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Ln(){if(!On(Ce))return{};try{return JSON.parse(Nn(Ce,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ce}: ${e}
|
|
97
|
+
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as tt}from"os";import{join as v}from"path";import{mkdir as Mn,writeFile as Qe,readFile as et,rm as Hn}from"fs/promises";var Ee="kanonak-device",zn=v(tt(),".config","kanonak","device-credentials.enc"),Wn=v(tt(),".kanonak","devices"),Q=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=c(e).replace(/[^a-zA-Z0-9._-]/g,"_");return v(this.deps.certBaseDir??Wn,t)}async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){let t=await(await this.getBackend()).get(e);if(!t)return null;if(typeof t.certificatePem=="string"&&typeof t.chainPem=="string")return t;let n=this.certDir(e),o,i;try{o=await et(v(n,"cert.pem"),"utf-8"),i=await et(v(n,"chain.pem"),"utf-8")}catch{return null}return{...t,certificatePem:o,chainPem:i}}async store(e,t){let{certificatePem:n,chainPem:o,...i}=t,a=this.certDir(e);await Mn(a,{recursive:!0}),await Qe(v(a,"cert.pem"),n,"utf-8"),await Qe(v(a,"chain.pem"),o,"utf-8"),await(await this.getBackend()).store(e,i)}async remove(e){await(await this.getBackend()).remove(e),await Hn(this.certDir(e),{recursive:!0,force:!0})}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new b(Ee):process.platform==="win32"?new P(`${Ee}:`):await D()?new w(Ee):new S(zn)}};import{createHash as Gn,createPrivateKey as Jn,generateKeyPairSync as qn,randomUUID as Zn,sign as Yn}from"crypto";function nt(){let{publicKey:r,privateKey:e}=qn("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function B(r,e,t,n,o,i){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Zn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Gn("sha256").update(o).digest("base64url")),i&&(s.nonce=i),Xn(a,s,r)}function ot(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Xn(r,e,t){let n=rt(JSON.stringify(r)),o=rt(JSON.stringify(e)),i=`${n}.${o}`,a=Jn({key:t,format:"jwk"}),l=Yn("SHA256",Buffer.from(i),{key:a,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${l}`}function rt(r){return Buffer.from(r,"utf-8").toString("base64url")}function it(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return R(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return R(t,{method:o});M(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let a={};if(i.dpopKeyPair){let l=e.get(n);try{let u=B(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,l);a.Authorization=`DPoP ${i.accessToken}`,a.DPoP=u}catch(u){let p=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${n}': ${p}
|
|
98
|
+
The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),a.Authorization=`Bearer ${i.accessToken}`}}else a.Authorization=`Bearer ${i.accessToken}`;let s=await R(t,{method:o,headers:a});if(s.status===401&&i.dpopKeyPair){let l=s.headers.get("DPoP-Nonce");if(l){e.set(n,l);try{let u=B(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,l);a.DPoP=u,s=await R(t,{method:o,headers:a})}catch{}}}return s}}import{readFileSync as Qn,writeFileSync as eo,existsSync as to}from"fs";import{createHash as ro}from"crypto";import at from"js-yaml";var st="kanonak.lock",no=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
99
|
+
`;function ct(r=st){if(!to(r))return null;let e=Qn(r,"utf-8"),t=at.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function lt(r,e=st){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=at.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});eo(e,no+n,"utf-8")}function ut(r){return`sha256:${ro("sha256").update(r).digest("hex")}`}import*as Ke from"js-yaml";import{canonicalForm as oo,canonicalHash as io}from"@kanonak-protocol/canonical";function xe(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as kt}from"@kanonak-protocol/canonical";function pt(r){return oo(xe(r)?r:dt(r))}function ee(r){return io(xe(r)?r:dt(r))}function dt(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:lo(t),statements:Ie(t.statement)});return{subjects:e}}function Ie(r){let e=[];for(let t of r){let n=co(t);if(!n)continue;let o=ao(t);o&&e.push({predicate:n,value:o})}return e}function ao(r){if(r instanceof ue&&r.carrier)return{lit:r.lexical??String(r.object),datatype:ft(r.carrier)};if(r instanceof pe)return{raw:r.object};if(r instanceof de)return{raw:r.lexical??String(r.object)};if(r instanceof me)return{raw:r.lexical??String(r.object)};if(r instanceof fe)return{ref:yt(r.object)};if(r instanceof ye)return mt(r.object);if(r instanceof ge)return{list:r.object.map(so)}}function mt(r){let e=Ie(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function so(r){if(r instanceof h)return{ref:yt(r)};if(r instanceof y)return mt(r);if(r instanceof le){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:ft(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof ce)return{embed:{statements:Ie(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function ft(r){return r===L.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function co(r){let e=r.predicate;if(e)return gt(e.subject)}function lo(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function yt(r){return gt(r.subject)}function gt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as ht}from"@kanonak-protocol/types/document/models/enums";var uo="0.0.0",E=class{constructor(e,t=new I,n){this.repository=e;this.parser=t;this.objectParser=n??new j(this.parser)}repository;parser;objectParser;imports(){return new V}serializeValue(e,t){return wt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=$e(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let a={[o]:i,...e.body},s=this.dump(a);return{yaml:s,byteCount:Pt(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},a=this.dump(i),s={yaml:a,byteCount:Pt(a),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ke.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[bt]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ke.dump(o,{lineWidth:-1})),a=i.metadata.namespace_?.toString(),l=(await this.objectParser.parseKanonaks(new _e(i,this.repository))).filter(u=>u instanceof f&&u.namespace===a&&u.name!==bt);for(let u of l)u.namespace="ephemeral";return ee(l)}},bt="__pkgbuilder_probe__";function Pt(r){return new TextEncoder().encode(r).length}function $e(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var V=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=ht.Major){let a=`${e}/${t}@${n}`,s=this.byKey.get(a);if(s)return s.alias;let l=this.uniqueAlias(o);return this.byKey.set(a,{publisher:e,package_:t,version:n,alias:l,match:i}),l}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,uo,o??t,ht.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:se(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=O(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function wt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof h)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>wt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(po(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function O(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function po(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var te=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${k(o)}`,a=this.produced.get(i);if(a)return a;let{document:s}=await e.produce(t,n,o);return this.produced.set(i,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=Pe(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var je={async authorize(){return{allowed:!0}}},De={async record(){}},N=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},re=class{inner;ctx;policy;meter;constructor(e,t,n=je,o=De){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new N(e,t.reason)}};var d="kanonak.org",m="view",St="core-kanonak",mo={publisher:d,package_:m,name:"rootView"},fo={publisher:d,package_:m,name:"bind"},yo={publisher:d,package_:m,name:"produces"},go={publisher:d,package_:m,name:"projections"},ko={publisher:d,package_:m,name:"where"},ho={publisher:d,package_:m,name:"value"},bo={publisher:d,package_:m,name:"as"},ne=class{constructor(e,t=new I){this.repository=e;this.parser=t;this.objectParser=new j(this.parser),this.builder=new E(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=K(o,fo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let a=K(o,yo);if(!a)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=Po(o),l=vt(n,d,St),u=vt(n,d,m),p=this.builder.imports(),oe=p.ensure(d,St,l,"ck"),Ct=p.ensure(d,m,u,"v"),Et=p.ref(a),xt=new Le(this.repository,this.parser,this.objectParser),Ae=new Ue(xt,n),It=this.readProjections(n,o),Kt=vo(o,ko),$t=this.findInstances(n,i,await this.reason(t)),Te={},jt=new Set;for(let _ of $t){if(!await this.passesWhere(Ae,n,Kt,_))continue;let ae={type:Et};for(let Ve of It){let Dt=await this.evaluateValue(Ae,n,Ve.value,_),Oe=this.builder.serializeValue(Rt(Dt),p);Oe!==void 0&&(ae[p.ref(Ve.as)]=Oe)}let Be=g(_);Be&&(ae[`${Ct}.derivedFrom`]=p.ref(Be)),Te[this.rowName(_,jt)]=ae}let ie={};t.resolvedAt&&(ie[`${oe}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ie[`${oe}.id`]=t.invocationId);let x=await this.builder.buildContentAddressed({publisher:s,book:p,body:Te,contentHashProperty:`${oe}.contentHash`,header:ie});return{yaml:x.yaml,contentHash:x.contentHash,packageName:x.packageName,publisher:x.publisher,rowCount:x.resourceCount}}resolveView(e,t){let n=F(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=K(n,mo);if(o){let i=F(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of he(t,go)){let i=o instanceof y?o:o instanceof h?F(e,o.subject):void 0;if(!i)continue;let a=ke(i,ho),s=K(i,bo);a&&s&&n.push({value:a,as:s})}return n}async reason(e){return new be({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=So(e),i=[],a=new Set;for(let s of n.getInstancesOfClass(t)){if(a.has(s))continue;a.add(s);let l=o.get(s);l&&i.push(l)}return i.sort((s,l)=>{let u=$(g(s)),p=$(g(l));return u<p?-1:u>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let a=await this.evaluateValue(e,t,i,o);if(!Ro(a))return!1}return!0}async evaluateValue(e,t,n,o){let i=Fe(n,"view-projection",{catalog:t,depth:0}),a=new Map([["input",o]]);return e.evaluate(i,a)}rowName(e,t){let n=O(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Rt(r){return we(r)?r.value:Array.isArray(r)?r.map(Rt):r}function Po(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function vt(r,e,t){let n=wo(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function wo(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let i=g(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||U(i.version,n)>0)&&(n=i.version)}return n?k(n):void 0}function So(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let i=$(o),a=t.get(i);(!a||U(o.version,a)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function vo(r,e){let t=ke(r,e);return t?[t]:he(r,e).filter(n=>n instanceof y)}function Ro(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:we(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{rn as AmbiguousReferenceRule,me as BooleanStatement,kt as CANONICAL_FORM_VERSION,L as Carrier,ln as ClassDefinitionRule,qr as ClassHierarchyCycleRule,Mt as CompositeKanonakDocumentRepository,X as CredentialStore,ce as DefinedKanonak,Q as DeviceCertificateStore,Lt as DocumentLocation,kr as EdgeType,y as EmbeddedKanonak,Wr as EmbeddedKanonakTypeRule,ye as EmbeddedStatement,N as EntitlementDeniedError,re as EntitlementProducer,Ft as FileSystemKanonakDocumentRepository,vr as GitIgnoreFilter,hr as GraphBuilder,Xt as HttpKanonakDocumentRepository,V as ImportBook,Gr as ImportExistenceRule,Ut as InMemoryKanonakDocumentRepository,Wt as KANONAK_USER_AGENT,nr as Kanonak,Cr as KanonakDocumentPositions,j as KanonakObjectParser,pn as KanonakObjectValidator,I as KanonakParser,or as KanonakUri,Ir as KanonakUriBuilder,$r as KanonakUrlResolver,dr as KanonakVocabulary,ge as ListStatement,le as LiteralKanonak,Qt as LocalFirstRepository,er as LockAwareRepository,fn as LookRenderer,un as MarkdownLinkRule,ar as MarkdownStatement,en as NamespaceImportCycleRule,Fr as NamespacePrefixRule,gr as NodeType,de as NumberStatement,wr as OWL_RL_CLASSIFICATION_RULES,on as ObjectPropertyValueValidationRule,Nr as OntologyValidationError,Vr as OntologyValidationResult,E as PackageBuilder,zr as PackageHeaderRule,te as ProducerRepository,an as PropertyDomainRule,Zr as PropertyHierarchyCycleRule,sn as PropertyKindRangeConsistencyRule,Rr as PropertyMetadata,nn as PropertyRangeReferenceRule,Yr as PropertyRangeRequiredRule,Mr as PropertyTypeSpecificityRule,qt as PublisherConfigResolver,Zt as PublisherIndex,Pr as RDFS_RULES,be as Reasoner,Sr as ReasoningResult,h as ReferenceKanonak,fe as ReferenceStatement,zt as RepositoryFactory,cn as ReservedNameShadowRule,Lr as ResourceNamingRule,sr as ResourceResolver,yr as ResourceTypeClassifier,ue as ScalarStatement,ir as Statement,pe as StringStatement,Xr as SubClassOfReferenceRule,Qr as SubPropertyOfReferenceRule,f as SubjectKanonak,Hr as SubjectKanonakTypeRequiredRule,br as TripleStore,cr as TypeResolver,tn as UnresolvedPredicateRule,Jr as UnresolvedReferenceRule,Ur as ValidationCache,_r as ValidationContext,Or as ValidationSeverity,Fa as VersionOperator,ne as ViewMaterializer,je as allowAllPolicy,Yt as assertPackageIdentity,rr as buildLocalFirstRepository,yn as buildOntologyModel,pt as canonicalForm,ee as canonicalHash,Ne as carrierOf,tr as collectKanonakFiles,U as compareVersions,ut as computeIntegrity,$e as contentAddressedName,Tr as contextTypesOf,it as createAuthenticatedFetch,B as createDPoPProof,Bt as createVersion,fr as extractMarkdownLinks,dn as findDerivation,Br as findInstancesByType,mr as findMalformedReferences,xr as findMarkdownLinkAt,Kr as formatKanonakAddress,k as formatVersion,nt as generateDPoPKeyPair,Ht as getGlobalCachePath,Jt as getKanonakUserAgent,H as hasValidToken,Ot as isCompatibleVersion,M as isExpired,Nt as isMajorCompatible,R as kanonakFetch,ct as loadLockFile,lr as makeUriKey,De as noopMeter,c as normalizeHost,Pe as parseKanonakAddress,Vt as parseVersionString,Er as parseWithPositions,_t as pickHighestDocument,Dr as propertiesInScope,mn as resolveDisplayValue,Ar as resolvePropertyStep,O as sanitizeName,lt as saveLockFile,ot as serverSupportsDPoP,Gt as setKanonakUserAgent,g as subjectUri,jr as superClassChain,ur as tripleKey,$ as uriKey,pr as uriTriple,At as versionOperatorFromChar,se as versionOperatorToChar,Tt as versionsEqual};
|
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-S6VSAKXB.js";import{l as b}from"../chunk-MX3DEXMV.js";import{a}from"../chunk-NJ3AZYQD.js";import"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
|
|
@@ -9,6 +9,17 @@ import type { Vocabulary } from './Vocabulary.js';
|
|
|
9
9
|
* imported — and therefore must never be treated as an "unresolved predicate."
|
|
10
10
|
*/
|
|
11
11
|
export declare function isBuiltinTerm(name: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The canonical home package of a reserved built-in term (`Class` → core-rdf,
|
|
14
|
+
* `ObjectProperty` → core-owl, `Package` → core-kanonak, …), or `undefined` for
|
|
15
|
+
* a non-built-in name. A package that defines a LOCAL entity with a built-in
|
|
16
|
+
* name whose home is a DIFFERENT package shadows the built-in — see the
|
|
17
|
+
* reserved-name shadow check.
|
|
18
|
+
*/
|
|
19
|
+
export declare function builtinHome(name: string): {
|
|
20
|
+
publisher: string;
|
|
21
|
+
package_: string;
|
|
22
|
+
} | undefined;
|
|
12
23
|
/**
|
|
13
24
|
* Canonicalize a built-in URI in place against {@link BUILTIN_HOMES}.
|
|
14
25
|
*
|
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-TVSHIXLA.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import{c as a,d as b,e as c,g as d,j as e,k as f}from"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{f as KanonakVocabulary,i as OWL_RL_CLASSIFICATION_RULES,h as RDFS_RULES,k as Reasoner,j as ReasoningResult,g as TripleStore,e as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
|
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-WFQANMBQ.js";import"../chunk-6U26UASC.js";import{a as m,b as n}from"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import{a as l}from"../chunk-FUUTGGJS.js";import{a,b,c,d,e,f,g,h,i,j}from"../chunk-2ACBWC7K.js";export{l as KanonakUri,p as KanonakUriBuilder,s as KanonakUrlResolver,m as ResourceResolver,o as ResourceTypeClassifier,n as TypeResolver,k as assertPackageIdentity,c as compareVersions,x as contextTypesOf,f as createVersion,y as findInstancesByType,r as formatKanonakAddress,e as formatVersion,h as isCompatibleVersion,i as isMajorCompatible,q as parseKanonakAddress,g as parseVersionString,j as pickHighestDocument,v as propertiesInScope,w as resolvePropertyStep,t as subjectUri,u as superClassChain,a as versionOperatorFromChar,b as versionOperatorToChar,d as versionsEqual};
|
package/dist/search/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as g}from"../chunk-
|
|
1
|
+
import{a as g}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import{d as m,h as S}from"../chunk-WFQANMBQ.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as v,m as p,r as E}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
|
|
2
2
|
Install it with:
|
|
3
3
|
npm install @huggingface/transformers
|
|
4
4
|
(underlying import error: ${e.message})`)}return F({transformers:r})})()),y}function H(r,e){let t=0;for(let n=0;n<r.length;n++)t+=r[n]*e[n];return t}function R(r,e){return e?r.version?e.version?x(r.version,e.version)>0:!0:!1:!0}function K(r,e){let t=g(r,e),n=[t.label],s=S(e);if(s.length>0){let i=E(r,s[0]),a=i?g(r,i).label:s[0].name;a&&n.push(`\u2014 a ${a}.`)}return t.summary&&n.push(t.summary),n.join(" ")}function q(r){let e=new Map;for(let t of r){if(!(t instanceof v))continue;let n=m(t);if(!n)continue;let s=p(n),i=e.get(s);(!i||R(n,m(i)))&&e.set(s,t)}return[...e.values()].sort((t,n)=>{let s=m(t)?p(m(t)):t.name,i=m(n)?p(m(n)):n.name;return s.localeCompare(i)})}var k=class{entries=[];embedder;constructor(e={}){this.embedder=e.embedder}resolveEmbedder(){return this.embedder?Promise.resolve(this.embedder):U()}get size(){return this.entries.length}async build(e,t={}){let n=q(e);if(t.include&&(n=n.filter(t.include)),n.length===0)return this.entries=[],{size:0,cached:!1};let s=n.map(o=>K(e,o)),i=t.cacheDir,a;if(i){let o=C("sha256").update(h+"|"+w+`
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as ee}from"../chunk-H37TY5AQ.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as O,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{l as X}from"../chunk-R73T4RUO.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as Z}from"../chunk-2HNPPYSK.js";import"../chunk-6U26UASC.js";import"../chunk-WGKIRLMA.js";import{c as be,s as Q}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as M,e as F,f as L,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as De,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";function Se(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function H(t,e){let n=new Set,r=[...t];for(;r.length>0;){let s=r.shift(),a=Se(s);if(!a||n.has(a))continue;n.add(a);let m=s.metadata?.imports;if(m)for(let[p,k]of Object.entries(m))for(let d of k)try{let u=await e.getHighestCompatibleVersionAsync(p,d);u&&r.push(u)}catch{}}return n}var V=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let r=Se(n);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var we=[{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 T(t){let e=t?.render;if(e&&e.length>0){let n=[];for(let r of e)try{let s=Z(r);s.kind==="package"?n.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&n.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(n.length>0)return n}return we}function C(t){return`${t.publisher}/${t.package_}`}function W(t){let e={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},n=[];for(let r of t)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";n.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&n.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return n}function re(t){let{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,renderStack:p,producers:k}=t,d=new Map,u=new Map,o=new Map,h=new Set;for(let y of r){if(!(y instanceof be))continue;let b=y.namespace||"";if(!a.has(b))continue;d.set(`${b}/${y.name}`,y);let $=b.split("/")[1]??"",[w,_]=$.split("@");if(!w||!_)continue;let I=ue(_);I&&(h.has($)||(h.add($),u.has(w)||u.set(w,[]),u.get(w).push({verStr:_,version:I})),y.name===w&&o.set($,y))}for(let y of u.values())y.sort((b,$)=>M($.version,b.version));return{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,bySubject:d,pkgVersions:u,pkgSelfByVer:o,renderStack:p,...k?{producers:k}:{}}}async function se(t,e={}){let n=new E,r=new ge(n),s=[],a=[];for(let c of J(t)){let l;try{l=De(c,"utf-8")}catch{continue}let v;try{v=n.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:F(N),version:N,source:l})}a.sort((c,l)=>M(l.version,c.version));for(let c of a)await r.saveDocumentAsync(n.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),s.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(s.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!m.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)p=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let k=new Set,d=new Map;for(let c of s)c.publisher===p&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),o=new he(u,!0,n),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let y=e.repository??new ye(r,o,new Y(h)),b=e.log??(()=>{}),$=T(void 0),w=[],_=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>M(v,l)).map(F);if(!e.repository){b(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new O({fetchFn:e.fetchFn}):new O;for(let l of $){let v=C(l),N=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(N.length>0){let S=_(N);w.push({...l,origin:"workspace",versions:S}),b(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await o.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=_(U);w.push({...l,origin:"cache",versions:S}),b(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let f=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let j=await c.getPackageUrl(l.publisher,l.package_,S),i=await(e.fetchFn?e.fetchFn(j,l.publisher):me(j));if(!i.ok){let f=`fetch ${j} failed: HTTP ${i.status} ${i.statusText}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let g=await i.text();await r.saveDocumentAsync(n.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let f=$e(u,l.publisher);je(f,{recursive:!0}),_e($e(f,`${l.package_}@${S}.kan.yml`),g,"utf-8"),w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, installed to cache`)}catch(f){w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, but cache ${u} is NOT WRITABLE (${f.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let j=`fetch failed: ${S.message}`;w.push({...l,origin:"missing",reason:j}),b(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let I=y;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await H(c,y);for(let v of $)l.add(C(v));I=new V(y,l)}let B=await new X(n).parseKanonaks(I),oe=new ee(B),G=(c,l)=>Q(B,{publisher:c,package_:l,name:l}).length>0,A;if(e.repository){A=[];for(let c of $){let l=await y.getDocumentsByNamespaceAsync(c.publisher,c.package_);A.push(l.length>0?{...c,origin:"repository",versions:_(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=w.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=W(A);for(let c of q)b(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:m,catalog:B,lookRenderer:oe,localNamespaces:k,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:A,warnings:q}})}import{existsSync as Ce,readFileSync as Ae,writeFileSync as Ie,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function ae(t,e={}){let n=new E,r=Z(t),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),m=e.cacheRoot??z(),p=(i,g,f)=>Re(m,i,`${g}@${f}.kan.yml`),k=new Set,d=new Set,u=new Map,o=new Y({getFromCache:(i,g,f)=>{let D=p(i,g,f),R=Ce(D)?Ae(D,"utf-8"):null;return R!==null&&k.add(`${i}/${g}`),R},onFetch:(i,g,f,D)=>{d.add(`${i}/${g}`);try{let R=Re(m,i);Ne(R,{recursive:!0}),Ie(p(i,g,f),D,"utf-8")}catch(R){u.set(`${i}/${g}`,R.message),a(`[render] fetched ${i}/${g}@${f} but cache ${m} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new O(e.fetchFn?{fetchFn:e.fetchFn}:void 0),y;if(r.kind==="resource"){let i=r.uri.version;y=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;y=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else y=(await h.listLatestPackages(s)).map(g=>({package_:g.packageName}));let b=async(i,g,f)=>{try{let D=f?n.buildImport(g,"=",f,i):n.buildImport(g,"*","0.0.0",i),R=await o.getHighestCompatibleVersionAsync(i,D);return R?{doc:R}:{doc:null,error:`${i} did not resolve ${g}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(D){return{doc:null,error:D.message}}},$=[],w=[];for(let i of y){let{doc:g,error:f}=await b(s,i.package_,i.version);g?$.push(g):f&&w.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${s}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=await new ke(e.fetchFn).getConfig(s).catch(()=>{}),I=T(_),B=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,f)=>M(f,g)).map(F);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${B}); cache: ${m}`);let G=[],A=[];for(let i of I){let g=C(i),{doc:f,error:D}=await b(i.publisher,i.package_,void 0);if(f){G.push(f);let R=oe([f]),pe=d.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...i,origin:pe,versions:R}),a(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...i,origin:"missing",reason:D??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${D??"unresolved"}`)}let q=await H([...$,...G],o),de=new V(o,q),c=await new X(n).parseKanonaks(de),l=new ee(c),v=A.map(i=>i.origin==="missing"||Q(c,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),N=W(v);for(let i of N)a(`[render-stack] WARNING: ${i}`);let U={contractSource:B,cachePath:m,packages:v,warnings:N},S=new Set,j=new Map;for(let i of await o.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==s)continue;let f=F(g.version),D=`${g.publisher}/${g.package_}@${f}`;S.add(D);let R=await o.getDocumentContentAsync(D);R!==null&&j.set(`${g.package_}@${f}`,R)}return re({publisher:s,availablePublishers:[s],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:j,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:n,renderStack:r,catalog:s}=t,a=e.explainStylesheet(e.publisherSubject(n)),m=[...a.tokens.entries()].map(([o,h])=>({name:o,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,k={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},d=new Map;for(let o of s){let h=o.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([o,h])=>({namespace:o,resources:h})).sort((o,h)=>o.namespace.localeCompare(h.namespace));return{publisher:n,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ie(t){let e=Fe,n=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
|
|
1
|
+
import{j as ee}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as O,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{l as X}from"../chunk-MX3DEXMV.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as Z}from"../chunk-WFQANMBQ.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as be,s as Q}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as M,e as F,f as L,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as De,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";function Se(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function H(t,e){let n=new Set,r=[...t];for(;r.length>0;){let s=r.shift(),a=Se(s);if(!a||n.has(a))continue;n.add(a);let m=s.metadata?.imports;if(m)for(let[p,k]of Object.entries(m))for(let d of k)try{let u=await e.getHighestCompatibleVersionAsync(p,d);u&&r.push(u)}catch{}}return n}var V=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let r=Se(n);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var we=[{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 T(t){let e=t?.render;if(e&&e.length>0){let n=[];for(let r of e)try{let s=Z(r);s.kind==="package"?n.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&n.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(n.length>0)return n}return we}function C(t){return`${t.publisher}/${t.package_}`}function W(t){let e={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},n=[];for(let r of t)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";n.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&n.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return n}function re(t){let{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,renderStack:p,producers:k}=t,d=new Map,u=new Map,o=new Map,h=new Set;for(let y of r){if(!(y instanceof be))continue;let b=y.namespace||"";if(!a.has(b))continue;d.set(`${b}/${y.name}`,y);let $=b.split("/")[1]??"",[w,_]=$.split("@");if(!w||!_)continue;let I=ue(_);I&&(h.has($)||(h.add($),u.has(w)||u.set(w,[]),u.get(w).push({verStr:_,version:I})),y.name===w&&o.set($,y))}for(let y of u.values())y.sort((b,$)=>M($.version,b.version));return{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,bySubject:d,pkgVersions:u,pkgSelfByVer:o,renderStack:p,...k?{producers:k}:{}}}async function se(t,e={}){let n=new E,r=new ge(n),s=[],a=[];for(let c of J(t)){let l;try{l=De(c,"utf-8")}catch{continue}let v;try{v=n.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:F(N),version:N,source:l})}a.sort((c,l)=>M(l.version,c.version));for(let c of a)await r.saveDocumentAsync(n.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),s.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(s.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!m.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)p=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let k=new Set,d=new Map;for(let c of s)c.publisher===p&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),o=new he(u,!0,n),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let y=e.repository??new ye(r,o,new Y(h)),b=e.log??(()=>{}),$=T(void 0),w=[],_=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>M(v,l)).map(F);if(!e.repository){b(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new O({fetchFn:e.fetchFn}):new O;for(let l of $){let v=C(l),N=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(N.length>0){let S=_(N);w.push({...l,origin:"workspace",versions:S}),b(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await o.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=_(U);w.push({...l,origin:"cache",versions:S}),b(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let f=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let j=await c.getPackageUrl(l.publisher,l.package_,S),i=await(e.fetchFn?e.fetchFn(j,l.publisher):me(j));if(!i.ok){let f=`fetch ${j} failed: HTTP ${i.status} ${i.statusText}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let g=await i.text();await r.saveDocumentAsync(n.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let f=$e(u,l.publisher);je(f,{recursive:!0}),_e($e(f,`${l.package_}@${S}.kan.yml`),g,"utf-8"),w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, installed to cache`)}catch(f){w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, but cache ${u} is NOT WRITABLE (${f.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let j=`fetch failed: ${S.message}`;w.push({...l,origin:"missing",reason:j}),b(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let I=y;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await H(c,y);for(let v of $)l.add(C(v));I=new V(y,l)}let B=await new X(n).parseKanonaks(I),oe=new ee(B),G=(c,l)=>Q(B,{publisher:c,package_:l,name:l}).length>0,A;if(e.repository){A=[];for(let c of $){let l=await y.getDocumentsByNamespaceAsync(c.publisher,c.package_);A.push(l.length>0?{...c,origin:"repository",versions:_(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=w.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=W(A);for(let c of q)b(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:m,catalog:B,lookRenderer:oe,localNamespaces:k,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:A,warnings:q}})}import{existsSync as Ce,readFileSync as Ae,writeFileSync as Ie,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function ae(t,e={}){let n=new E,r=Z(t),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),m=e.cacheRoot??z(),p=(i,g,f)=>Re(m,i,`${g}@${f}.kan.yml`),k=new Set,d=new Set,u=new Map,o=new Y({getFromCache:(i,g,f)=>{let D=p(i,g,f),R=Ce(D)?Ae(D,"utf-8"):null;return R!==null&&k.add(`${i}/${g}`),R},onFetch:(i,g,f,D)=>{d.add(`${i}/${g}`);try{let R=Re(m,i);Ne(R,{recursive:!0}),Ie(p(i,g,f),D,"utf-8")}catch(R){u.set(`${i}/${g}`,R.message),a(`[render] fetched ${i}/${g}@${f} but cache ${m} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new O(e.fetchFn?{fetchFn:e.fetchFn}:void 0),y;if(r.kind==="resource"){let i=r.uri.version;y=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;y=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else y=(await h.listLatestPackages(s)).map(g=>({package_:g.packageName}));let b=async(i,g,f)=>{try{let D=f?n.buildImport(g,"=",f,i):n.buildImport(g,"*","0.0.0",i),R=await o.getHighestCompatibleVersionAsync(i,D);return R?{doc:R}:{doc:null,error:`${i} did not resolve ${g}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(D){return{doc:null,error:D.message}}},$=[],w=[];for(let i of y){let{doc:g,error:f}=await b(s,i.package_,i.version);g?$.push(g):f&&w.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${s}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=await new ke(e.fetchFn).getConfig(s).catch(()=>{}),I=T(_),B=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,f)=>M(f,g)).map(F);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${B}); cache: ${m}`);let G=[],A=[];for(let i of I){let g=C(i),{doc:f,error:D}=await b(i.publisher,i.package_,void 0);if(f){G.push(f);let R=oe([f]),pe=d.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...i,origin:pe,versions:R}),a(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...i,origin:"missing",reason:D??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${D??"unresolved"}`)}let q=await H([...$,...G],o),de=new V(o,q),c=await new X(n).parseKanonaks(de),l=new ee(c),v=A.map(i=>i.origin==="missing"||Q(c,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),N=W(v);for(let i of N)a(`[render-stack] WARNING: ${i}`);let U={contractSource:B,cachePath:m,packages:v,warnings:N},S=new Set,j=new Map;for(let i of await o.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==s)continue;let f=F(g.version),D=`${g.publisher}/${g.package_}@${f}`;S.add(D);let R=await o.getDocumentContentAsync(D);R!==null&&j.set(`${g.package_}@${f}`,R)}return re({publisher:s,availablePublishers:[s],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:j,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:n,renderStack:r,catalog:s}=t,a=e.explainStylesheet(e.publisherSubject(n)),m=[...a.tokens.entries()].map(([o,h])=>({name:o,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,k={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},d=new Map;for(let o of s){let h=o.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([o,h])=>({namespace:o,resources:h})).sort((o,h)=>o.namespace.localeCompare(h.namespace));return{publisher:n,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ie(t){let e=Fe,n=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
|
|
2
2
|
`),s=t.renderStack.packages.map(d=>{let u=d.origin!=="missing"&&!d.resolvedButNotInCatalog,o=d.origin==="missing"?'<span class="bad">MISSING</span>':d.resolvedButNotInCatalog?`<span class="bad">${e(d.origin)} (not in catalog)</span>`:`<span class="good">${e(d.origin)}</span>`,h=d.reason?e(d.reason):e((d.versions??[]).join(", "));return`<tr class="${u?"":"row-bad"}"><td><code>${e(d.package_)}</code></td><td>${o}</td><td>${h}</td></tr>`}).join(`
|
|
3
3
|
`),a=t.stylesheet.baseStylesheet,m=a.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(a.source??"")}</code> (${a.bytes} bytes, ${e(a.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${a.problem?` \u2014 ${e(a.problem)}`:""}${a.candidates.length>0?`<br>candidates considered: ${a.candidates.map(d=>`<code>${e(d)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,p=t.stylesheet.tokens.map(d=>`<tr><td><code>--kan-${e(d.name)}</code></td><td><code>${e(d.value)}</code></td><td><code>${e(d.source)}</code></td><td>${e(d.level)}</td></tr>`).join(`
|
|
4
4
|
`),k=t.catalog.map(d=>`<tr><td><code>${e(d.namespace)}</code></td><td>${d.resources}</td></tr>`).join(`
|
|
@@ -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-IHB7UVEH.js";import{a as se}from"../chunk-EZSHR3CB.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-S6VSAKXB.js";import"../chunk-PEJALHXK.js";import{d as kn,e as bn,f as hn,g as Dn,l as ie}from"../chunk-MX3DEXMV.js";import{a as ae}from"../chunk-NJ3AZYQD.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.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,n as L,o as A,r as S}from"../chunk-7BHDZHJY.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(`
|
|
@@ -3,5 +3,17 @@ export declare class OntologyValidationResult {
|
|
|
3
3
|
isValid: boolean;
|
|
4
4
|
errors: OntologyValidationError[];
|
|
5
5
|
warnings: OntologyValidationError[];
|
|
6
|
+
/**
|
|
7
|
+
* Informational notices (`ValidationSeverity.Info`) — never affect `isValid`.
|
|
8
|
+
* Kept in their own channel so consumers can surface them distinctly (an
|
|
9
|
+
* Information diagnostic in an editor, a separate CLI line) or ignore them.
|
|
10
|
+
*/
|
|
11
|
+
infos: OntologyValidationError[];
|
|
6
12
|
get totalIssues(): number;
|
|
13
|
+
/**
|
|
14
|
+
* All diagnostics across every severity, errors first. Consumers that render
|
|
15
|
+
* every severity (the VS Code PROBLEMS view, the CLI listing) iterate this so
|
|
16
|
+
* a new severity channel is picked up without each call site changing.
|
|
17
|
+
*/
|
|
18
|
+
get allDiagnostics(): OntologyValidationError[];
|
|
7
19
|
}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
export declare enum ValidationSeverity {
|
|
2
|
+
/**
|
|
3
|
+
* Informational notice — nothing is wrong and resolution succeeds, but
|
|
4
|
+
* something is worth confirming because a silent mistake could hide here
|
|
5
|
+
* (e.g. a local entity that shadows a reserved built-in name). Surfaces in
|
|
6
|
+
* tooling as an Information diagnostic, never blocks.
|
|
7
|
+
*/
|
|
8
|
+
Info = "Info",
|
|
2
9
|
Warning = "Warning",
|
|
3
10
|
Error = "Error"
|
|
4
11
|
}
|
|
@@ -8,4 +8,4 @@ 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
10
|
export { NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, PackageHeaderRule } from './rules/document/index.js';
|
|
11
|
-
export { ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, UnresolvedPredicateRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyKindRangeConsistencyRule, ClassDefinitionRule, EmbeddedKanonakTypeRule, MarkdownLinkRule, DisplayLensScopeRule, LookSemanticSvgPathRule, TxExpressionPathRule, ShaclShapeRule, OwlOneOfRule, DiamondNameClashRule } from './rules/repository/index.js';
|
|
11
|
+
export { ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, UnresolvedPredicateRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyKindRangeConsistencyRule, ReservedNameShadowRule, 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,
|
|
1
|
+
import{A,B,C,D,E,F,G,J as H,K as I,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-ZO5IUMX6.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import"../chunk-WFQANMBQ.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{u as AmbiguousReferenceRule,A as ClassDefinitionRule,n as ClassHierarchyCycleRule,H as DiamondNameClashRule,C as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,I as KanonakObjectValidator,D as LookSemanticSvgPathRule,B as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,w as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,G as OwlOneOfRule,j as PackageHeaderRule,x as PropertyDomainRule,o as PropertyHierarchyCycleRule,y as PropertyKindRangeConsistencyRule,v as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,z as ReservedNameShadowRule,g as ResourceNamingRule,F as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,E as TxExpressionPathRule,t as UnresolvedPredicateRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
|
|
2
|
+
import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
|
|
3
|
+
import type { IRepositoryValidationRule } from './IRepositoryValidationRule.js';
|
|
4
|
+
import { OntologyValidationError } from '../../OntologyValidationError.js';
|
|
5
|
+
import type { ValidationCache } from '../../ValidationCache.js';
|
|
6
|
+
/**
|
|
7
|
+
* INFO: a package defines a LOCAL entity whose name is a reserved built-in term
|
|
8
|
+
* homed in a DIFFERENT package — e.g. core-owl declares `Class` (its `owl.Class`)
|
|
9
|
+
* while the built-in `Class` is homed in core-rdf (`rdfs.Class`). This is usually
|
|
10
|
+
* intentional (owl.Class is a legitimate distinct entity), so it is NOT an error
|
|
11
|
+
* or warning — but it is worth surfacing, because a BARE reference to that name
|
|
12
|
+
* within the package silently resolves to the local definition, not the built-in.
|
|
13
|
+
* That exact shadow let `subClassOf: Class` in core-owl resolve to a self-loop
|
|
14
|
+
* (`owl.Class subClassOf owl.Class`) instead of the intended `rdfs.Class`. The
|
|
15
|
+
* notice asks the author to confirm and qualify, so a silent mistake can't hide.
|
|
16
|
+
*
|
|
17
|
+
* A package defining the built-in it IS the home of (core-owl/`ObjectProperty`,
|
|
18
|
+
* core-rdf/`Class`) is not a shadow and does not fire.
|
|
19
|
+
*/
|
|
20
|
+
export declare class ReservedNameShadowRule implements IRepositoryValidationRule {
|
|
21
|
+
readonly ruleName = "ReservedNameShadow";
|
|
22
|
+
validateAsync(document: KanonakDocument, repository: IKanonakDocumentRepository, cache?: ValidationCache): Promise<OntologyValidationError[]>;
|
|
23
|
+
private info;
|
|
24
|
+
}
|
|
@@ -13,6 +13,7 @@ export { PropertyRangeReferenceRule } from './PropertyRangeReferenceRule.js';
|
|
|
13
13
|
export { ObjectPropertyValueValidationRule } from './ObjectPropertyValueValidationRule.js';
|
|
14
14
|
export { PropertyDomainRule } from './PropertyDomainRule.js';
|
|
15
15
|
export { PropertyKindRangeConsistencyRule } from './PropertyKindRangeConsistencyRule.js';
|
|
16
|
+
export { ReservedNameShadowRule } from './ReservedNameShadowRule.js';
|
|
16
17
|
export { ClassDefinitionRule } from './ClassDefinitionRule.js';
|
|
17
18
|
export { EmbeddedKanonakTypeRule } from './EmbeddedKanonakTypeRule.js';
|
|
18
19
|
export { MarkdownLinkRule } from './MarkdownLinkRule.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.16.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",
|
|
@@ -126,7 +126,7 @@
|
|
|
126
126
|
],
|
|
127
127
|
"dependencies": {
|
|
128
128
|
"@kanonak-protocol/canonical": "^0.1.1",
|
|
129
|
-
"@kanonak-protocol/types": "^4.
|
|
129
|
+
"@kanonak-protocol/types": "^4.16.0",
|
|
130
130
|
"ignore": "^7.0.5",
|
|
131
131
|
"js-yaml": "^4.1.0",
|
|
132
132
|
"yaml": "^2.7.0"
|