@kanonak-protocol/sdk 5.0.0 → 5.1.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/SessionExchange.d.ts +6 -3
- package/dist/index.js +7 -5
- package/package.json +2 -2
|
@@ -8,15 +8,18 @@ export interface ExchangedSession {
|
|
|
8
8
|
scope: string;
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
|
-
* mTLS transport: POST `body` to `url` presenting the client cert/key
|
|
12
|
-
*
|
|
11
|
+
* mTLS transport: POST `body` to `url` presenting the client cert/key.
|
|
12
|
+
* `certPem` is the full client chain (leaf first, then any issuing
|
|
13
|
+
* intermediates) ready to hand to the TLS stack; the server certificate is
|
|
14
|
+
* verified against the platform's default trust store (issue #74 — the client
|
|
15
|
+
* issuance chain must never be used as the server-verification CA).
|
|
16
|
+
* Injectable so the exchange unit-tests without a live mTLS endpoint —
|
|
13
17
|
* the same seam {@link NativeIssuanceClient} uses for the enrollment HTTP.
|
|
14
18
|
*/
|
|
15
19
|
export type MtlsTransport = (req: {
|
|
16
20
|
url: string;
|
|
17
21
|
certPem: string;
|
|
18
22
|
keyPem: string;
|
|
19
|
-
caPem: string | undefined;
|
|
20
23
|
body: string;
|
|
21
24
|
contentType: string;
|
|
22
25
|
}) => Promise<{
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as _r,b as Nr,c as jr,d as Or,e as Ie}from"./chunk-TVSHIXLA.js";import{a as An,c as De,e as Ye,h as Ze,i as Qe,j as In}from"./chunk-IHB7UVEH.js";import{a as Dr,b as
|
|
1
|
+
import{a as _r,b as Nr,c as jr,d as Or,e as Ie}from"./chunk-TVSHIXLA.js";import{a as An,c as De,e as Ye,h as Ze,i as Qe,j as In}from"./chunk-IHB7UVEH.js";import{a as Dr,b as $r,c as Tr,d as Q,e as ee,f as l,g as Kn}from"./chunk-EBH5WSSY.js";import{a as xn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as rr,b as nr,c as or,d as ir,e as sr,f as fr,g as yr,h as hr,i as gr}from"./chunk-GMEPM2QQ.js";import{a as ar,b as cr,c as lr,d as I,f as pr,g as dr,h as mr}from"./chunk-JYBKSBB5.js";import{a as tr}from"./chunk-4NO7MHS7.js";import{a as Mr,b as Vr,c as Lr,d as Ur}from"./chunk-S6VSAKXB.js";import{a as Fr,b as Xr}from"./chunk-PEUTCG3B.js";import{a as zr}from"./chunk-PEJALHXK.js";import{a as ur}from"./chunk-SC5M74NM.js";import{A as Rn,B as En,K as Cn,a as Yr,b as Zr,c as Qr,d as en,e as tn,f as rn,g as nn,h as on,i as sn,j as an,k as cn,l as ln,m as pn,n as dn,o as un,p as mn,q as fn,r as yn,s as hn,t as gn,u as kn,v as Sn,w as wn,x as bn,y as Pn,z as vn}from"./chunk-FPUQEPYK.js";import{a as P,b as Se,c as br,h as Z,i as qe,j as Ar,k as Ir,l as U}from"./chunk-MX3DEXMV.js";import{a as M}from"./chunk-NJ3AZYQD.js";import{a as Kr,b as Ke,c as Hr,d as v,e as Wr,f as Gr,g as Jr,h as qr}from"./chunk-ZP6P7HNU.js";import{a as Xe}from"./chunk-6U26UASC.js";import{a as Pr,b as vr,c as L,d as Rr,e as Er,g as Cr,k as xr}from"./chunk-GZPLWII7.js";import{a as kr,b as ke,c as b,d as C,e as wr,f as we,g as be,h as Pe,i as ve,j as Re,k as Ee,l as Ce,r as Y,w as V,x as xe,y as Ae}from"./chunk-7BHDZHJY.js";import{a as Sr}from"./chunk-FUUTGGJS.js";import{a as Jt,b as ge,c as X,d as qt,e as E,f as Xt,g as Yt,h as Zt,i as Qt,j as er}from"./chunk-2ACBWC7K.js";import{a as Br}from"./chunk-ODIECDN7.js";import{VersionOperator as Oa}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Zn,readFileSync as Qn}from"fs";import{homedir as eo}from"os";import{join as to}from"path";import{execFile as Dn}from"child_process";import{promisify as $n}from"util";var te=$n(Dn),Tn="kanonak",re="/usr/bin/security",m=class{constructor(e=Tn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await te(re,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
|
|
2
2
|
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(et(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${ne(n)}
|
|
3
3
|
The Keychain may be locked or inaccessible.
|
|
4
4
|
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=l(e),o=JSON.stringify(t);try{await te(re,["add-generic-password","-s",this.service,"-a",n,"-U","-w",o],{timeout:1e4})}catch(i){throw new Error(`macOS Keychain write failed for '${n}': ${ne(i)}
|
|
@@ -90,12 +90,14 @@ public class CredMan {
|
|
|
90
90
|
public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
|
|
91
91
|
}
|
|
92
92
|
"@`,Bn="";import{execFile as Mn,spawn as Vn}from"child_process";import{promisify as Ln}from"util";var se=Ln(Mn),Un="kanonak",y=class{constructor(e=Un){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await se("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((i,s)=>{let a=Vn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(o),a.stdin.end(),a.on("close",c=>{c===0?i():s(new Error(`secret-tool store exited with code ${c}`))}),a.on("error",s)})}async remove(e){let t=l(e);try{await se("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await se("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
|
|
93
|
-
`)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function x(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as rt,mkdirSync as nt,readFileSync as ot,writeFileSync as it}from"fs";import{createCipheriv as Fn,createDecipheriv as Hn,randomBytes as st}from"crypto";import{homedir as zn}from"os";import{join as _e,dirname as at}from"path";var lt=_e(zn(),".config","kanonak"),F=_e(lt,"keyring.key"),Wn=_e(lt,"credentials.enc"),ct="aes-256-gcm"
|
|
93
|
+
`)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function x(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as rt,mkdirSync as nt,readFileSync as ot,writeFileSync as it}from"fs";import{createCipheriv as Fn,createDecipheriv as Hn,randomBytes as st}from"crypto";import{homedir as zn}from"os";import{join as _e,dirname as at}from"path";var lt=_e(zn(),".config","kanonak"),F=_e(lt,"keyring.key"),Wn=_e(lt,"credentials.enc"),ct="aes-256-gcm",$e=32,K=12,Te=16,h=class{constructor(e=Wn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!rt(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ot(this.secretsFile);if(t.length<K+Te)return{};let n=t.subarray(0,K),o=t.subarray(K,K+Te),i=t.subarray(K+Te),s=Hn(ct,e,n);s.setAuthTag(o);let a=Buffer.concat([s.update(i),s.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=st(K),o=Fn(ct,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(i),o.final()]),a=o.getAuthTag(),c=Buffer.concat([n,a,s]);nt(at(this.secretsFile),{recursive:!0}),it(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(rt(F)){let t=ot(F);if(t.length!==$e)throw new Error(`Credential keyring key is corrupted (expected ${$e} bytes, got ${t.length}). Delete ${F} and re-authenticate.`);return t}let e=st($e);return nt(at(F),{recursive:!0}),it(F,e,{mode:384}),e}};import{execFile as Gn}from"child_process";import{promisify as Jn}from"util";var qn=Jn(Gn),pt=3e4,H=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${ae(n)}
|
|
94
94
|
Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
|
|
95
95
|
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=l(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${ae(o)}
|
|
96
96
|
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${ae(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: ${ae(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await qn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:pt});return n}catch(n){throw Xn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
97
97
|
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Yn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${pt/1e3}s on '${e}'.
|
|
98
98
|
The helper may be waiting for authentication to an external vault.`):n}}};function ae(r){return r instanceof Error?r.message:String(r)}function Xn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function Yn(r){return r instanceof Error&&"killed"in r&&r.killed}var Ne=to(eo(),".kanonak","config.json"),ce=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=ro(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!ee(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=no();return e.credentialHelper?new H(e.credentialHelper):process.platform==="darwin"?new m:process.platform==="win32"?new f:await x()?new y:new h}};function ro(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function no(){if(!Zn(Ne))return{};try{return JSON.parse(Qn(Ne,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ne}: ${e}
|
|
99
|
-
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as ft}from"os";import{join as A}from"path";import{mkdir as oo,writeFile as dt,readFile as ut,rm as mt}from"fs/promises";var je="kanonak-device",io=A(ft(),".config","kanonak","device-credentials.enc"),so=A(ft(),".kanonak","devices"),D=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=l(e).replace(/[^a-zA-Z0-9._-]/g,"_");return A(this.deps.certBaseDir??so,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 ut(A(n,"cert.pem"),"utf-8"),i=await ut(A(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,s=this.certDir(e);await oo(s,{recursive:!0}),await dt(A(s,"cert.pem"),n,"utf-8"),await dt(A(s,"chain.pem"),o,"utf-8");try{await(await this.getBackend()).store(e,i)}catch(a){throw await mt(s,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await mt(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 m(je):process.platform==="win32"?new f(`${je}:`):await x()?new y(je):new h(io)}};import{homedir as ao}from"os";import{join as co}from"path";var Oe="kanonak-session",lo=co(ao(),".config","kanonak","session-credentials.enc"),T=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Oe):process.platform==="win32"?new f(`${Oe}:`):await x()?new y(Oe):new h(lo)}};function le(r,e=5*6e4,t=Date.now()){let n=Date.parse(r.expiresAt);return Number.isNaN(n)?!0:t>=n-e}var yt="key_thumbprint",R=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=l(e);if(this.prCache.has(t))return this.prCache.get(t);let n=`https://${t}/.well-known/oauth-protected-resource`,o=await po(n),i=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],s=i.length>0?i:null;return this.prCache.set(t,s),s}async discover(e){let t=l(e);if(this.cache.has(t))return this.cache.get(t);let n=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(n);if(!o){let i=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(i)}return this.cache.set(t,o),o}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(o){let i=o instanceof Error?o.message:String(o);return i.includes("ENOTFOUND")||i.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${i})`),console.error(" If the server is behind a VPN, ensure you are connected.")):i.includes("CERT")||i.includes("SSL")||i.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${i})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${i}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(n.issuer),authorizationEndpoint:g(n.authorization_endpoint),tokenEndpoint:g(n.token_endpoint),registrationEndpoint:g(n.registration_endpoint),revocationEndpoint:g(n.revocation_endpoint),scopesSupported:k(n.scopes_supported),responseTypesSupported:k(n.response_types_supported),grantTypesSupported:k(n.grant_types_supported),codeChallengeMethodsSupported:k(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(n.dpop_signing_alg_values_supported),enrollmentEndpoint:g(n.enrollment_endpoint),enrollmentIssuanceProtocols:k(n.enrollment_issuance_protocols),enrollmentKeyTypes:k(n.enrollment_key_types),enrollmentScopesSupported:k(n.enrollment_scopes_supported),enrollmentConsentBindingParam:g(n.enrollment_consent_binding_param),sessionEndpoint:g(n.session_endpoint),sessionEndpointAuthMethod:g(n.session_endpoint_auth_method)}}};async function po(r){try{let e=await fetch(r);return e.ok?await e.json():null}catch{return null}}function g(r){return typeof r=="string"?r:null}function k(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):null}import*as ht from"https";import{createPrivateKey as uo}from"crypto";var mo="client_credentials",S=class extends Error{},$=class{constructor(e=yo){this.transport=e}transport;async exchange(e,t,n={}){let o=fo(t.keyMaterial),i=new URLSearchParams({grant_type:mo});n.scope&&i.set("scope",n.scope);let s=i.toString(),a;try{a=await this.transport({url:e,certPem:t.certificatePem,keyPem:o,caPem:t.chainPem||void 0,body:s,contentType:"application/x-www-form-urlencoded"})}catch(O){throw new S(`mTLS session exchange to ${e} failed: ${O.message}`)}if(a.status<200||a.status>=300)throw new S(`Session endpoint ${e} returned HTTP ${a.status}: ${a.body.slice(0,300)}`);let c;try{c=JSON.parse(a.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${a.body.slice(0,200)}`)}if(typeof c.access_token!="string"||!c.access_token)throw new S("Session response had no access_token.");let p=typeof c.expires_in=="number"?c.expires_in:0,d=n.nowMs??Date.now();return{token:c.access_token,tokenType:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expiresAt:new Date(d+p*1e3).toISOString(),scope:typeof c.scope=="string"?c.scope:""}}};function fo(r){try{return uo({key:r,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var yo=r=>new Promise((e,t)=>{let n=new URL(r.url),o=ht.request({method:"POST",hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,cert:r.certPem,key:r.keyPem,...r.caPem?{ca:r.caPem}:{},headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(r.body),Accept:"application/json"},timeout:3e4},i=>{let s=[];i.on("data",a=>s.push(a)),i.on("end",()=>e({status:i.statusCode??0,body:Buffer.concat(s).toString("utf-8")}))});o.on("error",t),o.on("timeout",()=>o.destroy(new Error("mTLS request timed out"))),o.write(r.body),o.end()});var _=class extends Error{},N=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new R,this.deviceStore=e.deviceStore??new D,this.sessionStore=e.sessionStore??new T,this.exchange=e.exchange??new $}async acquire(e,t={}){let n=l(e),o=await this.sessionEndpoint(e);if(!o)throw new _(`'${n}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let i=await this.deviceStore.get(e);if(!i)throw new _(`No device certificate enrolled for '${n}'. Run 'kanonak device enroll ${e}' first.`);let s=await this.exchange.exchange(o,i,t),a={token:s.token,tokenType:s.tokenType,expiresAt:s.expiresAt,scope:s.scope};return await this.sessionStore.store(n,a),a}async getValidSession(e){let t=l(e),n=await this.sessionStore.get(t);return n&&!le(n)?n:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(l(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var pe=class{discovery;sessions;constructor(e={}){this.discovery=e.discovery??new R,this.sessions=e.sessionManager??new N}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;for(let n of t){let o=ho(n);if(!o)continue;let i=await this.sessions.getValidSession(o);if(i)return{authority:o,token:i.token,expiresAt:i.expiresAt,scope:i.scope}}return null}};function ho(r){try{return new URL(r).host}catch{return}}import{createHash as go,createPrivateKey as ko,generateKeyPairSync as So,randomUUID as wo,sign as bo}from"crypto";function kt(){let{publicKey:r,privateKey:e}=So("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function z(r,e,t,n,o,i){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:wo(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(a.ath=go("sha256").update(o).digest("base64url")),i&&(a.nonce=i),Po(s,a,r)}function St(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Po(r,e,t){let n=gt(JSON.stringify(r)),o=gt(JSON.stringify(e)),i=`${n}.${o}`,s=ko({key:t,format:"jwk"}),c=bo("SHA256",Buffer.from(i),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function gt(r){return Buffer.from(r,"utf-8").toString("base64url")}function wt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return I(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return I(t,{method:o});Q(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(i.dpopKeyPair){let c=e.get(n);try{let p=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.Authorization=`DPoP ${i.accessToken}`,s.DPoP=p}catch(p){let d=p instanceof Error?p.message:String(p);console.error(` Error: Failed to create DPoP proof for '${n}': ${d}
|
|
100
|
-
|
|
101
|
-
`;function vt(r=Pt){if(!Eo(r))return null;let e=vo(r,"utf-8"),t=bt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Rt(r,e=Pt){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=bt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Ro(e,xo+n,"utf-8")}function Et(r){return`sha256:${Co("sha256").update(r).digest("hex")}`}import*as Ve from"js-yaml";import{canonicalForm as Ao,canonicalHash as Io}from"@kanonak-protocol/canonical";function Be(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as Tt}from"@kanonak-protocol/canonical";function Ct(r){return Ao(Be(r)?r:xt(r))}function de(r){return Io(Be(r)?r:xt(r))}function xt(r){let e=[];for(let t of r)t instanceof b&&e.push({uri:$o(t),statements:Me(t.statement)});return{subjects:e}}function Me(r){let e=[];for(let t of r){let n=To(t);if(!n)continue;let o=Ko(t);o&&e.push({predicate:n,value:o})}return e}function Ko(r){if(r instanceof we&&r.carrier)return{lit:r.lexical??String(r.object),datatype:It(r.carrier)};if(r instanceof be)return{raw:r.object};if(r instanceof Pe)return{raw:r.lexical??String(r.object)};if(r instanceof ve)return{raw:r.lexical??String(r.object)};if(r instanceof Re)return{ref:Kt(r.object)};if(r instanceof Ee)return At(r.object);if(r instanceof Ce)return{list:r.object.map(Do)}}function At(r){let e=Me(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function Do(r){if(r instanceof C)return{ref:Kt(r)};if(r instanceof P)return At(r);if(r instanceof Se){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:It(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 ke)return{embed:{statements:Me(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 It(r){return r===Z.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function To(r){let e=r.predicate;if(e)return Dt(e.subject)}function $o(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function Kt(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 $t}from"@kanonak-protocol/types/document/models/enums";var _o="0.0.0",j=class{constructor(e,t=new M,n){this.repository=e;this.parser=t;this.objectParser=n??new U(this.parser)}repository;parser;objectParser;imports(){return new W}serializeValue(e,t){return jt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Le(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let s={[o]:i,...e.body},a=this.dump(s);return{yaml:a,byteCount:Nt(a),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},s=this.dump(i),a={yaml:s,byteCount:Nt(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(a.contentHash=o),a}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[_t]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ve.dump(o,{lineWidth:-1})),s=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Xe(i,this.repository))).filter(p=>p instanceof b&&p.namespace===s&&p.name!==_t);for(let p of c)p.namespace="ephemeral";return de(c)}},_t="__pkgbuilder_probe__";function Nt(r){return new TextEncoder().encode(r).length}function Le(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var W=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=$t.Major){let s=`${e}/${t}@${n}`,a=this.byKey.get(s);if(a)return a.alias;let c=this.uniqueAlias(o);return this.byKey.set(s,{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_,E(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,_o,o??t,$t.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:ge(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=G(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function jt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof C)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>jt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof P)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(No(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 G(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function No(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ue=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}@${E(o)}`,s=this.produced.get(i);if(s)return s;let{document:a}=await e.produce(t,n,o);return this.produced.set(i,a),a}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=Ke(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ue={async authorize(){return{allowed:!0}}},Fe={async record(){}},J=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},me=class{inner;ctx;policy;meter;constructor(e,t,n=Ue,o=Fe){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 J(e,t.reason)}};var u="kanonak.org",w="view",Ot="core-kanonak",jo={publisher:u,package_:w,name:"rootView"},Oo={publisher:u,package_:w,name:"bind"},Bo={publisher:u,package_:w,name:"produces"},Mo={publisher:u,package_:w,name:"projections"},Vo={publisher:u,package_:w,name:"where"},Lo={publisher:u,package_:w,name:"value"},Uo={publisher:u,package_:w,name:"as"},fe=class{constructor(e,t=new M){this.repository=e;this.parser=t;this.objectParser=new U(this.parser),this.builder=new j(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=V(o,Oo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let s=V(o,Bo);if(!s)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 a=Fo(o),c=Bt(n,u,Ot),p=Bt(n,u,w),d=this.builder.imports(),O=d.ensure(u,Ot,c,"ck"),Vt=d.ensure(u,w,p,"v"),Lt=d.ref(s),Ut=new Qe(this.repository,this.parser,this.objectParser),He=new Ye(Ut,n),Ft=this.readProjections(n,o),Ht=Wo(o,Vo),zt=this.findInstances(n,i,await this.reason(t)),ze={},Wt=new Set;for(let q of zt){if(!await this.passesWhere(He,n,Ht,q))continue;let he={type:Lt};for(let Ge of Ft){let Gt=await this.evaluateValue(He,n,Ge.value,q),Je=this.builder.serializeValue(Mt(Gt),d);Je!==void 0&&(he[d.ref(Ge.as)]=Je)}let We=v(q);We&&(he[`${Vt}.derivedFrom`]=d.ref(We)),ze[this.rowName(q,Wt)]=he}let ye={};t.resolvedAt&&(ye[`${O}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ye[`${O}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:d,body:ze,contentHashProperty:`${O}.contentHash`,header:ye});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let n=Y(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=V(n,jo);if(o){let i=Y(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 Ae(t,Mo)){let i=o instanceof P?o:o instanceof C?Y(e,o.subject):void 0;if(!i)continue;let s=xe(i,Lo),a=V(i,Uo);s&&a&&n.push({value:s,as:a})}return n}async reason(e){return new Ie({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=zo(e),i=[],s=new Set;for(let a of n.getInstancesOfClass(t)){if(s.has(a))continue;s.add(a);let c=o.get(a);c&&i.push(c)}return i.sort((a,c)=>{let p=L(v(a)),d=L(v(c));return p<d?-1:p>d?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let s=await this.evaluateValue(e,t,i,o);if(!Go(s))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ze(n,"view-projection",{catalog:t,depth:0}),s=new Map([["input",o]]);return e.evaluate(i,s)}rowName(e,t){let n=G(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Mt(r){return De(r)?r.value:Array.isArray(r)?r.map(Mt):r}function Fo(r){let e=v(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function Bt(r,e,t){let n=Ho(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function Ho(r,e,t){let n;for(let o of r){if(!(o instanceof b))continue;let i=v(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||X(i.version,n)>0)&&(n=i.version)}return n?E(n):void 0}function zo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof b))continue;let o=v(n);if(!o||!o.version)continue;let i=L(o),s=t.get(i);(!s||X(o.version,s)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function Wo(r,e){let t=xe(r,e);return t?[t]:Ae(r,e).filter(n=>n instanceof P)}function Go(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:De(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{kn as AmbiguousReferenceRule,ve as BooleanStatement,Tt as CANONICAL_FORM_VERSION,Z as Carrier,Rn as ClassDefinitionRule,dn as ClassHierarchyCycleRule,or as CompositeKanonakDocumentRepository,pe as CredentialResolver,ce as CredentialStore,yt as DEFAULT_CONSENT_BINDING_PARAM,ke as DefinedKanonak,D as DeviceCertificateStore,nr as DocumentLocation,Tr as EdgeType,P as EmbeddedKanonak,cn as EmbeddedKanonakTypeRule,Ee as EmbeddedStatement,J as EntitlementDeniedError,me as EntitlementProducer,rr as FileSystemKanonakDocumentRepository,Br as GitIgnoreFilter,$r as GraphBuilder,mr as HttpKanonakDocumentRepository,W as ImportBook,ln as ImportExistenceRule,tr as InMemoryKanonakDocumentRepository,ar as KANONAK_USER_AGENT,kr as Kanonak,Vr as KanonakDocumentPositions,U as KanonakObjectParser,Cn as KanonakObjectValidator,M as KanonakParser,Sr as KanonakUri,Fr as KanonakUriBuilder,zr as KanonakUrlResolver,xr as KanonakVocabulary,Ce as ListStatement,Se as LiteralKanonak,fr as LocalFirstRepository,yr as LockAwareRepository,In as LookRenderer,En as MarkdownLinkRule,br as MarkdownStatement,hn as NamespaceImportCycleRule,rn as NamespacePrefixRule,Dr as NodeType,Pe as NumberStatement,R as OAuthDiscovery,jr as OWL_RL_CLASSIFICATION_RULES,wn as ObjectPropertyValueValidationRule,Qr as OntologyValidationError,Yr as OntologyValidationResult,j as PackageBuilder,an as PackageHeaderRule,ue as ProducerRepository,bn as PropertyDomainRule,un as PropertyHierarchyCycleRule,Pn as PropertyKindRangeConsistencyRule,Mr as PropertyMetadata,Sn as PropertyRangeReferenceRule,mn as PropertyRangeRequiredRule,on as PropertyTypeSpecificityRule,pr as PublisherConfigResolver,dr as PublisherIndex,Nr as RDFS_RULES,Ie as Reasoner,Or as ReasoningResult,C as ReferenceKanonak,Re as ReferenceStatement,sr as RepositoryFactory,vn as ReservedNameShadowRule,nn as ResourceNamingRule,Pr as ResourceResolver,Kr as ResourceTypeClassifier,we as ScalarStatement,_ as SessionError,$ as SessionExchange,S as SessionExchangeError,N as SessionManager,T as SessionStore,wr as Statement,be as StringStatement,fn as SubClassOfReferenceRule,yn as SubPropertyOfReferenceRule,b as SubjectKanonak,sn as SubjectKanonakTypeRequiredRule,_r as TripleStore,vr as TypeResolver,gn as UnresolvedPredicateRule,pn as UnresolvedReferenceRule,tn as ValidationCache,en as ValidationContext,Zr as ValidationSeverity,ja as VersionOperator,fe as ViewMaterializer,Ue as allowAllPolicy,ur as assertPackageIdentity,gr as buildLocalFirstRepository,Kn as buildOntologyModel,Ct as canonicalForm,de as canonicalHash,qe as carrierOf,hr as collectKanonakFiles,X as compareVersions,Et as computeIntegrity,Le as contentAddressedName,qr as contextTypesOf,wt as createAuthenticatedFetch,z as createDPoPProof,Xt as createVersion,Ir as extractMarkdownLinks,xn as findDerivation,Xr as findInstancesByType,Ar as findMalformedReferences,Ur as findMarkdownLinkAt,Hr as formatKanonakAddress,E as formatVersion,kt as generateDPoPKeyPair,ir as getGlobalCachePath,lr as getKanonakUserAgent,ee as hasValidToken,Zt as isCompatibleVersion,Q as isExpired,Qt as isMajorCompatible,I as kanonakFetch,vt as loadLockFile,Rr as makeUriKey,Fe as noopMeter,l as normalizeHost,Ke as parseKanonakAddress,Yt as parseVersionString,Lr as parseWithPositions,er as pickHighestDocument,Gr as propertiesInScope,An as resolveDisplayValue,Jr as resolvePropertyStep,G as sanitizeName,Rt as saveLockFile,St as serverSupportsDPoP,le as sessionNeedsRefresh,cr as setKanonakUserAgent,v as subjectUri,Wr as superClassChain,Er as tripleKey,L as uriKey,Cr as uriTriple,Jt as versionOperatorFromChar,ge as versionOperatorToChar,qt as versionsEqual};
|
|
99
|
+
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as ft}from"os";import{join as A}from"path";import{mkdir as oo,writeFile as dt,readFile as ut,rm as mt}from"fs/promises";var je="kanonak-device",io=A(ft(),".config","kanonak","device-credentials.enc"),so=A(ft(),".kanonak","devices"),D=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=l(e).replace(/[^a-zA-Z0-9._-]/g,"_");return A(this.deps.certBaseDir??so,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 ut(A(n,"cert.pem"),"utf-8"),i=await ut(A(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,s=this.certDir(e);await oo(s,{recursive:!0}),await dt(A(s,"cert.pem"),n,"utf-8"),await dt(A(s,"chain.pem"),o,"utf-8");try{await(await this.getBackend()).store(e,i)}catch(a){throw await mt(s,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await mt(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 m(je):process.platform==="win32"?new f(`${je}:`):await x()?new y(je):new h(io)}};import{homedir as ao}from"os";import{join as co}from"path";var Oe="kanonak-session",lo=co(ao(),".config","kanonak","session-credentials.enc"),$=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Oe):process.platform==="win32"?new f(`${Oe}:`):await x()?new y(Oe):new h(lo)}};function le(r,e=5*6e4,t=Date.now()){let n=Date.parse(r.expiresAt);return Number.isNaN(n)?!0:t>=n-e}var yt="key_thumbprint",R=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=l(e);if(this.prCache.has(t))return this.prCache.get(t);let n=`https://${t}/.well-known/oauth-protected-resource`,o=await po(n),i=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],s=i.length>0?i:null;return this.prCache.set(t,s),s}async discover(e){let t=l(e);if(this.cache.has(t))return this.cache.get(t);let n=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(n);if(!o){let i=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(i)}return this.cache.set(t,o),o}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(o){let i=o instanceof Error?o.message:String(o);return i.includes("ENOTFOUND")||i.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${i})`),console.error(" If the server is behind a VPN, ensure you are connected.")):i.includes("CERT")||i.includes("SSL")||i.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${i})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${i}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(n.issuer),authorizationEndpoint:g(n.authorization_endpoint),tokenEndpoint:g(n.token_endpoint),registrationEndpoint:g(n.registration_endpoint),revocationEndpoint:g(n.revocation_endpoint),scopesSupported:k(n.scopes_supported),responseTypesSupported:k(n.response_types_supported),grantTypesSupported:k(n.grant_types_supported),codeChallengeMethodsSupported:k(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(n.dpop_signing_alg_values_supported),enrollmentEndpoint:g(n.enrollment_endpoint),enrollmentIssuanceProtocols:k(n.enrollment_issuance_protocols),enrollmentKeyTypes:k(n.enrollment_key_types),enrollmentScopesSupported:k(n.enrollment_scopes_supported),enrollmentConsentBindingParam:g(n.enrollment_consent_binding_param),sessionEndpoint:g(n.session_endpoint),sessionEndpointAuthMethod:g(n.session_endpoint_auth_method)}}};async function po(r){try{let e=await fetch(r);return e.ok?await e.json():null}catch{return null}}function g(r){return typeof r=="string"?r:null}function k(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):null}import*as ht from"https";import{createPrivateKey as uo}from"crypto";var mo="client_credentials",S=class extends Error{},T=class{constructor(e=ho){this.transport=e}transport;async exchange(e,t,n={}){let o=yo(t.keyMaterial),i=new URLSearchParams({grant_type:mo});n.scope&&i.set("scope",n.scope);let s=i.toString(),a;try{a=await this.transport({url:e,certPem:fo(t),keyPem:o,body:s,contentType:"application/x-www-form-urlencoded"})}catch(O){throw new S(`mTLS session exchange to ${e} failed: ${O.message}`)}if(a.status<200||a.status>=300)throw new S(`Session endpoint ${e} returned HTTP ${a.status}: ${a.body.slice(0,300)}`);let c;try{c=JSON.parse(a.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${a.body.slice(0,200)}`)}if(typeof c.access_token!="string"||!c.access_token)throw new S("Session response had no access_token.");let p=typeof c.expires_in=="number"?c.expires_in:0,d=n.nowMs??Date.now();return{token:c.access_token,tokenType:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expiresAt:new Date(d+p*1e3).toISOString(),scope:typeof c.scope=="string"?c.scope:""}}};function fo(r){let e=r.chainPem.trim();return e?`${r.certificatePem.replace(/\s+$/,"")}
|
|
100
|
+
${e}
|
|
101
|
+
`:r.certificatePem}function yo(r){try{return uo({key:r,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var ho=r=>new Promise((e,t)=>{let n=new URL(r.url),o=ht.request({method:"POST",hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,cert:r.certPem,key:r.keyPem,headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(r.body),Accept:"application/json"},timeout:3e4},i=>{let s=[];i.on("data",a=>s.push(a)),i.on("end",()=>e({status:i.statusCode??0,body:Buffer.concat(s).toString("utf-8")}))});o.on("error",t),o.on("timeout",()=>o.destroy(new Error("mTLS request timed out"))),o.write(r.body),o.end()});var _=class extends Error{},N=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new R,this.deviceStore=e.deviceStore??new D,this.sessionStore=e.sessionStore??new $,this.exchange=e.exchange??new T}async acquire(e,t={}){let n=l(e),o=await this.sessionEndpoint(e);if(!o)throw new _(`'${n}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let i=await this.deviceStore.get(e);if(!i)throw new _(`No device certificate enrolled for '${n}'. Run 'kanonak device enroll ${e}' first.`);let s=await this.exchange.exchange(o,i,t),a={token:s.token,tokenType:s.tokenType,expiresAt:s.expiresAt,scope:s.scope};return await this.sessionStore.store(n,a),a}async getValidSession(e){let t=l(e),n=await this.sessionStore.get(t);return n&&!le(n)?n:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(l(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var pe=class{discovery;sessions;constructor(e={}){this.discovery=e.discovery??new R,this.sessions=e.sessionManager??new N}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;for(let n of t){let o=go(n);if(!o)continue;let i=await this.sessions.getValidSession(o);if(i)return{authority:o,token:i.token,expiresAt:i.expiresAt,scope:i.scope}}return null}};function go(r){try{return new URL(r).host}catch{return}}import{createHash as ko,createPrivateKey as So,generateKeyPairSync as wo,randomUUID as bo,sign as Po}from"crypto";function kt(){let{publicKey:r,privateKey:e}=wo("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function z(r,e,t,n,o,i){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:bo(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(a.ath=ko("sha256").update(o).digest("base64url")),i&&(a.nonce=i),vo(s,a,r)}function St(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function vo(r,e,t){let n=gt(JSON.stringify(r)),o=gt(JSON.stringify(e)),i=`${n}.${o}`,s=So({key:t,format:"jwk"}),c=Po("SHA256",Buffer.from(i),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function gt(r){return Buffer.from(r,"utf-8").toString("base64url")}function wt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return I(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return I(t,{method:o});Q(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(i.dpopKeyPair){let c=e.get(n);try{let p=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.Authorization=`DPoP ${i.accessToken}`,s.DPoP=p}catch(p){let d=p instanceof Error?p.message:String(p);console.error(` Error: Failed to create DPoP proof for '${n}': ${d}
|
|
102
|
+
The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${i.accessToken}`}}else s.Authorization=`Bearer ${i.accessToken}`;let a=await I(t,{method:o,headers:s});if(a.status===401&&i.dpopKeyPair){let c=a.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let p=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.DPoP=p,a=await I(t,{method:o,headers:s})}catch{}}}return a}}import{readFileSync as Ro,writeFileSync as Eo,existsSync as Co}from"fs";import{createHash as xo}from"crypto";import bt from"js-yaml";var Pt="kanonak.lock",Ao=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
103
|
+
`;function vt(r=Pt){if(!Co(r))return null;let e=Ro(r,"utf-8"),t=bt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Rt(r,e=Pt){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=bt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Eo(e,Ao+n,"utf-8")}function Et(r){return`sha256:${xo("sha256").update(r).digest("hex")}`}import*as Ve from"js-yaml";import{canonicalForm as Io,canonicalHash as Ko}from"@kanonak-protocol/canonical";function Be(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as $t}from"@kanonak-protocol/canonical";function Ct(r){return Io(Be(r)?r:xt(r))}function de(r){return Ko(Be(r)?r:xt(r))}function xt(r){let e=[];for(let t of r)t instanceof b&&e.push({uri:_o(t),statements:Me(t.statement)});return{subjects:e}}function Me(r){let e=[];for(let t of r){let n=To(t);if(!n)continue;let o=Do(t);o&&e.push({predicate:n,value:o})}return e}function Do(r){if(r instanceof we&&r.carrier)return{lit:r.lexical??String(r.object),datatype:It(r.carrier)};if(r instanceof be)return{raw:r.object};if(r instanceof Pe)return{raw:r.lexical??String(r.object)};if(r instanceof ve)return{raw:r.lexical??String(r.object)};if(r instanceof Re)return{ref:Kt(r.object)};if(r instanceof Ee)return At(r.object);if(r instanceof Ce)return{list:r.object.map($o)}}function At(r){let e=Me(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function $o(r){if(r instanceof C)return{ref:Kt(r)};if(r instanceof P)return At(r);if(r instanceof Se){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:It(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 ke)return{embed:{statements:Me(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 It(r){return r===Z.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function To(r){let e=r.predicate;if(e)return Dt(e.subject)}function _o(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function Kt(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 Tt}from"@kanonak-protocol/types/document/models/enums";var No="0.0.0",j=class{constructor(e,t=new M,n){this.repository=e;this.parser=t;this.objectParser=n??new U(this.parser)}repository;parser;objectParser;imports(){return new W}serializeValue(e,t){return jt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Le(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let s={[o]:i,...e.body},a=this.dump(s);return{yaml:a,byteCount:Nt(a),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},s=this.dump(i),a={yaml:s,byteCount:Nt(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(a.contentHash=o),a}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[_t]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ve.dump(o,{lineWidth:-1})),s=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Xe(i,this.repository))).filter(p=>p instanceof b&&p.namespace===s&&p.name!==_t);for(let p of c)p.namespace="ephemeral";return de(c)}},_t="__pkgbuilder_probe__";function Nt(r){return new TextEncoder().encode(r).length}function Le(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var W=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=Tt.Major){let s=`${e}/${t}@${n}`,a=this.byKey.get(s);if(a)return a.alias;let c=this.uniqueAlias(o);return this.byKey.set(s,{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_,E(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,No,o??t,Tt.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:ge(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=G(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function jt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof C)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>jt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof P)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(jo(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 G(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function jo(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ue=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}@${E(o)}`,s=this.produced.get(i);if(s)return s;let{document:a}=await e.produce(t,n,o);return this.produced.set(i,a),a}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=Ke(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ue={async authorize(){return{allowed:!0}}},Fe={async record(){}},J=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},me=class{inner;ctx;policy;meter;constructor(e,t,n=Ue,o=Fe){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 J(e,t.reason)}};var u="kanonak.org",w="view",Ot="core-kanonak",Oo={publisher:u,package_:w,name:"rootView"},Bo={publisher:u,package_:w,name:"bind"},Mo={publisher:u,package_:w,name:"produces"},Vo={publisher:u,package_:w,name:"projections"},Lo={publisher:u,package_:w,name:"where"},Uo={publisher:u,package_:w,name:"value"},Fo={publisher:u,package_:w,name:"as"},fe=class{constructor(e,t=new M){this.repository=e;this.parser=t;this.objectParser=new U(this.parser),this.builder=new j(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=V(o,Bo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let s=V(o,Mo);if(!s)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 a=Ho(o),c=Bt(n,u,Ot),p=Bt(n,u,w),d=this.builder.imports(),O=d.ensure(u,Ot,c,"ck"),Vt=d.ensure(u,w,p,"v"),Lt=d.ref(s),Ut=new Qe(this.repository,this.parser,this.objectParser),He=new Ye(Ut,n),Ft=this.readProjections(n,o),Ht=Go(o,Lo),zt=this.findInstances(n,i,await this.reason(t)),ze={},Wt=new Set;for(let q of zt){if(!await this.passesWhere(He,n,Ht,q))continue;let he={type:Lt};for(let Ge of Ft){let Gt=await this.evaluateValue(He,n,Ge.value,q),Je=this.builder.serializeValue(Mt(Gt),d);Je!==void 0&&(he[d.ref(Ge.as)]=Je)}let We=v(q);We&&(he[`${Vt}.derivedFrom`]=d.ref(We)),ze[this.rowName(q,Wt)]=he}let ye={};t.resolvedAt&&(ye[`${O}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ye[`${O}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:d,body:ze,contentHashProperty:`${O}.contentHash`,header:ye});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let n=Y(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=V(n,Oo);if(o){let i=Y(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 Ae(t,Vo)){let i=o instanceof P?o:o instanceof C?Y(e,o.subject):void 0;if(!i)continue;let s=xe(i,Uo),a=V(i,Fo);s&&a&&n.push({value:s,as:a})}return n}async reason(e){return new Ie({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=Wo(e),i=[],s=new Set;for(let a of n.getInstancesOfClass(t)){if(s.has(a))continue;s.add(a);let c=o.get(a);c&&i.push(c)}return i.sort((a,c)=>{let p=L(v(a)),d=L(v(c));return p<d?-1:p>d?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let s=await this.evaluateValue(e,t,i,o);if(!Jo(s))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ze(n,"view-projection",{catalog:t,depth:0}),s=new Map([["input",o]]);return e.evaluate(i,s)}rowName(e,t){let n=G(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Mt(r){return De(r)?r.value:Array.isArray(r)?r.map(Mt):r}function Ho(r){let e=v(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=zo(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 zo(r,e,t){let n;for(let o of r){if(!(o instanceof b))continue;let i=v(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||X(i.version,n)>0)&&(n=i.version)}return n?E(n):void 0}function Wo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof b))continue;let o=v(n);if(!o||!o.version)continue;let i=L(o),s=t.get(i);(!s||X(o.version,s)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function Go(r,e){let t=xe(r,e);return t?[t]:Ae(r,e).filter(n=>n instanceof P)}function Jo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:De(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{kn as AmbiguousReferenceRule,ve as BooleanStatement,$t as CANONICAL_FORM_VERSION,Z as Carrier,Rn as ClassDefinitionRule,dn as ClassHierarchyCycleRule,or as CompositeKanonakDocumentRepository,pe as CredentialResolver,ce as CredentialStore,yt as DEFAULT_CONSENT_BINDING_PARAM,ke as DefinedKanonak,D as DeviceCertificateStore,nr as DocumentLocation,$r as EdgeType,P as EmbeddedKanonak,cn as EmbeddedKanonakTypeRule,Ee as EmbeddedStatement,J as EntitlementDeniedError,me as EntitlementProducer,rr as FileSystemKanonakDocumentRepository,Br as GitIgnoreFilter,Tr as GraphBuilder,mr as HttpKanonakDocumentRepository,W as ImportBook,ln as ImportExistenceRule,tr as InMemoryKanonakDocumentRepository,ar as KANONAK_USER_AGENT,kr as Kanonak,Vr as KanonakDocumentPositions,U as KanonakObjectParser,Cn as KanonakObjectValidator,M as KanonakParser,Sr as KanonakUri,Fr as KanonakUriBuilder,zr as KanonakUrlResolver,xr as KanonakVocabulary,Ce as ListStatement,Se as LiteralKanonak,fr as LocalFirstRepository,yr as LockAwareRepository,In as LookRenderer,En as MarkdownLinkRule,br as MarkdownStatement,hn as NamespaceImportCycleRule,rn as NamespacePrefixRule,Dr as NodeType,Pe as NumberStatement,R as OAuthDiscovery,jr as OWL_RL_CLASSIFICATION_RULES,wn as ObjectPropertyValueValidationRule,Qr as OntologyValidationError,Yr as OntologyValidationResult,j as PackageBuilder,an as PackageHeaderRule,ue as ProducerRepository,bn as PropertyDomainRule,un as PropertyHierarchyCycleRule,Pn as PropertyKindRangeConsistencyRule,Mr as PropertyMetadata,Sn as PropertyRangeReferenceRule,mn as PropertyRangeRequiredRule,on as PropertyTypeSpecificityRule,pr as PublisherConfigResolver,dr as PublisherIndex,Nr as RDFS_RULES,Ie as Reasoner,Or as ReasoningResult,C as ReferenceKanonak,Re as ReferenceStatement,sr as RepositoryFactory,vn as ReservedNameShadowRule,nn as ResourceNamingRule,Pr as ResourceResolver,Kr as ResourceTypeClassifier,we as ScalarStatement,_ as SessionError,T as SessionExchange,S as SessionExchangeError,N as SessionManager,$ as SessionStore,wr as Statement,be as StringStatement,fn as SubClassOfReferenceRule,yn as SubPropertyOfReferenceRule,b as SubjectKanonak,sn as SubjectKanonakTypeRequiredRule,_r as TripleStore,vr as TypeResolver,gn as UnresolvedPredicateRule,pn as UnresolvedReferenceRule,tn as ValidationCache,en as ValidationContext,Zr as ValidationSeverity,Oa as VersionOperator,fe as ViewMaterializer,Ue as allowAllPolicy,ur as assertPackageIdentity,gr as buildLocalFirstRepository,Kn as buildOntologyModel,Ct as canonicalForm,de as canonicalHash,qe as carrierOf,hr as collectKanonakFiles,X as compareVersions,Et as computeIntegrity,Le as contentAddressedName,qr as contextTypesOf,wt as createAuthenticatedFetch,z as createDPoPProof,Xt as createVersion,Ir as extractMarkdownLinks,xn as findDerivation,Xr as findInstancesByType,Ar as findMalformedReferences,Ur as findMarkdownLinkAt,Hr as formatKanonakAddress,E as formatVersion,kt as generateDPoPKeyPair,ir as getGlobalCachePath,lr as getKanonakUserAgent,ee as hasValidToken,Zt as isCompatibleVersion,Q as isExpired,Qt as isMajorCompatible,I as kanonakFetch,vt as loadLockFile,Rr as makeUriKey,Fe as noopMeter,l as normalizeHost,Ke as parseKanonakAddress,Yt as parseVersionString,Lr as parseWithPositions,er as pickHighestDocument,Gr as propertiesInScope,An as resolveDisplayValue,Jr as resolvePropertyStep,G as sanitizeName,Rt as saveLockFile,St as serverSupportsDPoP,le as sessionNeedsRefresh,cr as setKanonakUserAgent,v as subjectUri,Wr as superClassChain,Er as tripleKey,L as uriKey,Cr as uriTriple,Jt as versionOperatorFromChar,ge as versionOperatorToChar,qt as versionsEqual};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.1.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": "^5.
|
|
129
|
+
"@kanonak-protocol/types": "^5.1.0",
|
|
130
130
|
"ignore": "^7.0.5",
|
|
131
131
|
"js-yaml": "^4.1.0",
|
|
132
132
|
"yaml": "^2.7.0"
|