@kanonak-protocol/sdk 4.15.0 → 4.17.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/index.js +27 -27
- package/package.json +2 -2
|
@@ -27,6 +27,21 @@ export interface DeviceEnrollmentRecord {
|
|
|
27
27
|
/** A human-facing device label shown on the consent screen. */
|
|
28
28
|
deviceName?: string;
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* The portion of a {@link DeviceEnrollmentRecord} kept in the platform-secure
|
|
32
|
+
* backend: the device KEY material and small metadata — everything EXCEPT the
|
|
33
|
+
* certificate + chain PEMs. Those are PUBLIC (not secrets) and large (a leaf +
|
|
34
|
+
* two CA PEMs ≈ 3–5 KB of text, ≈ 6–10 KB UTF-16), which overflows the Windows
|
|
35
|
+
* Credential Manager `CRED_MAX_CREDENTIAL_BLOB_SIZE` (2560 bytes) — so they go to
|
|
36
|
+
* disk instead (#69). cert/chain are typed optional only to read records written
|
|
37
|
+
* by the pre-split layout (backward compatibility); `store` never writes them.
|
|
38
|
+
*/
|
|
39
|
+
type StoredDeviceRecord = Omit<DeviceEnrollmentRecord, 'certificatePem' | 'chainPem'> & Partial<Pick<DeviceEnrollmentRecord, 'certificatePem' | 'chainPem'>>;
|
|
40
|
+
/** Test seam: inject an in-memory backend and a scratch cert dir. */
|
|
41
|
+
export interface DeviceCertificateStoreDeps {
|
|
42
|
+
backend?: SecretBackend<StoredDeviceRecord>;
|
|
43
|
+
certBaseDir?: string;
|
|
44
|
+
}
|
|
30
45
|
/**
|
|
31
46
|
* Persists {@link DeviceEnrollmentRecord}s in the same platform-secure stores as
|
|
32
47
|
* OAuth credentials, but under a separate `kanonak-device` namespace so the two
|
|
@@ -39,9 +54,13 @@ export interface DeviceEnrollmentRecord {
|
|
|
39
54
|
* exported from the SDK browser entry.
|
|
40
55
|
*/
|
|
41
56
|
export declare class DeviceCertificateStore {
|
|
57
|
+
private readonly deps;
|
|
42
58
|
private backend;
|
|
43
59
|
private backendReady;
|
|
44
|
-
|
|
60
|
+
constructor(deps?: DeviceCertificateStoreDeps);
|
|
61
|
+
/** Per-host on-disk directory for the (public) certificate + chain PEMs. */
|
|
62
|
+
private certDir;
|
|
63
|
+
getBackend(): Promise<SecretBackend<StoredDeviceRecord>>;
|
|
45
64
|
get(host: string): Promise<DeviceEnrollmentRecord | null>;
|
|
46
65
|
store(host: string, record: DeviceEnrollmentRecord): Promise<void>;
|
|
47
66
|
remove(host: string): Promise<void>;
|
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 Pr,b as wr,c as Sr,d as Rr,e as be}from"./chunk-TVSHIXLA.js";import{a as fn,c as we,e as Ue,h as Fe,i as Le,j as yn}from"./chunk-IHB7UVEH.js";import{a as hr,b as kr,c as br,d as M,e as H,f as c,g as gn}from"./chunk-VZNNI2VR.js";import{a as mn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as Lt,b as Mt,c as Ht,d as zt,e as Wt,f as er,g as tr,h as rr,i as nr}from"./chunk-GMEPM2QQ.js";import{a as Gt,b as Jt,c as qt,d as v,f as Zt,g as Yt,h as Qt}from"./chunk-JYBKSBB5.js";import{a as Ft}from"./chunk-4NO7MHS7.js";import{a as Cr,b as Er,c as xr,d as Ir}from"./chunk-S6VSAKXB.js";import{a as Kr,b as Vr}from"./chunk-PEUTCG3B.js";import{a as Dr}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as un,B as pn,K as dn,a as Or,b as _r,c as Nr,d as Ur,e as Fr,f as Lr,g as Mr,h as Hr,i as zr,j as Wr,k as Gr,l as Jr,m as qr,n as Zr,o as Yr,p as Xr,q as Qr,r as en,s as tn,t as rn,u as nn,v as on,w as an,x as sn,y as cn,z as ln}from"./chunk-ZO5IUMX6.js";import{a as y,b as le,c as sr,h as L,i as _e,j as fr,k as yr,l as D}from"./chunk-MX3DEXMV.js";import{a as I}from"./chunk-NJ3AZYQD.js";import{a as gr,b as Pe,c as $r,d as g,e as jr,f as Ar,g as Tr,h as Br}from"./chunk-WFQANMBQ.js";import{a as Ne}from"./chunk-6U26UASC.js";import{a as cr,b as lr,c as $,d as ur,e as pr,g as dr,k as mr}from"./chunk-GZPLWII7.js";import{a as or,b as ce,c as f,d as k,e as ar,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 he,y as ke}from"./chunk-7BHDZHJY.js";import{a as ir}from"./chunk-FUUTGGJS.js";import{a as Tt,b as se,c as U,d as Bt,e as h,f as Vt,g as Ot,h as _t,i as Nt,j as Ut}from"./chunk-2ACBWC7K.js";import{a as vr}from"./chunk-ODIECDN7.js";import{VersionOperator as La}from"@kanonak-protocol/types/document/models/enums";import{existsSync as _n,readFileSync as Nn}from"fs";import{homedir as Un}from"os";import{join as Fn}from"path";import{execFile as hn}from"child_process";import{promisify as kn}from"util";var z=kn(hn),bn="kanonak",W="/usr/bin/security",b=class{constructor(e=bn){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 Pn}from"child_process";import{promisify as wn}from"util";var Sn=wn(Pn),Rn="kanonak:",He=2560,P=class{constructor(e=Rn){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=Buffer.byteLength(o,"utf16le");if(i>He)throw new Error(`Credential '${n}' is ${i} bytes (UTF-16), over the Windows Credential Manager limit of ${He} (CRED_MAX_CREDENTIAL_BLOB_SIZE). Keep only the secret here and store large/public material (certificates, chains) on disk.`);let a=`
|
|
22
|
+
${q}
|
|
23
23
|
$target = [Console]::In.ReadLine()
|
|
24
24
|
$json = [Console]::In.ReadLine()
|
|
25
25
|
$bytes = [System.Text.Encoding]::Unicode.GetBytes($json)
|
|
@@ -32,16 +32,16 @@ try {
|
|
|
32
32
|
[System.Runtime.InteropServices.Marshal]::Copy($bytes, 0, $cred.CredentialBlob, $bytes.Length)
|
|
33
33
|
$cred.Persist = 2
|
|
34
34
|
$result = [CredMan]::CredWrite([ref]$cred, 0)
|
|
35
|
-
if (-not $result) { throw "CredWrite failed" }
|
|
35
|
+
if (-not $result) { throw "CredWrite failed (Win32 error $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error()))" }
|
|
36
36
|
} finally {
|
|
37
37
|
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
|
|
38
|
-
}`;try{await
|
|
39
|
-
${o}`)}catch(
|
|
40
|
-
${
|
|
38
|
+
}`;try{await J(a,`${n}
|
|
39
|
+
${o}`)}catch(s){throw new Error(`Windows Credential Manager write failed: ${String(s)}`)}}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 Sn(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 j(){try{return await
|
|
90
|
+
"@`,vn="";import{execFile as Cn,spawn as En}from"child_process";import{promisify as xn}from"util";var Z=xn(Cn),In="kanonak",w=class{constructor(e=In){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=En("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 j(){try{return await Z("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as ze,mkdirSync as We,readFileSync as Ge,writeFileSync as Je}from"fs";import{createCipheriv as Kn,createDecipheriv as $n,randomBytes as qe}from"crypto";import{homedir as Dn}from"os";import{join as ve,dirname as Ze}from"path";var Xe=ve(Dn(),".config","kanonak"),A=ve(Xe,"keyring.key"),jn=ve(Xe,"credentials.enc"),Ye="aes-256-gcm",Se=32,C=12,Re=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(!ze(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=Ge(this.secretsFile);if(t.length<C+Re)return{};let n=t.subarray(0,C),o=t.subarray(C,C+Re),i=t.subarray(C+Re),a=$n(Ye,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=qe(C),o=Kn(Ye,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]);We(Ze(this.secretsFile),{recursive:!0}),Je(this.secretsFile,l,{mode:384})}getOrCreateKey(){if(ze(A)){let t=Ge(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=qe(Se);return We(Ze(A),{recursive:!0}),Je(A,e,{mode:384}),e}};import{execFile as An}from"child_process";import{promisify as Tn}from"util";var Bn=Tn(An),Qe=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
|
|
99
|
-
`;function ot(r=nt){if(!Yn(r))return null;let e=Jn(r,"utf-8"),t=rt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function it(r,e=nt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=rt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});qn(e,Xn+n,"utf-8")}function at(r){return`sha256:${Zn("sha256").update(r).digest("hex")}`}import*as Ie from"js-yaml";import{canonicalForm as Qn,canonicalHash as eo}from"@kanonak-protocol/canonical";function Ce(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as mt}from"@kanonak-protocol/canonical";function st(r){return Qn(Ce(r)?r:ct(r))}function Q(r){return eo(Ce(r)?r:ct(r))}function ct(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:oo(t),statements:xe(t.statement)});return{subjects:e}}function xe(r){let e=[];for(let t of r){let n=no(t);if(!n)continue;let o=to(t);o&&e.push({predicate:n,value:o})}return e}function to(r){if(r instanceof le&&r.carrier)return{lit:r.lexical??String(r.object),datatype:ut(r.carrier)};if(r instanceof ue)return{raw:r.object};if(r instanceof pe)return{raw:r.lexical??String(r.object)};if(r instanceof de)return{raw:r.lexical??String(r.object)};if(r instanceof me)return{ref:pt(r.object)};if(r instanceof fe)return lt(r.object);if(r instanceof ye)return{list:r.object.map(ro)}}function lt(r){let e=xe(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function ro(r){if(r instanceof h)return{ref:pt(r)};if(r instanceof y)return lt(r);if(r instanceof ce){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:ut(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof se)return{embed:{statements:xe(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function ut(r){return r===F.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function no(r){let e=r.predicate;if(e)return dt(e.subject)}function oo(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function pt(r){return dt(r.subject)}function dt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as ft}from"@kanonak-protocol/types/document/models/enums";var io="0.0.0",E=class{constructor(e,t=new x,n){this.repository=e;this.parser=t;this.objectParser=n??new $(this.parser)}repository;parser;objectParser;imports(){return new B}serializeValue(e,t){return kt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Ke(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let a={[o]:i,...e.body},s=this.dump(a);return{yaml:s,byteCount:gt(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},a=this.dump(i),s={yaml:a,byteCount:gt(a),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Ie.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[yt]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ie.dump(o,{lineWidth:-1})),a=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Ne(i,this.repository))).filter(u=>u instanceof f&&u.namespace===a&&u.name!==yt);for(let u of c)u.namespace="ephemeral";return Q(c)}},yt="__pkgbuilder_probe__";function gt(r){return new TextEncoder().encode(r).length}function Ke(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var B=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=ft.Major){let a=`${e}/${t}@${n}`,s=this.byKey.get(a);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(a,{publisher:e,package_:t,version:n,alias:c,match:i}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,io,o??t,ft.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ae(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=V(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function kt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof h)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>kt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(ao(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function V(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function ao(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ee=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${k(o)}`,a=this.produced.get(i);if(a)return a;let{document:s}=await e.produce(t,n,o);return this.produced.set(i,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=be(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var $e={async authorize(){return{allowed:!0}}},je={async record(){}},O=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},te=class{inner;ctx;policy;meter;constructor(e,t,n=$e,o=je){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new O(e,t.reason)}};var d="kanonak.org",m="view",ht="core-kanonak",so={publisher:d,package_:m,name:"rootView"},co={publisher:d,package_:m,name:"bind"},lo={publisher:d,package_:m,name:"produces"},uo={publisher:d,package_:m,name:"projections"},po={publisher:d,package_:m,name:"where"},mo={publisher:d,package_:m,name:"value"},fo={publisher:d,package_:m,name:"as"},re=class{constructor(e,t=new x){this.repository=e;this.parser=t;this.objectParser=new $(this.parser),this.builder=new E(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=I(o,co);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let a=I(o,lo);if(!a)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=yo(o),c=bt(n,d,ht),u=bt(n,d,m),p=this.builder.imports(),ne=p.ensure(d,ht,c,"ck"),wt=p.ensure(d,m,u,"v"),St=p.ref(a),Rt=new Fe(this.repository,this.parser,this.objectParser),Ae=new _e(Rt,n),vt=this.readProjections(n,o),Et=ho(o,po),Ct=this.findInstances(n,i,await this.reason(t)),Te={},xt=new Set;for(let N of Ct){if(!await this.passesWhere(Ae,n,Et,N))continue;let ie={type:St};for(let Be of vt){let It=await this.evaluateValue(Ae,n,Be.value,N),Ve=this.builder.serializeValue(Pt(It),p);Ve!==void 0&&(ie[p.ref(Be.as)]=Ve)}let De=g(N);De&&(ie[`${wt}.derivedFrom`]=p.ref(De)),Te[this.rowName(N,xt)]=ie}let oe={};t.resolvedAt&&(oe[`${ne}.resolvedAt`]=t.resolvedAt),t.invocationId&&(oe[`${ne}.id`]=t.invocationId);let C=await this.builder.buildContentAddressed({publisher:s,book:p,body:Te,contentHashProperty:`${ne}.contentHash`,header:oe});return{yaml:C.yaml,contentHash:C.contentHash,packageName:C.packageName,publisher:C.publisher,rowCount:C.resourceCount}}resolveView(e,t){let n=U(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=I(n,so);if(o){let i=U(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of ke(t,uo)){let i=o instanceof y?o:o instanceof h?U(e,o.subject):void 0;if(!i)continue;let a=ge(i,mo),s=I(i,fo);a&&s&&n.push({value:a,as:s})}return n}async reason(e){return new he({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=ko(e),i=[],a=new Set;for(let s of n.getInstancesOfClass(t)){if(a.has(s))continue;a.add(s);let c=o.get(s);c&&i.push(c)}return i.sort((s,c)=>{let u=K(g(s)),p=K(g(c));return u<p?-1:u>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let a=await this.evaluateValue(e,t,i,o);if(!bo(a))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ue(n,"view-projection",{catalog:t,depth:0}),a=new Map([["input",o]]);return e.evaluate(i,a)}rowName(e,t){let n=V(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Pt(r){return Pe(r)?r.value:Array.isArray(r)?r.map(Pt):r}function yo(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function bt(r,e,t){let n=go(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function go(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let i=g(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||_(i.version,n)>0)&&(n=i.version)}return n?k(n):void 0}function ko(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let i=K(o),a=t.get(i);(!a||_(o.version,a)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function ho(r,e){let t=ge(r,e);return t?[t]:ke(r,e).filter(n=>n instanceof y)}function bo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Pe(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{Xr as AmbiguousReferenceRule,de as BooleanStatement,mt as CANONICAL_FORM_VERSION,F as Carrier,on as ClassDefinitionRule,zr as ClassHierarchyCycleRule,_t as CompositeKanonakDocumentRepository,Z as CredentialStore,se as DefinedKanonak,X as DeviceCertificateStore,Nt as DocumentLocation,mr as EdgeType,y as EmbeddedKanonak,Lr as EmbeddedKanonakTypeRule,fe as EmbeddedStatement,O as EntitlementDeniedError,te as EntitlementProducer,Ot as FileSystemKanonakDocumentRepository,br as GitIgnoreFilter,fr as GraphBuilder,Jt as HttpKanonakDocumentRepository,B as ImportBook,Mr as ImportExistenceRule,Vt as InMemoryKanonakDocumentRepository,Lt as KANONAK_USER_AGENT,Qt as Kanonak,wr as KanonakDocumentPositions,$ as KanonakObjectParser,sn as KanonakObjectValidator,x as KanonakParser,er as KanonakUri,vr as KanonakUriBuilder,Cr as KanonakUrlResolver,cr as KanonakVocabulary,ye as ListStatement,ce as LiteralKanonak,qt as LocalFirstRepository,Yt as LockAwareRepository,un as LookRenderer,an as MarkdownLinkRule,rr as MarkdownStatement,Yr as NamespaceImportCycleRule,Or as NamespacePrefixRule,dr as NodeType,pe as NumberStatement,kr as OWL_RL_CLASSIFICATION_RULES,en as ObjectPropertyValueValidationRule,Dr as OntologyValidationError,Ar as OntologyValidationResult,E as PackageBuilder,Fr as PackageHeaderRule,ee as ProducerRepository,tn as PropertyDomainRule,Wr as PropertyHierarchyCycleRule,rn as PropertyKindRangeConsistencyRule,Pr as PropertyMetadata,Qr as PropertyRangeReferenceRule,Gr as PropertyRangeRequiredRule,_r as PropertyTypeSpecificityRule,zt as PublisherConfigResolver,Wt as PublisherIndex,gr as RDFS_RULES,he as Reasoner,hr as ReasoningResult,h as ReferenceKanonak,me as ReferenceStatement,Ft as RepositoryFactory,nn as ReservedNameShadowRule,Nr as ResourceNamingRule,nr as ResourceResolver,pr as ResourceTypeClassifier,le as ScalarStatement,tr as Statement,ue as StringStatement,Jr as SubClassOfReferenceRule,qr as SubPropertyOfReferenceRule,f as SubjectKanonak,Ur as SubjectKanonakTypeRequiredRule,yr as TripleStore,or as TypeResolver,Zr as UnresolvedPredicateRule,Hr as UnresolvedReferenceRule,Vr as ValidationCache,Br as ValidationContext,Tr as ValidationSeverity,Ba as VersionOperator,re as ViewMaterializer,$e as allowAllPolicy,Gt as assertPackageIdentity,Xt as buildLocalFirstRepository,pn as buildOntologyModel,st as canonicalForm,Q as canonicalHash,Oe as carrierOf,Zt as collectKanonakFiles,_ as compareVersions,at as computeIntegrity,Ke as contentAddressedName,$r as contextTypesOf,tt as createAuthenticatedFetch,D as createDPoPProof,jt as createVersion,ur as extractMarkdownLinks,cn as findDerivation,jr as findInstancesByType,lr as findMalformedReferences,Rr as findMarkdownLinkAt,Er as formatKanonakAddress,k as formatVersion,Qe as generateDPoPKeyPair,Ut as getGlobalCachePath,Ht as getKanonakUserAgent,M as hasValidToken,Tt as isCompatibleVersion,L as isExpired,Dt as isMajorCompatible,R as kanonakFetch,ot as loadLockFile,ir as makeUriKey,je as noopMeter,l as normalizeHost,be as parseKanonakAddress,At as parseVersionString,Sr as parseWithPositions,Bt as pickHighestDocument,Ir as propertiesInScope,ln as resolveDisplayValue,Kr as resolvePropertyStep,V as sanitizeName,it as saveLockFile,et as serverSupportsDPoP,Mt as setKanonakUserAgent,g as subjectUri,xr as superClassChain,ar as tripleKey,K as uriKey,sr as uriTriple,Kt as versionOperatorFromChar,ae as versionOperatorToChar,$t as versionsEqual};
|
|
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 Bn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Qe});return n}catch(n){throw Vn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
95
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):On(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Qe/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 Vn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function On(r){return r instanceof Error&&"killed"in r&&r.killed}var Ce=Fn(Un(),".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=Ln(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=Mn();return e.credentialHelper?new T(e.credentialHelper):process.platform==="darwin"?new b:process.platform==="win32"?new P:await j()?new w:new S}};function Ln(r){let t="KANONAK_TOKEN_"+c(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Mn(){if(!_n(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 rt}from"os";import{join as R}from"path";import{mkdir as Hn,writeFile as et,readFile as tt,rm as zn}from"fs/promises";var Ee="kanonak-device",Wn=R(rt(),".config","kanonak","device-credentials.enc"),Gn=R(rt(),".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 R(this.deps.certBaseDir??Gn,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 tt(R(n,"cert.pem"),"utf-8"),i=await tt(R(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 Hn(a,{recursive:!0}),await et(R(a,"cert.pem"),n,"utf-8"),await et(R(a,"chain.pem"),o,"utf-8"),await(await this.getBackend()).store(e,i)}async remove(e){await(await this.getBackend()).remove(e),await zn(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 j()?new w(Ee):new S(Wn)}};import{createHash as Jn,createPrivateKey as qn,generateKeyPairSync as Zn,randomUUID as Yn,sign as Xn}from"crypto";function ot(){let{publicKey:r,privateKey:e}=Zn("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:Yn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Jn("sha256").update(o).digest("base64url")),i&&(s.nonce=i),Qn(a,s,r)}function it(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Qn(r,e,t){let n=nt(JSON.stringify(r)),o=nt(JSON.stringify(e)),i=`${n}.${o}`,a=qn({key:t,format:"jwk"}),l=Xn("SHA256",Buffer.from(i),{key:a,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${l}`}function nt(r){return Buffer.from(r,"utf-8").toString("base64url")}function at(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return v(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return v(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 v(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 v(t,{method:o,headers:a})}catch{}}}return s}}import{readFileSync as eo,writeFileSync as to,existsSync as ro}from"fs";import{createHash as no}from"crypto";import st from"js-yaml";var ct="kanonak.lock",oo=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
99
|
+
`;function lt(r=ct){if(!ro(r))return null;let e=eo(r,"utf-8"),t=st.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function ut(r,e=ct){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=st.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});to(e,oo+n,"utf-8")}function pt(r){return`sha256:${no("sha256").update(r).digest("hex")}`}import*as Ke from"js-yaml";import{canonicalForm as io,canonicalHash as ao}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 dt(r){return io(xe(r)?r:mt(r))}function ee(r){return ao(xe(r)?r:mt(r))}function mt(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:uo(t),statements:Ie(t.statement)});return{subjects:e}}function Ie(r){let e=[];for(let t of r){let n=lo(t);if(!n)continue;let o=so(t);o&&e.push({predicate:n,value:o})}return e}function so(r){if(r instanceof ue&&r.carrier)return{lit:r.lexical??String(r.object),datatype:yt(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:gt(r.object)};if(r instanceof ye)return ft(r.object);if(r instanceof ge)return{list:r.object.map(co)}}function ft(r){let e=Ie(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function co(r){if(r instanceof k)return{ref:gt(r)};if(r instanceof y)return ft(r);if(r instanceof le){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:yt(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 yt(r){return r===L.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function lo(r){let e=r.predicate;if(e)return ht(e.subject)}function uo(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function gt(r){return ht(r.subject)}function ht(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 bt}from"@kanonak-protocol/types/document/models/enums";var po="0.0.0",E=class{constructor(e,t=new I,n){this.repository=e;this.parser=t;this.objectParser=n??new D(this.parser)}repository;parser;objectParser;imports(){return new V}serializeValue(e,t){return St(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:wt(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:wt(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={[Pt]:{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 Ne(i,this.repository))).filter(u=>u instanceof f&&u.namespace===a&&u.name!==Pt);for(let u of l)u.namespace="ephemeral";return ee(l)}},Pt="__pkgbuilder_probe__";function wt(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=bt.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_,h(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,po,o??t,bt.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 St(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof k)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>St(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(mo(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 mo(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}@${h(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 De={async authorize(){return{allowed:!0}}},je={async record(){}},_=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=De,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 _(e,t.reason)}};var d="kanonak.org",m="view",Rt="core-kanonak",fo={publisher:d,package_:m,name:"rootView"},yo={publisher:d,package_:m,name:"bind"},go={publisher:d,package_:m,name:"produces"},ho={publisher:d,package_:m,name:"projections"},ko={publisher:d,package_:m,name:"where"},bo={publisher:d,package_:m,name:"value"},Po={publisher:d,package_:m,name:"as"},ne=class{constructor(e,t=new I){this.repository=e;this.parser=t;this.objectParser=new D(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,yo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let a=K(o,go);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=wo(o),l=vt(n,d,Rt),u=vt(n,d,m),p=this.builder.imports(),oe=p.ensure(d,Rt,l,"ck"),Et=p.ensure(d,m,u,"v"),xt=p.ref(a),It=new Le(this.repository,this.parser,this.objectParser),Ae=new Ue(It,n),Kt=this.readProjections(n,o),$t=vo(o,ko),Dt=this.findInstances(n,i,await this.reason(t)),Te={},jt=new Set;for(let N of Dt){if(!await this.passesWhere(Ae,n,$t,N))continue;let ae={type:xt};for(let Ve of Kt){let At=await this.evaluateValue(Ae,n,Ve.value,N),Oe=this.builder.serializeValue(Ct(At),p);Oe!==void 0&&(ae[p.ref(Ve.as)]=Oe)}let Be=g(N);Be&&(ae[`${Et}.derivedFrom`]=p.ref(Be)),Te[this.rowName(N,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,fo);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 ke(t,ho)){let i=o instanceof y?o:o instanceof k?F(e,o.subject):void 0;if(!i)continue;let a=he(i,bo),s=K(i,Po);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=Ro(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(!Co(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 Ct(r){return we(r)?r.value:Array.isArray(r)?r.map(Ct):r}function wo(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=So(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 So(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?h(n):void 0}function Ro(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=he(r,e);return t?[t]:ke(r,e).filter(n=>n instanceof y)}function Co(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{nn as AmbiguousReferenceRule,me as BooleanStatement,kt as CANONICAL_FORM_VERSION,L as Carrier,un as ClassDefinitionRule,Zr as ClassHierarchyCycleRule,Ht as CompositeKanonakDocumentRepository,X as CredentialStore,ce as DefinedKanonak,Q as DeviceCertificateStore,Mt as DocumentLocation,kr as EdgeType,y as EmbeddedKanonak,Gr as EmbeddedKanonakTypeRule,ye as EmbeddedStatement,_ as EntitlementDeniedError,re as EntitlementProducer,Lt as FileSystemKanonakDocumentRepository,vr as GitIgnoreFilter,br as GraphBuilder,Qt as HttpKanonakDocumentRepository,V as ImportBook,Jr as ImportExistenceRule,Ft as InMemoryKanonakDocumentRepository,Gt as KANONAK_USER_AGENT,or as Kanonak,Er as KanonakDocumentPositions,D as KanonakObjectParser,dn as KanonakObjectValidator,I as KanonakParser,ir as KanonakUri,Kr as KanonakUriBuilder,Dr as KanonakUrlResolver,mr as KanonakVocabulary,ge as ListStatement,le as LiteralKanonak,er as LocalFirstRepository,tr as LockAwareRepository,yn as LookRenderer,pn as MarkdownLinkRule,sr as MarkdownStatement,tn as NamespaceImportCycleRule,Lr as NamespacePrefixRule,hr as NodeType,de as NumberStatement,Sr as OWL_RL_CLASSIFICATION_RULES,an as ObjectPropertyValueValidationRule,Nr as OntologyValidationError,Or as OntologyValidationResult,E as PackageBuilder,Wr as PackageHeaderRule,te as ProducerRepository,sn as PropertyDomainRule,Yr as PropertyHierarchyCycleRule,cn as PropertyKindRangeConsistencyRule,Cr as PropertyMetadata,on as PropertyRangeReferenceRule,Xr as PropertyRangeRequiredRule,Hr as PropertyTypeSpecificityRule,Zt as PublisherConfigResolver,Yt as PublisherIndex,wr as RDFS_RULES,be as Reasoner,Rr as ReasoningResult,k as ReferenceKanonak,fe as ReferenceStatement,Wt as RepositoryFactory,ln as ReservedNameShadowRule,Mr as ResourceNamingRule,cr as ResourceResolver,gr as ResourceTypeClassifier,ue as ScalarStatement,ar as Statement,pe as StringStatement,Qr as SubClassOfReferenceRule,en as SubPropertyOfReferenceRule,f as SubjectKanonak,zr as SubjectKanonakTypeRequiredRule,Pr as TripleStore,lr as TypeResolver,rn as UnresolvedPredicateRule,qr as UnresolvedReferenceRule,Fr as ValidationCache,Ur as ValidationContext,_r as ValidationSeverity,La as VersionOperator,ne as ViewMaterializer,De as allowAllPolicy,Xt as assertPackageIdentity,nr as buildLocalFirstRepository,gn as buildOntologyModel,dt as canonicalForm,ee as canonicalHash,_e as carrierOf,rr as collectKanonakFiles,U as compareVersions,pt as computeIntegrity,$e as contentAddressedName,Br as contextTypesOf,at as createAuthenticatedFetch,B as createDPoPProof,Vt as createVersion,yr as extractMarkdownLinks,mn as findDerivation,Vr as findInstancesByType,fr as findMalformedReferences,Ir as findMarkdownLinkAt,$r as formatKanonakAddress,h as formatVersion,ot as generateDPoPKeyPair,zt as getGlobalCachePath,qt as getKanonakUserAgent,H as hasValidToken,_t as isCompatibleVersion,M as isExpired,Nt as isMajorCompatible,v as kanonakFetch,lt as loadLockFile,ur as makeUriKey,je as noopMeter,c as normalizeHost,Pe as parseKanonakAddress,Ot as parseVersionString,xr as parseWithPositions,Ut as pickHighestDocument,Ar as propertiesInScope,fn as resolveDisplayValue,Tr as resolvePropertyStep,O as sanitizeName,ut as saveLockFile,it as serverSupportsDPoP,Jt as setKanonakUserAgent,g as subjectUri,jr as superClassChain,pr as tripleKey,$ as uriKey,dr as uriTriple,Tt as versionOperatorFromChar,se as versionOperatorToChar,Bt as versionsEqual};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.17.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.17.0",
|
|
130
130
|
"ignore": "^7.0.5",
|
|
131
131
|
"js-yaml": "^4.1.0",
|
|
132
132
|
"yaml": "^2.7.0"
|