@kanonak-protocol/sdk 3.58.0 → 3.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-WDQONH3P.js";import{a as Qe}from"./chunk-IIODYDKS.js";import"./chunk-3NEUHF7E.js";import{a as H,c as L,d as W,e as F}from"./chunk-6SGRDFL5.js";import{a as Pe,b as we,c as he}from"./chunk-CYDDQF6S.js";import{a as ke,b as be}from"./chunk-DC774EQL.js";import"./chunk-NIGFQYVA.js";import{A as We,B as Fe,C as Ge,E as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-BSJ6PEKE.js";import{c as pe}from"./chunk-VJT6YUWK.js";import{a as Y,c as le}from"./chunk-H2LEQLVD.js";import{a as q}from"./chunk-7CUTGGH3.js";import{a as ye}from"./chunk-N224PFBI.js";import"./chunk-Q4DKP5DO.js";import{a as O,b as V,c as $,d as U,e as z,f as M,g as N,h as J}from"./chunk-FQHALFRR.js";import{b as ue,c as de}from"./chunk-64TVBQFR.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-W6T7MOKY.js";import{a as Z}from"./chunk-FUUTGGJS.js";var j="kanonak-credentials",u="credentials",Ye=1,f=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
1
+ import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-WDQONH3P.js";import{a as Qe}from"./chunk-IIODYDKS.js";import"./chunk-3NEUHF7E.js";import{a as H,c as L,d as W,e as F}from"./chunk-4FZUKBBE.js";import{a as Pe,b as we,c as he}from"./chunk-CYDDQF6S.js";import{a as ke,b as be}from"./chunk-PEUTCG3B.js";import"./chunk-NIGFQYVA.js";import"./chunk-SC5M74NM.js";import{A as We,B as Fe,C as Ge,E as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-BSJ6PEKE.js";import{c as pe}from"./chunk-VJT6YUWK.js";import{a as Y,c as le}from"./chunk-H2LEQLVD.js";import{a as q}from"./chunk-7CUTGGH3.js";import{a as ye}from"./chunk-N224PFBI.js";import"./chunk-Q4DKP5DO.js";import{a as O,b as V,c as $,d as U,e as z,f as M,g as N,h as J}from"./chunk-FQHALFRR.js";import{b as ue,c as de}from"./chunk-64TVBQFR.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-W6T7MOKY.js";import{a as Z}from"./chunk-FUUTGGJS.js";var j="kanonak-credentials",u="credentials",Ye=1,f=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
2
2
  Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await er(t)),o&&(s.nonce=o),await Ze(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function Ze(n,r,e){let t=v(JSON.stringify(n)),o=v(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=D(s);return`${t}.${o}.${l}`}async function er(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return D(e)}function v(n){let r=new TextEncoder().encode(n);return D(r.buffer)}function D(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var rr=300*1e3,S=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new f,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=x(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let g=await k();a=g.keys,s=g.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let g=await this.registerClient(t.registrationEndpoint);if(!g)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=g.clientId,c=g.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=tr(),p=await nr(m),R=or(),A=sr(t.authorizationEndpoint,i,this.callbackUrl,R,p),y=await this.openAuthPopup(A,R);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==R)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let T={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,T),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await fetch(e);if(!t.ok)continue;let o=await t.json();return{issuer:w(o.issuer),authorizationEndpoint:w(o.authorization_endpoint),tokenEndpoint:w(o.token_endpoint),registrationEndpoint:w(o.registration_endpoint),revocationEndpoint:w(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},rr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await K(l,"POST",r));try{let m=await fetch(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function tr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function nr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function or(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function sr(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Ne as AmbiguousReferenceRule,se as BooleanStatement,f as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,ze as DefinitionPropertyReferenceRule,fe as EdgeType,Y as EmbeddedKanonak,je as EmbeddedKanonakTypeRule,ae as EmbeddedStatement,me as GraphBuilder,F as HttpKanonakDocumentRepository,ve as ImportExistenceRule,H as InMemoryKanonakDocumentRepository,Ue as InstancePropertyReferenceRule,G as Kanonak,we as KanonakDocumentPositions,pe as KanonakObjectParser,Xe as KanonakObjectValidator,q as KanonakParser,Z as KanonakUri,ke as KanonakUriBuilder,ce as ListStatement,Ge as MarkdownLinkRule,le as MarkdownStatement,$e as NamespaceImportCycleRule,De as NamespacePrefixRule,ge as NodeType,oe as NumberStatement,He as ObjectPropertyImportRule,qe as ObjectPropertyValueValidationRule,Se as OntologyValidationError,Ke as OntologyValidationResult,Le as PropertyDomainRule,Ae as PropertyHierarchyCycleRule,Pe as PropertyMetadata,Je as PropertyRangeReferenceRule,Te as PropertyRangeRequiredRule,Ce as PropertyTypeSpecificityRule,We as PropertyValueTypeRule,L as PublisherConfigResolver,W as PublisherIndex,ee as ReferenceKanonak,ie as ReferenceStatement,Be as ResourceNamingRule,ue as ResourceResolver,ye as ResourceTypeClassifier,te as ScalarStatement,re as Statement,ne as StringStatement,Oe as SubClassOfReferenceRule,Ve as SubPropertyOfReferenceRule,Q as SubjectKanonak,Ee as SubjectKanonakTypeRequiredRule,de as TypeResolver,_e as UnresolvedReferenceRule,Re as ValidationContext,xe as ValidationSeverity,Me as XsdImportRule,x as browserServerSupportsDPoP,O as compareVersions,K as createBrowserDPoPProof,U as createVersion,Qe as findDerivation,be as findInstancesByType,$ as formatVersion,k as generateBrowserDPoPKeyPair,_ as generateBrowserDPoPKeys,E as hasValidToken,b as importDPoPKeys,M as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,z as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
@@ -0,0 +1,2 @@
1
+ import{a as d}from"./chunk-SC5M74NM.js";import{a as P}from"./chunk-7CUTGGH3.js";import{a as f,b as k,f as y,g as v}from"./chunk-FQHALFRR.js";var C=class{documents=new Map;documentContents=new Map;parser;constructor(t){this.parser=t}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){let s=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===t&&n.metadata?.namespace_?.package_===e&&s.push(n);return s}async getHighestCompatibleVersionAsync(t,e){let s=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e.packageName&&r.metadata?.namespace_?.version!==void 0&&s.push(r);if(s.length===0)return null;let n=s.filter(r=>{let a=r.metadata.namespace_.version;if(!a)return!1;switch(e.versionOperator){case 0:return k(a,e.version);case 1:return y(a,e.version);case 2:return v(a,e.version);case 3:return f(a,e.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((r,a)=>{let o=r.metadata.namespace_.version,c=a.metadata.namespace_.version;return!o&&!c?0:o?c?f(c,o):-1:1}),n[0])}async saveDocumentAsync(t,e){this.documents.set(e,t);let s=this.parser.save(t);this.documentContents.set(e,s)}async deleteDocumentAsync(t){this.documents.delete(t),this.documentContents.delete(t)}async clearNamespaceAsync(t,e){let s=[];for(let[n,r]of this.documents.entries())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e&&s.push(n);for(let n of s)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let t=[];for(let e of this.documents.values())e.metadata?.namespace_&&t.push({identifier:e.metadata.namespace_.toString(),uri:`kanonak://${e.metadata.namespace_}`,hasParseError:!1});return t}async getDocumentContentAsync(t){let e=this.documentContents.get(t);if(e!==void 0)return e;let s=this.documents.get(t);return s!==void 0?this.parser.save(s):null}async getDocumentUriAsync(t){let e=this.documents.get(t);return e?e.metadata?.namespace_?`kanonak://${e.metadata.namespace_}`:`kanonak://${t}`:null}};var D="https://{publisher}/index.txt",F="https://{publisher}/{package}/{version}.kan.yml",x={version:1};function N(i){return{version:1,index:D.replaceAll("{publisher}",i),package:F.replaceAll("{publisher}",i),auth:"none"}}var m=class{cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,s;try{s=await fetch(e)}catch{return x}if(s.status===404)return x;if(!s.ok)throw new Error(`Failed to fetch publisher config: ${e} (${s.status} ${s.statusText})`);let n=await s.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let r={version:n.version};return typeof n.index=="string"&&(r.index=n.index),typeof n.package=="string"&&(r.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(r.auth=n.auth),r}resolveIndexUrl(t,e){let s=e.index??D;return w(s,{publisher:t})}resolvePackageUrl(t,e,s,n){let r=n.package??F;return w(r,{publisher:t,package:e,version:s})}};function w(i,t){let e=i;for(let[n,r]of Object.entries(t))e=e.replaceAll(`{${n}}`,r);let s=e.match(/\{[a-z]+\}/);if(s)throw new Error(`Unresolved variable ${s[0]} in URL template: ${i}`);return e}import{VersionOperator as g}from"@kanonak-protocol/types/document/models/enums";var u=class i{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new m,this.fetchFn=t?.fetchFn}async resolveVersion(t,e){let s=await this.getPackageVersions(t,e.packageName);if(s.length===0)return null;let n=s.filter(r=>this.isVersionCompatible(r,e.version,e.versionOperator));return n.length===0?null:(n.sort((r,a)=>this.compareVersionStrings(a,r)),n[0])}async getHighestVersion(t,e){let s=await this.getPackageVersions(t,e);return s.length===0?null:[...s].sort((r,a)=>this.compareVersionStrings(a,r))[0]}async listLatestPackages(t){let e=await this.getIndex(t),s=[];for(let[n,r]of e){if(r.length===0)continue;let a=[...r].sort((o,c)=>this.compareVersionStrings(c,o));s.push({packageName:n,version:a[0]})}return s.sort((n,r)=>n.packageName.localeCompare(r.packageName)),s}async getPackageUrl(t,e,s){let n=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,s,n)}async getPackageVersions(t,e){return(await this.getIndex(t)).get(e)??[]}getIndex(t){let e=this.indexCache.get(t);return e||(e=this.fetchIndex(t),this.indexCache.set(t,e),e.catch(()=>{this.indexCache.get(t)===e&&this.indexCache.delete(t)})),e}async fetchIndex(t){let e=await this.configResolver.getConfig(t),s=this.configResolver.resolveIndexUrl(t,e),n=this.fetchFn?await this.fetchFn(s,t):await fetch(s);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${s} (${n.status} ${n.statusText})`);let r=await n.text();return i.parseIndex(r)}static parseIndex(t){let e=new Map;for(let s of t.split(`
2
+ `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("/");if(r===-1)continue;let a=n.substring(0,r),o=n.substring(r+1);if(!a||!o)continue;let c=e.get(a);c?c.push(o):e.set(a,[o])}return e}isVersionCompatible(t,e,s){let n=i.parseVersion(t);if(!n)return!1;switch(s){case g.Any:return!0;case g.Exact:return n.major===e.major&&n.minor===e.minor&&n.patch===e.patch;case g.Compatible:return n.major===e.major&&n.minor===e.minor&&n.patch>=e.patch;case g.Major:return n.major!==e.major?!1:n.minor>e.minor?!0:n.minor===e.minor?n.patch>=e.patch:!1;default:return!1}}static parseVersion(t){let e=t.split(".");if(e.length<2)return null;let s=parseInt(e[0],10),n=parseInt(e[1],10),r=e.length>=3?parseInt(e[2],10):0;return isNaN(s)||isNaN(n)||isNaN(r)?null:{major:s,minor:n,patch:r}}compareVersionStrings(t,e){let s=i.parseVersion(t),n=i.parseVersion(e);return!s&&!n?0:s?n?s.major!==n.major?s.major-n.major:s.minor!==n.minor?s.minor-n.minor:s.patch-n.patch:1:-1}};var A=class{parser=new P;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new u({fetchFn:t.fetchFn}):new u}async getHighestCompatibleVersionAsync(t,e){let s=await this.publisherIndex.resolveVersion(t,e);if(!s)return null;let n=`${t}/${e.packageName}@${s}`,r=this.documents.get(n);if(r)return r;if(this.getFromCache){let h=this.getFromCache(t,e.packageName,s);if(h){let p=this.parser.parse(h);return d(p,t,e.packageName,s),this.documents.set(n,p),this.contentCache.set(n,h),p}}let a=await this.publisherIndex.getPackageUrl(t,e.packageName,s),o=this.fetchFn?await this.fetchFn(a,t):await fetch(a);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${o.status} ${o.statusText})`);let c=await o.text(),l=this.parser.parse(c);return d(l,t,e.packageName,s),this.onFetch&&this.onFetch(t,e.packageName,s,c),this.documents.set(n,l),this.contentCache.set(n,c),l}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(s=>{let n=s.metadata.namespace_;return n&&n.publisher===t&&n.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,s,n,r]=e;return this.publisherIndex.getPackageUrl(s,n,r)}};export{C as a,N as b,m as c,u as d,A as e};
@@ -1 +1 @@
1
- import{a as w,e as A}from"./chunk-6SGRDFL5.js";import{a as f}from"./chunk-7CUTGGH3.js";import{a as P,b as K,f as I,g as R}from"./chunk-FQHALFRR.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as F}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case 0:return K(r,t.version);case 1:return I(r,t.version);case 2:return R(r,t.version);case 3:return P(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return P(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],p=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,p)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=F(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return F(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as d from"fs";var b=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(b||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(t)||d.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as x}from"path";function g(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||x(_(),".kanonak","packages")}var v=class u{static createComposite(e,t,n){let o=e??g(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=g(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{readFileSync as N,readdirSync as B}from"fs";import{join as S}from"path";var H=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of B(u,{withFileTypes:!0}))t.isDirectory()?H.has(t.name)||C(S(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(S(u,t.name));return e}async function $(u,e=new f,t={}){let n=new w(e);for(let m of C(u))try{let l=e.parse(N(m,"utf-8")),h=l.metadata?.namespace_,p=h?.version;h&&p&&await n.saveDocumentAsync(l,`${h.publisher}/${h.package_}@${p.major}.${p.minor}.${p.patch}`)}catch{}let o=new y(g(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,h)=>s.get(`${m}|${l}|${h}`)??null,onFetch:(m,l,h,p)=>{s.set(`${m}|${l}|${h}`,p)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,b,k as c,g as d,v as e,D as f,C as g,$ as h};
1
+ import{a as w,e as A}from"./chunk-4FZUKBBE.js";import{a as f}from"./chunk-7CUTGGH3.js";import{a as P,b as K,f as I,g as R}from"./chunk-FQHALFRR.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as F}from"url";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case 0:return K(r,t.version);case 1:return I(r,t.version);case 2:return R(r,t.version);case 3:return P(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return P(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],p=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,p)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=F(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return F(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as d from"fs";var b=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(b||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(t)||d.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as x}from"path";function g(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||x(_(),".kanonak","packages")}var v=class u{static createComposite(e,t,n){let o=e??g(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=g(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{readFileSync as N,readdirSync as B}from"fs";import{join as S}from"path";var H=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function C(u,e=[]){for(let t of B(u,{withFileTypes:!0}))t.isDirectory()?H.has(t.name)||C(S(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(S(u,t.name));return e}async function $(u,e=new f,t={}){let n=new w(e);for(let m of C(u))try{let l=e.parse(N(m,"utf-8")),h=l.metadata?.namespace_,p=h?.version;h&&p&&await n.saveDocumentAsync(l,`${h.publisher}/${h.package_}@${p.major}.${p.minor}.${p.patch}`)}catch{}let o=new y(g(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,h)=>s.get(`${m}|${l}|${h}`)??null,onFetch:(m,l,h,p)=>{s.set(`${m}|${l}|${h}`,p)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,b,k as c,g as d,v as e,D as f,C as g,$ as h};
@@ -1 +1 @@
1
- import{a as m}from"./chunk-FUUTGGJS.js";var f=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,r){return(await this.resourceResolver.resolveEntityAsync(e,r))?.uri??null}buildFromName(e,r,s){if(e.includes(".")){let o=e.split("."),c=o[0],u=o[1],a=this.findPackageNameForAlias(s,c);if(a){for(let i of r.values())if(i.entityName===u&&i.uri.package_===a)return i.uri}return null}let n=r.get(e);return n?n.uri:null}create(e,r,s,n){return new m(e,r,s,n)}findPackageNameForAlias(e,r){if(!e.metadata.imports)return null;for(let[s,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===r||!o.alias&&o.packageName===r)return o.packageName;return null}};async function R(t,e){let r=[],s=await t.getAllDocumentsAsync();for(let n of s){let o=n.metadata.namespace_;if(!o)continue;let c=o.publisher,u=o.package_,a=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[i,p]of Object.entries(n.body)){if(!p||typeof p!="object")continue;let l=p.type;!l||typeof l!="string"||l!=="Package"&&d(l,e)&&r.push({entityName:i,entity:p,documentNamespace:`${c}/${u}@${a}`,publisher:c,package_:u,version:a})}}return r}function d(t,e){let r=y(t),s=y(e);return r===s}function y(t){let e=t.lastIndexOf(".");if(e!==-1)return t.substring(e+1);let r=t.lastIndexOf("/");return r!==-1?t.substring(r+1):t}export{f as a,R as b};
1
+ import{a as m}from"./chunk-FUUTGGJS.js";var f=class{resourceResolver;constructor(e){this.resourceResolver=e}async buildFromNameAsync(e,r){return(await this.resourceResolver.resolveEntityAsync(e,r))?.uri??null}buildFromName(e,r,s){if(e.includes(".")){let o=e.split("."),c=o[0],p=o[1],a=this.findPackageNameForAlias(s,c);if(a){for(let i of r.values())if(i.entityName===p&&i.uri.package_===a)return i.uri}return null}let n=r.get(e);return n?n.uri:null}create(e,r,s,n){return new m(e,r,s,n)}findPackageNameForAlias(e,r){if(!e.metadata.imports)return null;for(let[s,n]of Object.entries(e.metadata.imports))for(let o of n)if(o.alias===r||!o.alias&&o.packageName===r)return o.packageName;return null}};async function R(t,e){let r=[],s=await t.getAllDocumentsAsync();for(let n of s){let o=n.metadata.namespace_;if(!o)continue;let c=o.publisher,p=o.package_,a=o.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"0.0.0";for(let[i,u]of Object.entries(n.body)){if(!u||typeof u!="object")continue;let l=u.type;!l||typeof l!="string"||l!=="Package"&&d(l,e)&&r.push({entityName:i,entity:u,documentNamespace:`${c}/${p}@${a}`,publisher:c,package_:p,version:a})}}return r}function d(t,e){let r=y(t),s=y(e);return r===s}function y(t){let e=t.lastIndexOf(".");if(e!==-1)return t.substring(e+1);let r=t.lastIndexOf("/");return r!==-1?t.substring(r+1):t}export{f as a,R as b};
@@ -0,0 +1 @@
1
+ function i(s,n,o,a){let e=s.metadata?.namespace_,t=e?.version,c=t?`${t.major}.${t.minor}.${t.patch}`:void 0;if(!e||e.publisher!==n||e.package_!==o||c!==a){let r=e?`${e.publisher}/${e.package_}@${c??"?"}`:"(no namespace declared)";throw new Error(`Package identity mismatch: requested ${n}/${o}@${a} but the fetched document declares ${r}. Refusing to use it.`)}}export{i as a};
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@ export { GitIgnoreFilter } from './filtering/index.js';
8
8
  export type { IGitIgnoreFilter } from './filtering/index.js';
9
9
  export { KanonakParser, KanonakObjectParser, PropertyMetadata, KanonakDocumentPositions, parseWithPositions, findMarkdownLinkAt, } from './parsing/index.js';
10
10
  export type { IKanonakObjectParser, SourcePosition, ImportPackageEntry, ParsedDocumentWithPositions, } from './parsing/index.js';
11
- export { ResourceResolver, KanonakUri, KanonakUriBuilder, parseKanonakAddress, formatKanonakAddress, KanonakUrlResolver, TypeResolver, ResourceTypeClassifier, findInstancesByType, compareVersions, versionsEqual, formatVersion, parseVersionString, createVersion, isCompatibleVersion, isMajorCompatible, pickHighestDocument, propertiesInScope, resolvePropertyStep, contextTypesOf, subjectUri, } from './resolution/index.js';
11
+ export { ResourceResolver, KanonakUri, KanonakUriBuilder, parseKanonakAddress, formatKanonakAddress, KanonakUrlResolver, TypeResolver, ResourceTypeClassifier, findInstancesByType, compareVersions, versionsEqual, formatVersion, parseVersionString, createVersion, isCompatibleVersion, isMajorCompatible, pickHighestDocument, propertiesInScope, resolvePropertyStep, contextTypesOf, subjectUri, assertPackageIdentity, } from './resolution/index.js';
12
12
  export type { ResourceResolutionResult, ILogger, InstanceSearchResult, DocumentVersionPick, PropertyDescriptor, PropertyKind, StepResolution, KanonakAddress, UrlAddress, PublisherUrlAddress, PackageUrlAddress, ResourceUrlAddress, VersionSpec, UrlForm, } from './resolution/index.js';
13
13
  export { Kanonak, DefinedKanonak, SubjectKanonak, EmbeddedKanonak, ReferenceKanonak, LiteralKanonak } from './kanonaks/index.js';
14
14
  export type { IStatement } from './statements/index.js';
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{a as ct,b as lt,c as dt,d as ut,e as pt}from"./chunk-SD5QKNBC.js";import{a as or,c as ar}from"./chunk-ESYVKB25.js";import{a as at,b as it,c as st,d as b,e as S,f as i}from"./chunk-WDQONH3P.js";import{a as nr}from"./chunk-IIODYDKS.js";import"./chunk-3NEUHF7E.js";import{a as Te,b as je,c as Le,d as Fe,e as De,f as Ue,g as Ve,h as He}from"./chunk-MYPKSBTP.js";import{a as Ie,c as Ne,d as Oe,e as Ae}from"./chunk-6SGRDFL5.js";import{a as ft,b as yt,c as gt,d as ht}from"./chunk-CYDDQF6S.js";import{a as kt,b as $t}from"./chunk-DC774EQL.js";import{a as Ct}from"./chunk-NIGFQYVA.js";import{A as Qt,B as er,C as tr,E as rr,a as vt,b as Et,c as Kt,d as It,e as Bt,f as Tt,g as jt,h as Lt,i as Ft,j as Dt,k as Nt,l as Ot,m as At,n as Ut,o as Vt,p as Ht,q as Mt,r as _t,s as zt,t as Gt,u as Wt,v as Jt,w as qt,x as Yt,y as Xt,z as Zt}from"./chunk-BSJ6PEKE.js";import{a as tt,b as rt,c as nt}from"./chunk-VJT6YUWK.js";import{a as F,b as N,c as We}from"./chunk-H2LEQLVD.js";import{a as Be}from"./chunk-7CUTGGH3.js";import{a as ot,b as bt,c as St,d as Pt,e as Rt,f as wt,g as xt}from"./chunk-N224PFBI.js";import"./chunk-Q4DKP5DO.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as Je,c as qe,d as Ye,e as Xe,f as Ze,h as Qe,j as et}from"./chunk-64TVBQFR.js";import{a as Me,b as j,c as L,d as D,e as ze,f as Ge,g as O,h as A,i as U,j as V,k as H,l as M}from"./chunk-W6T7MOKY.js";import{a as _e}from"./chunk-FUUTGGJS.js";import{a as mt}from"./chunk-ODIECDN7.js";import{VersionOperator as yo}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Rr,readFileSync as wr}from"fs";import{homedir as xr}from"os";import{join as $r}from"path";import{execFile as ir}from"child_process";import{promisify as sr}from"util";var C=sr(ir),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
1
+ import{a as lt,b as dt,c as ut,d as pt,e as mt}from"./chunk-SD5QKNBC.js";import{a as ar,c as ir}from"./chunk-ESYVKB25.js";import{a as it,b as st,c as ct,d as b,e as S,f as i}from"./chunk-WDQONH3P.js";import{a as or}from"./chunk-IIODYDKS.js";import"./chunk-3NEUHF7E.js";import{a as Te,b as je,c as Le,d as Fe,e as De,f as Ve,g as He,h as Me}from"./chunk-7RAM5KZZ.js";import{a as Ie,c as Ne,d as Oe,e as Ue}from"./chunk-4FZUKBBE.js";import{a as yt,b as gt,c as ht,d as kt}from"./chunk-CYDDQF6S.js";import{a as bt,b as vt}from"./chunk-PEUTCG3B.js";import{a as Pt}from"./chunk-NIGFQYVA.js";import{a as Ae}from"./chunk-SC5M74NM.js";import{A as er,B as tr,C as rr,E as nr,a as Et,b as Kt,c as It,d as Bt,e as Tt,f as jt,g as Lt,h as Ft,i as Dt,j as Nt,k as Ot,l as At,m as Ut,n as Vt,o as Ht,p as Mt,q as _t,r as zt,s as Gt,t as Wt,u as Jt,v as qt,w as Yt,x as Xt,y as Zt,z as Qt}from"./chunk-BSJ6PEKE.js";import{a as rt,b as nt,c as ot}from"./chunk-VJT6YUWK.js";import{a as F,b as N,c as Je}from"./chunk-H2LEQLVD.js";import{a as Be}from"./chunk-7CUTGGH3.js";import{a as at,b as St,c as Ct,d as Rt,e as wt,f as xt,g as $t}from"./chunk-N224PFBI.js";import"./chunk-Q4DKP5DO.js";import{a as Pe,b as Re,c as we,d as xe,e as $e,f as ve,g as Ee,h as Ke}from"./chunk-FQHALFRR.js";import{b as qe,c as Ye,d as Xe,e as Ze,f as Qe,h as et,j as tt}from"./chunk-64TVBQFR.js";import{a as _e,b as j,c as L,d as D,e as Ge,f as We,g as O,h as A,i as U,j as V,k as H,l as M}from"./chunk-W6T7MOKY.js";import{a as ze}from"./chunk-FUUTGGJS.js";import{a as ft}from"./chunk-ODIECDN7.js";import{VersionOperator as go}from"@kanonak-protocol/types/document/models/enums";import{existsSync as wr,readFileSync as xr}from"fs";import{homedir as $r}from"os";import{join as vr}from"path";import{execFile as sr}from"child_process";import{promisify as cr}from"util";var C=cr(sr),P="kanonak",R="/usr/bin/security",p=class{async get(e){let r=i(e);try{let{stdout:n}=await C(R,["find-generic-password","-s",P,"-a",r,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${r}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${r}' then 'kanonak login ${r}' to fix.`)}}catch(n){if(X(n,44))return null;throw new Error(`macOS Keychain read failed for '${r}': ${w(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,r){let n=i(e),o=JSON.stringify(r);try{await C(R,["add-generic-password","-s",P,"-a",n,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${n}': ${w(a)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
6
  On managed devices, your IT policy may block credential storage.`)}}async remove(e){let r=i(e);try{await C(R,["delete-generic-password","-s",P,"-a",r],{timeout:1e4})}catch(n){if(X(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${r}': ${w(n)}
7
7
  The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await C(R,["dump-keychain"],{timeout:1e4}),r=[],n=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${P}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&r.push(a[1]),n=!1}return r}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${w(e)}`),[]}}};function X(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}function w(t){return t instanceof Error?t.message:String(t)}import{execFile as cr}from"child_process";import{promisify as lr}from"util";var dr=lr(cr),x="kanonak:",m=class{async get(e){let r=x+i(e),n=`
8
+ `))if(o.includes(`"svce"<blob>="${P}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&r.push(a[1]),n=!1}return r}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${w(e)}`),[]}}};function X(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}function w(t){return t instanceof Error?t.message:String(t)}import{execFile as lr}from"child_process";import{promisify as dr}from"util";var ur=dr(lr),x="kanonak:",m=class{async get(e){let r=x+i(e),n=`
9
9
  ${v}
10
10
  $target = [Console]::In.ReadLine()
11
11
  $ptr = [IntPtr]::Zero
@@ -41,7 +41,7 @@ ${v}
41
41
  $target = [Console]::In.ReadLine()
42
42
  [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await $(n,r)}catch{}}async list(){let e=`
43
43
  ${v}
44
- ${ur}
44
+ ${pr}
45
45
  $prefix = [Console]::In.ReadLine()
46
46
  $count = 0
47
47
  $pCreds = [IntPtr]::Zero
@@ -56,7 +56,7 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
56
56
  }
57
57
  [CredMan]::CredFree($pCreds)
58
58
  }`;try{let{stdout:r}=await $(e,x);return r.trim().split(`
59
- `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function $(t,e){for(let r of["pwsh","powershell"])try{return await dr(r,["-NoProfile","-NonInteractive","-Command",t],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(r==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var v=`
59
+ `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function $(t,e){for(let r of["pwsh","powershell"])try{return await ur(r,["-NoProfile","-NonInteractive","-Command",t],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(r==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var v=`
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
- "@`,ur="";import{execFile as pr,spawn as mr}from"child_process";import{promisify as fr}from"util";var K=fr(pr),E="kanonak",f=class{async get(e){let r=i(e);try{let{stdout:n}=await K("secret-tool",["lookup","service",E,"publisher",r],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,r){let n=i(e),o=JSON.stringify(r);await new Promise((a,s)=>{let c=mr("secret-tool",["store","--label",`Kanonak: ${n}`,"service",E,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});c.stdin.write(o),c.stdin.end(),c.on("close",l=>{l===0?a():s(new Error(`secret-tool store exited with code ${l}`))}),c.on("error",s)})}async remove(e){let r=i(e);try{await K("secret-tool",["clear","service",E,"publisher",r],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await K("secret-tool",["search","service",E],{timeout:1e4}),r=[];for(let n of e.split(`
91
- `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&r.push(o[1].trim())}return r}catch{return[]}}};async function _(){try{return await K("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Z,mkdirSync as Q,readFileSync as ee,writeFileSync as te}from"fs";import{createCipheriv as yr,createDecipheriv as gr,randomBytes as re}from"crypto";import{homedir as hr}from"os";import{join as W,dirname as ne}from"path";var ae=W(hr(),".config","kanonak"),y=W(ae,"keyring.key"),I=W(ae,"credentials.enc"),oe="aes-256-gcm",z=32,u=12,G=16,g=class{async get(e){let r=this.loadStore(),n=i(e);return r[n]??null}async store(e,r){let n=this.loadStore(),o=i(e);n[o]=r,this.saveStore(n)}async remove(e){let r=this.loadStore(),n=i(e);delete r[n],this.saveStore(r)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Z(I))return{};try{let e=this.getOrCreateKey(),r=ee(I);if(r.length<u+G)return{};let n=r.subarray(0,u),o=r.subarray(u,u+G),a=r.subarray(u+G),s=gr(oe,e,n);s.setAuthTag(o);let c=Buffer.concat([s.update(a),s.final()]);return JSON.parse(c.toString("utf-8"))}catch{return{}}}saveStore(e){let r=this.getOrCreateKey(),n=re(u),o=yr(oe,r,n),a=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(a),o.final()]),c=o.getAuthTag(),l=Buffer.concat([n,c,s]);Q(ne(I),{recursive:!0}),te(I,l,{mode:384})}getOrCreateKey(){if(Z(y)){let r=ee(y);if(r.length!==z)throw new Error(`Credential keyring key is corrupted (expected ${z} bytes, got ${r.length}). Delete ${y} and re-authenticate.`);return r}let e=re(z);return Q(ne(y),{recursive:!0}),te(y,e,{mode:384}),e}};import{execFile as kr}from"child_process";import{promisify as br}from"util";var Sr=br(kr),ie=3e4,h=class{constructor(e){this.helperPath=e}helperPath;async get(e){let r=i(e);try{let o=(await this.runHelper("get",{publisher:r})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${r}': ${B(n)}
90
+ "@`,pr="";import{execFile as mr,spawn as fr}from"child_process";import{promisify as yr}from"util";var K=yr(mr),E="kanonak",f=class{async get(e){let r=i(e);try{let{stdout:n}=await K("secret-tool",["lookup","service",E,"publisher",r],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,r){let n=i(e),o=JSON.stringify(r);await new Promise((a,s)=>{let c=fr("secret-tool",["store","--label",`Kanonak: ${n}`,"service",E,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});c.stdin.write(o),c.stdin.end(),c.on("close",l=>{l===0?a():s(new Error(`secret-tool store exited with code ${l}`))}),c.on("error",s)})}async remove(e){let r=i(e);try{await K("secret-tool",["clear","service",E,"publisher",r],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await K("secret-tool",["search","service",E],{timeout:1e4}),r=[];for(let n of e.split(`
91
+ `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&r.push(o[1].trim())}return r}catch{return[]}}};async function _(){try{return await K("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as Z,mkdirSync as Q,readFileSync as ee,writeFileSync as te}from"fs";import{createCipheriv as gr,createDecipheriv as hr,randomBytes as re}from"crypto";import{homedir as kr}from"os";import{join as W,dirname as ne}from"path";var ae=W(kr(),".config","kanonak"),y=W(ae,"keyring.key"),I=W(ae,"credentials.enc"),oe="aes-256-gcm",z=32,u=12,G=16,g=class{async get(e){let r=this.loadStore(),n=i(e);return r[n]??null}async store(e,r){let n=this.loadStore(),o=i(e);n[o]=r,this.saveStore(n)}async remove(e){let r=this.loadStore(),n=i(e);delete r[n],this.saveStore(r)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!Z(I))return{};try{let e=this.getOrCreateKey(),r=ee(I);if(r.length<u+G)return{};let n=r.subarray(0,u),o=r.subarray(u,u+G),a=r.subarray(u+G),s=hr(oe,e,n);s.setAuthTag(o);let c=Buffer.concat([s.update(a),s.final()]);return JSON.parse(c.toString("utf-8"))}catch{return{}}}saveStore(e){let r=this.getOrCreateKey(),n=re(u),o=gr(oe,r,n),a=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(a),o.final()]),c=o.getAuthTag(),l=Buffer.concat([n,c,s]);Q(ne(I),{recursive:!0}),te(I,l,{mode:384})}getOrCreateKey(){if(Z(y)){let r=ee(y);if(r.length!==z)throw new Error(`Credential keyring key is corrupted (expected ${z} bytes, got ${r.length}). Delete ${y} and re-authenticate.`);return r}let e=re(z);return Q(ne(y),{recursive:!0}),te(y,e,{mode:384}),e}};import{execFile as br}from"child_process";import{promisify as Sr}from"util";var Cr=Sr(br),ie=3e4,h=class{constructor(e){this.helperPath=e}helperPath;async get(e){let r=i(e);try{let o=(await this.runHelper("get",{publisher:r})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${r}': ${B(n)}
92
92
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
93
93
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,r){let n=i(e);try{await this.runHelper("store",{publisher:n,credential:r})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${B(o)}
94
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let r=i(e);try{await this.runHelper("erase",{publisher:r})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${r}': ${B(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: ${B(e)}`),[]}}async runHelper(e,r){try{let{stdout:n}=await Sr(this.helperPath,[e],{...r&&{input:JSON.stringify(r)},timeout:ie});return n}catch(n){throw Cr(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Pr(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${ie/1e3}s on '${e}'.
96
- The helper may be waiting for authentication to an external vault.`):n}}};function B(t){return t instanceof Error?t.message:String(t)}function Cr(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"}function Pr(t){return t instanceof Error&&"killed"in t&&t.killed}var J=$r(xr(),".kanonak","config.json"),T=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 r=vr(e);if(r)return r;let o=await(await this.getBackend()).get(e);return!o||!S(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,r){return(await this.getBackend()).store(e,r)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Er();return e.credentialHelper?new h(e.credentialHelper):process.platform==="darwin"?new p:process.platform==="win32"?new m:await _()?new f:new g}};function vr(t){let r="KANONAK_TOKEN_"+i(t).replace(/[.\-]/g,"_").toUpperCase();return process.env[r]??null}function Er(){if(!Rr(J))return{};try{return JSON.parse(wr(J,"utf-8"))}catch(t){let e=t instanceof Error?t.message:String(t);return console.warn(` Warning: Failed to parse ${J}: ${e}
97
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Kr,createPrivateKey as Ir,generateKeyPairSync as Br,randomUUID as Tr,sign as jr}from"crypto";function ce(){let{publicKey:t,privateKey:e}=Br("ec",{namedCurve:"P-256"});return{publicKey:t.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function k(t,e,r,n,o,a){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},c={jti:Tr(),htm:r.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(c.ath=Kr("sha256").update(o).digest("base64url")),a&&(c.nonce=a),Lr(s,c,t)}function le(t){return!t||t.length===0?!1:t.some(e=>e.toUpperCase()==="ES256")}function Lr(t,e,r){let n=se(JSON.stringify(t)),o=se(JSON.stringify(e)),a=`${n}.${o}`,s=Ir({key:r,format:"jwk"}),l=jr("SHA256",Buffer.from(a),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${l}`}function se(t){return Buffer.from(t,"utf-8").toString("base64url")}function de(t){let e=new Map;return async(r,n,o="GET")=>{if(!t)return fetch(r,{method:o});let a=await t.getCredential(n);if(!a?.accessToken)return fetch(r,{method:o});b(a)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(a.dpopKeyPair){let l=e.get(n);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.Authorization=`DPoP ${a.accessToken}`,s.DPoP=d}catch(d){let Ce=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${n}': ${Ce}
98
- The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${a.accessToken}`}}else s.Authorization=`Bearer ${a.accessToken}`;let c=await fetch(r,{method:o,headers:s});if(c.status===401&&a.dpopKeyPair){let l=c.headers.get("DPoP-Nonce");if(l){e.set(n,l);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.DPoP=d,c=await fetch(r,{method:o,headers:s})}catch{}}}return c}}import{readFileSync as Fr,writeFileSync as Dr,existsSync as Nr}from"fs";import{createHash as Or}from"crypto";import ue from"js-yaml";var pe="kanonak.lock",Ar=`# This file is generated by Kanonak CLI. Do not edit manually.
99
- `;function me(t=pe){if(!Nr(t))return null;let e=Fr(t,"utf-8"),r=ue.load(e);return!r||typeof r!="object"||r.version!=="1"?null:{version:"1",lastUpdated:r.lastUpdated??new Date().toISOString(),packages:r.packages??{}}}function fe(t,e=pe){t.lastUpdated=new Date().toISOString();let r={};for(let o of Object.keys(t.packages).sort())r[o]=t.packages[o];t.packages=r;let n=ue.dump(t,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Dr(e,Ar+n,"utf-8")}function ye(t){return`sha256:${Or("sha256").update(t).digest("hex")}`}import{createHash as Ur}from"crypto";function q(t){let e=[];for(let n of t)n instanceof L&&e.push(Vr(n));return e.sort((n,o)=>n.uri<o.uri?-1:n.uri>o.uri?1:0),JSON.stringify({subjects:e})}function ge(t){let e=q(t);return`sha256:${Ur("sha256").update(e,"utf8").digest("hex")}`}function Vr(t){let e=Wr(t),r=Y(t.statement);return{uri:e,statements:r}}function Y(t){let e=[];for(let r of t){let n=Hr(r);n&&e.push(n)}return e.sort((r,n)=>r.predicate<n.predicate?-1:r.predicate>n.predicate?1:0),e}function Hr(t){let e=Gr(t);if(!e)return;let r=Mr(t);if(r)return zr(e,r)}function Mr(t){if(t instanceof O)return{type:"string",value:t.object};if(t instanceof A)return{type:"number",value:Se(t.object)};if(t instanceof U)return{type:"boolean",value:t.object};if(t instanceof V)return{type:"ref",value:ke(t.object)};if(t instanceof H){let e=t.object;return he(e)}if(t instanceof M)return{type:"list",items:t.object.map(_r)}}function he(t){let e=Y(t.statement);return t.name&&t.name.length>0?{type:"embedded",name:t.name,statements:e}:{type:"embedded",statements:e}}function _r(t){if(t instanceof D)return{type:"ref",value:ke(t)};if(t instanceof F)return he(t);if(t instanceof N){let e=t.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:Se(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(t instanceof j)return{type:"embedded",statements:Y(t.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${t.constructor?.name??typeof t}); add canonicalization support before hashing data that contains it`)}function zr(t,e){switch(e.type){case"string":return{predicate:t,type:"string",value:e.value};case"number":return{predicate:t,type:"number",value:e.value};case"boolean":return{predicate:t,type:"boolean",value:e.value};case"ref":return{predicate:t,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:t,type:"embedded",name:e.name,statements:e.statements}:{predicate:t,type:"embedded",statements:e.statements};case"list":return{predicate:t,type:"list",items:e.items}}}function Gr(t){let e=t.predicate;if(e)return be(e.subject)}function Wr(t){let e=t.namespace??"",r=t.name??"";return`${e}/${r}`}function ke(t){return be(t.subject)}function be(t){let e=t.version;return e&&typeof e.major=="number"?`${t.publisher}/${t.package_}@${e.major}.${e.minor}.${e.patch}/${t.name}`:`${t.publisher}/${t.package_}/${t.name}`}function Se(t){if(Number.isNaN(t))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(t))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(t,-0)?"0":String(t)}export{Jt as AmbiguousReferenceRule,U as BooleanStatement,er as ClassDefinitionRule,At as ClassHierarchyCycleRule,Le as CompositeKanonakDocumentRepository,T as CredentialStore,j as DefinedKanonak,Gt as DefinitionPropertyReferenceRule,je as DocumentLocation,it as EdgeType,F as EmbeddedKanonak,Dt as EmbeddedKanonakTypeRule,H as EmbeddedStatement,Te as FileSystemKanonakDocumentRepository,mt as GitIgnoreFilter,st as GraphBuilder,Ae as HttpKanonakDocumentRepository,Nt as ImportExistenceRule,Ie as InMemoryKanonakDocumentRepository,zt as InstancePropertyReferenceRule,Me as Kanonak,yt as KanonakDocumentPositions,nt as KanonakObjectParser,rr as KanonakObjectValidator,Be as KanonakParser,_e as KanonakUri,kt as KanonakUriBuilder,Ct as KanonakUrlResolver,et as KanonakVocabulary,M as ListStatement,N as LiteralKanonak,Ue as LocalFirstRepository,ar as LookRenderer,tr as MarkdownLinkRule,We as MarkdownStatement,_t as NamespaceImportCycleRule,Tt as NamespacePrefixRule,at as NodeType,A as NumberStatement,dt as OWL_RL_CLASSIFICATION_RULES,Yt as ObjectPropertyImportRule,Xt as ObjectPropertyValueValidationRule,Kt as OntologyValidationError,vt as OntologyValidationResult,Zt as PropertyDomainRule,Ut as PropertyHierarchyCycleRule,ft as PropertyMetadata,qt as PropertyRangeReferenceRule,Vt as PropertyRangeRequiredRule,Lt as PropertyTypeSpecificityRule,Qt as PropertyValueTypeRule,Ne as PublisherConfigResolver,Oe as PublisherIndex,lt as RDFS_RULES,pt as Reasoner,ut as ReasoningResult,D as ReferenceKanonak,V as ReferenceStatement,De as RepositoryFactory,jt as ResourceNamingRule,Je as ResourceResolver,ot as ResourceTypeClassifier,Ge as ScalarStatement,ze as Statement,O as StringStatement,Ht as SubClassOfReferenceRule,Mt as SubPropertyOfReferenceRule,L as SubjectKanonak,Ft as SubjectKanonakTypeRequiredRule,ct as TripleStore,qe as TypeResolver,Ot as UnresolvedReferenceRule,Bt as ValidationCache,It as ValidationContext,Et as ValidationSeverity,yo as VersionOperator,Wt as XsdImportRule,He as buildLocalFirstRepository,q as canonicalForm,ge as canonicalHash,Ve as collectKanonakFiles,Pe as compareVersions,ye as computeIntegrity,xt as contextTypesOf,de as createAuthenticatedFetch,k as createDPoPProof,xe as createVersion,rt as extractMarkdownLinks,nr as findDerivation,$t as findInstancesByType,tt as findMalformedReferences,ht as findMarkdownLinkAt,St as formatKanonakAddress,we as formatVersion,ce as generateDPoPKeyPair,Fe as getGlobalCachePath,S as hasValidToken,ve as isCompatibleVersion,b as isExpired,Ee as isMajorCompatible,me as loadLockFile,Xe as makeUriKey,i as normalizeHost,bt as parseKanonakAddress,$e as parseVersionString,gt as parseWithPositions,Ke as pickHighestDocument,Rt as propertiesInScope,or as resolveDisplayValue,wt as resolvePropertyStep,fe as saveLockFile,le as serverSupportsDPoP,Pt as subjectUri,Ze as tripleKey,Ye as uriKey,Qe as uriTriple,Re as versionsEqual};
94
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let r=i(e);try{await this.runHelper("erase",{publisher:r})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${r}': ${B(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: ${B(e)}`),[]}}async runHelper(e,r){try{let{stdout:n}=await Cr(this.helperPath,[e],{...r&&{input:JSON.stringify(r)},timeout:ie});return n}catch(n){throw Pr(n)?new Error(`Credential helper not found at '${this.helperPath}'.
95
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Rr(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${ie/1e3}s on '${e}'.
96
+ The helper may be waiting for authentication to an external vault.`):n}}};function B(t){return t instanceof Error?t.message:String(t)}function Pr(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"}function Rr(t){return t instanceof Error&&"killed"in t&&t.killed}var J=vr($r(),".kanonak","config.json"),T=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 r=Er(e);if(r)return r;let o=await(await this.getBackend()).get(e);return!o||!S(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,r){return(await this.getBackend()).store(e,r)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Kr();return e.credentialHelper?new h(e.credentialHelper):process.platform==="darwin"?new p:process.platform==="win32"?new m:await _()?new f:new g}};function Er(t){let r="KANONAK_TOKEN_"+i(t).replace(/[.\-]/g,"_").toUpperCase();return process.env[r]??null}function Kr(){if(!wr(J))return{};try{return JSON.parse(xr(J,"utf-8"))}catch(t){let e=t instanceof Error?t.message:String(t);return console.warn(` Warning: Failed to parse ${J}: ${e}
97
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Ir,createPrivateKey as Br,generateKeyPairSync as Tr,randomUUID as jr,sign as Lr}from"crypto";function ce(){let{publicKey:t,privateKey:e}=Tr("ec",{namedCurve:"P-256"});return{publicKey:t.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function k(t,e,r,n,o,a){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},c={jti:jr(),htm:r.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(c.ath=Ir("sha256").update(o).digest("base64url")),a&&(c.nonce=a),Fr(s,c,t)}function le(t){return!t||t.length===0?!1:t.some(e=>e.toUpperCase()==="ES256")}function Fr(t,e,r){let n=se(JSON.stringify(t)),o=se(JSON.stringify(e)),a=`${n}.${o}`,s=Br({key:r,format:"jwk"}),l=Lr("SHA256",Buffer.from(a),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${l}`}function se(t){return Buffer.from(t,"utf-8").toString("base64url")}function de(t){let e=new Map;return async(r,n,o="GET")=>{if(!t)return fetch(r,{method:o});let a=await t.getCredential(n);if(!a?.accessToken)return fetch(r,{method:o});b(a)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(a.dpopKeyPair){let l=e.get(n);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.Authorization=`DPoP ${a.accessToken}`,s.DPoP=d}catch(d){let Ce=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${n}': ${Ce}
98
+ The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${a.accessToken}`}}else s.Authorization=`Bearer ${a.accessToken}`;let c=await fetch(r,{method:o,headers:s});if(c.status===401&&a.dpopKeyPair){let l=c.headers.get("DPoP-Nonce");if(l){e.set(n,l);try{let d=k(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,r,a.accessToken,l);s.DPoP=d,c=await fetch(r,{method:o,headers:s})}catch{}}}return c}}import{readFileSync as Dr,writeFileSync as Nr,existsSync as Or}from"fs";import{createHash as Ar}from"crypto";import ue from"js-yaml";var pe="kanonak.lock",Ur=`# This file is generated by Kanonak CLI. Do not edit manually.
99
+ `;function me(t=pe){if(!Or(t))return null;let e=Dr(t,"utf-8"),r=ue.load(e);return!r||typeof r!="object"||r.version!=="1"?null:{version:"1",lastUpdated:r.lastUpdated??new Date().toISOString(),packages:r.packages??{}}}function fe(t,e=pe){t.lastUpdated=new Date().toISOString();let r={};for(let o of Object.keys(t.packages).sort())r[o]=t.packages[o];t.packages=r;let n=ue.dump(t,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Nr(e,Ur+n,"utf-8")}function ye(t){return`sha256:${Ar("sha256").update(t).digest("hex")}`}import{createHash as Vr}from"crypto";function q(t){let e=[];for(let n of t)n instanceof L&&e.push(Hr(n));return e.sort((n,o)=>n.uri<o.uri?-1:n.uri>o.uri?1:0),JSON.stringify({subjects:e})}function ge(t){let e=q(t);return`sha256:${Vr("sha256").update(e,"utf8").digest("hex")}`}function Hr(t){let e=Jr(t),r=Y(t.statement);return{uri:e,statements:r}}function Y(t){let e=[];for(let r of t){let n=Mr(r);n&&e.push(n)}return e.sort((r,n)=>r.predicate<n.predicate?-1:r.predicate>n.predicate?1:0),e}function Mr(t){let e=Wr(t);if(!e)return;let r=_r(t);if(r)return Gr(e,r)}function _r(t){if(t instanceof O)return{type:"string",value:t.object};if(t instanceof A)return{type:"number",value:Se(t.object)};if(t instanceof U)return{type:"boolean",value:t.object};if(t instanceof V)return{type:"ref",value:ke(t.object)};if(t instanceof H){let e=t.object;return he(e)}if(t instanceof M)return{type:"list",items:t.object.map(zr)}}function he(t){let e=Y(t.statement);return t.name&&t.name.length>0?{type:"embedded",name:t.name,statements:e}:{type:"embedded",statements:e}}function zr(t){if(t instanceof D)return{type:"ref",value:ke(t)};if(t instanceof F)return he(t);if(t instanceof N){let e=t.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:Se(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(t instanceof j)return{type:"embedded",statements:Y(t.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${t.constructor?.name??typeof t}); add canonicalization support before hashing data that contains it`)}function Gr(t,e){switch(e.type){case"string":return{predicate:t,type:"string",value:e.value};case"number":return{predicate:t,type:"number",value:e.value};case"boolean":return{predicate:t,type:"boolean",value:e.value};case"ref":return{predicate:t,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:t,type:"embedded",name:e.name,statements:e.statements}:{predicate:t,type:"embedded",statements:e.statements};case"list":return{predicate:t,type:"list",items:e.items}}}function Wr(t){let e=t.predicate;if(e)return be(e.subject)}function Jr(t){let e=t.namespace??"",r=t.name??"";return`${e}/${r}`}function ke(t){return be(t.subject)}function be(t){let e=t.version;return e&&typeof e.major=="number"?`${t.publisher}/${t.package_}@${e.major}.${e.minor}.${e.patch}/${t.name}`:`${t.publisher}/${t.package_}/${t.name}`}function Se(t){if(Number.isNaN(t))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(t))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(t,-0)?"0":String(t)}export{qt as AmbiguousReferenceRule,U as BooleanStatement,tr as ClassDefinitionRule,Ut as ClassHierarchyCycleRule,Le as CompositeKanonakDocumentRepository,T as CredentialStore,j as DefinedKanonak,Wt as DefinitionPropertyReferenceRule,je as DocumentLocation,st as EdgeType,F as EmbeddedKanonak,Nt as EmbeddedKanonakTypeRule,H as EmbeddedStatement,Te as FileSystemKanonakDocumentRepository,ft as GitIgnoreFilter,ct as GraphBuilder,Ue as HttpKanonakDocumentRepository,Ot as ImportExistenceRule,Ie as InMemoryKanonakDocumentRepository,Gt as InstancePropertyReferenceRule,_e as Kanonak,gt as KanonakDocumentPositions,ot as KanonakObjectParser,nr as KanonakObjectValidator,Be as KanonakParser,ze as KanonakUri,bt as KanonakUriBuilder,Pt as KanonakUrlResolver,tt as KanonakVocabulary,M as ListStatement,N as LiteralKanonak,Ve as LocalFirstRepository,ir as LookRenderer,rr as MarkdownLinkRule,Je as MarkdownStatement,zt as NamespaceImportCycleRule,jt as NamespacePrefixRule,it as NodeType,A as NumberStatement,ut as OWL_RL_CLASSIFICATION_RULES,Xt as ObjectPropertyImportRule,Zt as ObjectPropertyValueValidationRule,It as OntologyValidationError,Et as OntologyValidationResult,Qt as PropertyDomainRule,Vt as PropertyHierarchyCycleRule,yt as PropertyMetadata,Yt as PropertyRangeReferenceRule,Ht as PropertyRangeRequiredRule,Ft as PropertyTypeSpecificityRule,er as PropertyValueTypeRule,Ne as PublisherConfigResolver,Oe as PublisherIndex,dt as RDFS_RULES,mt as Reasoner,pt as ReasoningResult,D as ReferenceKanonak,V as ReferenceStatement,De as RepositoryFactory,Lt as ResourceNamingRule,qe as ResourceResolver,at as ResourceTypeClassifier,We as ScalarStatement,Ge as Statement,O as StringStatement,Mt as SubClassOfReferenceRule,_t as SubPropertyOfReferenceRule,L as SubjectKanonak,Dt as SubjectKanonakTypeRequiredRule,lt as TripleStore,Ye as TypeResolver,At as UnresolvedReferenceRule,Tt as ValidationCache,Bt as ValidationContext,Kt as ValidationSeverity,go as VersionOperator,Jt as XsdImportRule,Ae as assertPackageIdentity,Me as buildLocalFirstRepository,q as canonicalForm,ge as canonicalHash,He as collectKanonakFiles,Pe as compareVersions,ye as computeIntegrity,$t as contextTypesOf,de as createAuthenticatedFetch,k as createDPoPProof,xe as createVersion,nt as extractMarkdownLinks,or as findDerivation,vt as findInstancesByType,rt as findMalformedReferences,kt as findMarkdownLinkAt,Ct as formatKanonakAddress,we as formatVersion,ce as generateDPoPKeyPair,Fe as getGlobalCachePath,S as hasValidToken,ve as isCompatibleVersion,b as isExpired,Ee as isMajorCompatible,me as loadLockFile,Ze as makeUriKey,i as normalizeHost,St as parseKanonakAddress,$e as parseVersionString,ht as parseWithPositions,Ke as pickHighestDocument,wt as propertiesInScope,ar as resolveDisplayValue,xt as resolvePropertyStep,fe as saveLockFile,le as serverSupportsDPoP,Rt as subjectUri,Qe as tripleKey,Xe as uriKey,et as uriTriple,Re as versionsEqual};
@@ -1 +1 @@
1
- import{a as o,c as e,d as r,e as n}from"../chunk-6SGRDFL5.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{a as o,c as e,d as r,e as n}from"../chunk-4FZUKBBE.js";import"../chunk-SC5M74NM.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-MYPKSBTP.js";import{a,b as g,c as h,d as i,e as j}from"../chunk-6SGRDFL5.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-7RAM5KZZ.js";import{a,b as g,c as h,d as i,e as j}from"../chunk-4FZUKBBE.js";import"../chunk-SC5M74NM.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
@@ -0,0 +1,10 @@
1
+ import type { KanonakDocument } from '@kanonak-protocol/types/document/models';
2
+ /**
3
+ * Verify that a fetched/cached document actually declares the package identity
4
+ * it was requested under — "what you got is what you asked for." A publisher's
5
+ * `package` URL serving the wrong file, a misconfigured CDN, or a tampered
6
+ * source could otherwise be cached/locked under the requested identity with
7
+ * mismatched content (namespace confusion). Throws (fail visibly) on any
8
+ * publisher / package / version mismatch; never silently accepts.
9
+ */
10
+ export declare function assertPackageIdentity(doc: KanonakDocument, publisher: string, packageName: string, version: string): void;
@@ -1,5 +1,6 @@
1
1
  export { ResourceResolver } from './ResourceResolver.js';
2
2
  export type { ILogger } from './ResourceResolver.js';
3
+ export { assertPackageIdentity } from './assertPackageIdentity.js';
3
4
  export { KanonakUri } from './KanonakUri.js';
4
5
  export { KanonakUriBuilder } from './KanonakUriBuilder.js';
5
6
  export { parseKanonakAddress, formatKanonakAddress, } from './KanonakAddress.js';
@@ -1 +1 @@
1
- import{a as m,b as u}from"../chunk-DC774EQL.js";import{a as p}from"../chunk-NIGFQYVA.js";import{a as l,b as n,c as o,d as q,e as r,f as s,g as t}from"../chunk-N224PFBI.js";import"../chunk-Q4DKP5DO.js";import{a,b,c,d,e,f,g,h}from"../chunk-FQHALFRR.js";import{b as j,c as k}from"../chunk-64TVBQFR.js";import"../chunk-W6T7MOKY.js";import{a as i}from"../chunk-FUUTGGJS.js";export{i as KanonakUri,m as KanonakUriBuilder,p as KanonakUrlResolver,j as ResourceResolver,l as ResourceTypeClassifier,k as TypeResolver,a as compareVersions,t as contextTypesOf,d as createVersion,u as findInstancesByType,o as formatKanonakAddress,c as formatVersion,f as isCompatibleVersion,g as isMajorCompatible,n as parseKanonakAddress,e as parseVersionString,h as pickHighestDocument,r as propertiesInScope,s as resolvePropertyStep,q as subjectUri,b as versionsEqual};
1
+ import{a as n,b as v}from"../chunk-PEUTCG3B.js";import{a as q}from"../chunk-NIGFQYVA.js";import{a as i}from"../chunk-SC5M74NM.js";import{a as m,b as o,c as p,d as r,e as s,f as t,g as u}from"../chunk-N224PFBI.js";import"../chunk-Q4DKP5DO.js";import{a,b,c,d,e,f,g,h}from"../chunk-FQHALFRR.js";import{b as k,c as l}from"../chunk-64TVBQFR.js";import"../chunk-W6T7MOKY.js";import{a as j}from"../chunk-FUUTGGJS.js";export{j as KanonakUri,n as KanonakUriBuilder,q as KanonakUrlResolver,k as ResourceResolver,m as ResourceTypeClassifier,l as TypeResolver,i as assertPackageIdentity,a as compareVersions,u as contextTypesOf,d as createVersion,v as findInstancesByType,p as formatKanonakAddress,c as formatVersion,f as isCompatibleVersion,g as isMajorCompatible,o as parseKanonakAddress,e as parseVersionString,h as pickHighestDocument,s as propertiesInScope,t as resolvePropertyStep,r as subjectUri,b as versionsEqual};
@@ -1,4 +1,4 @@
1
- import{a as p}from"../chunk-ESYVKB25.js";import"../chunk-3NEUHF7E.js";import"../chunk-DC774EQL.js";import"../chunk-NIGFQYVA.js";import"../chunk-H2LEQLVD.js";import{d as m,g as x}from"../chunk-N224PFBI.js";import{a as d,f as S}from"../chunk-Q4DKP5DO.js";import{a as v}from"../chunk-FQHALFRR.js";import"../chunk-64TVBQFR.js";import{c as j}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{homedir as P}from"os";import{join as k}from"path";import{existsSync as B,mkdirSync as C,readFileSync as D,writeFileSync as O}from"fs";import{createHash as z}from"crypto";var f="Xenova/all-MiniLM-L6-v2",w="q8",b=32,g=null;async function K(){return g||(g=(async()=>{let t;try{t=await import("@huggingface/transformers")}catch(i){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import{a as p}from"../chunk-ESYVKB25.js";import"../chunk-3NEUHF7E.js";import"../chunk-PEUTCG3B.js";import"../chunk-NIGFQYVA.js";import"../chunk-SC5M74NM.js";import"../chunk-H2LEQLVD.js";import{d as m,g as x}from"../chunk-N224PFBI.js";import{a as d,f as S}from"../chunk-Q4DKP5DO.js";import{a as v}from"../chunk-FQHALFRR.js";import"../chunk-64TVBQFR.js";import{c as j}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{homedir as P}from"os";import{join as k}from"path";import{existsSync as B,mkdirSync as C,readFileSync as D,writeFileSync as O}from"fs";import{createHash as z}from"crypto";var f="Xenova/all-MiniLM-L6-v2",w="q8",b=32,g=null;async function K(){return g||(g=(async()=>{let t;try{t=await import("@huggingface/transformers")}catch(i){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
2
2
  Install it with:
3
3
  npm install @huggingface/transformers
4
4
  (underlying import error: ${i.message})`)}let{pipeline:r,env:n}=t;n.cacheDir=k(P(),".kanonak","models");let e=await r("feature-extraction",f,{dtype:w});return async i=>(await e(i,{pooling:"mean",normalize:!0})).tolist()})()),g}function H(t,r){let n=0;for(let e=0;e<t.length;e++)n+=t[e]*r[e];return n}function U(t,r){return r?t.version?r.version?v(t.version,r.version)>0:!0:!1:!0}function F(t,r){let n=p(t,r),e=[n.label],i=x(r);if(i.length>0){let s=S(t,i[0]),c=s?p(t,s).label:i[0].name;c&&e.push(`\u2014 a ${c}.`)}return n.summary&&e.push(n.summary),e.join(" ")}function M(t){let r=new Map;for(let n of t){if(!(n instanceof j))continue;let e=m(n);if(!e)continue;let i=d(e),s=r.get(i);(!s||U(e,m(s)))&&r.set(i,n)}return[...r.values()].sort((n,e)=>{let i=m(n)?d(m(n)):n.name,s=m(e)?d(m(e)):e.name;return i.localeCompare(s)})}var y=class{entries=[];get size(){return this.entries.length}async build(r,n={}){let e=M(r);if(n.include&&(e=e.filter(n.include)),e.length===0)return this.entries=[],{size:0,cached:!1};let i=e.map(o=>F(r,o)),s=n.cacheDir,c;if(s){let o=z("sha256").update(f+"|"+w+`
@@ -1,3 +1,3 @@
1
- import{c as z}from"../chunk-ESYVKB25.js";import"../chunk-3NEUHF7E.js";import{a as W,d as _,f as U,g as G}from"../chunk-MYPKSBTP.js";import{a as L,b as B,d as H,e as T}from"../chunk-6SGRDFL5.js";import{a as J}from"../chunk-NIGFQYVA.js";import{c as q}from"../chunk-VJT6YUWK.js";import"../chunk-H2LEQLVD.js";import{a as O}from"../chunk-7CUTGGH3.js";import"../chunk-Q4DKP5DO.js";import{a as P,e as E}from"../chunk-FQHALFRR.js";import"../chunk-64TVBQFR.js";import{c as Y}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{readFileSync as ne,existsSync as te,readdirSync as re,writeFileSync as oe,mkdirSync as se}from"fs";import{join as C}from"path";function Q(o){let e=o.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function V(o,e){let t=new Set,r=[...o];for(;r.length>0;){let s=r.shift(),d=Q(s);if(!d||t.has(d))continue;t.add(d);let m=s.metadata?.imports;if(m)for(let[u,w]of Object.entries(m))for(let b of w)try{let i=await e.getHighestCompatibleVersionAsync(u,b);i&&r.push(i)}catch{}}return t}var $=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=Q(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var X=["core-kanonak","site","link","look-tokens","look-styles","look","universal-look"];async function ie(o,e={}){let t=new O,r=new L(t),s=[],d=[];for(let n of G(o)){let p;try{p=ne(n,"utf-8")}catch{continue}let a;try{a=t.parse(p).metadata?.namespace_}catch{continue}if(!a?.version)continue;let k=a.version;d.push({publisher:a.publisher,package_:a.package_,verStr:`${k.major}.${k.minor}.${k.patch}`,version:k,source:p})}d.sort((n,p)=>P(p.version,n.version));for(let n of d)await r.saveDocumentAsync(t.parse(n.source),`${n.publisher}/${n.package_}@${n.verStr}`),s.push({publisher:n.publisher,package_:n.package_,verStr:n.verStr,source:n.source});let m=[...new Set(s.map(n=>n.publisher))].sort(),u=e.publisher;if(u){if(!m.includes(u))throw new Error(`Publisher "${u}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)u=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${o}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let w=new Set,b=new Map;for(let n of s)n.publisher===u&&(w.add(`${n.publisher}/${n.package_}@${n.verStr}`),b.set(`${n.package_}@${n.verStr}`,n.source));let i=new W(_(),!0,t),c=e.repository??new U(r,i,new T(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0));if(!e.repository){let n=_(),p=h=>C(n,h),a=h=>{let v=p(h);return te(v)?new Set(re(v).filter(K=>K.endsWith(".kan.yml")).map(K=>K.split("@")[0])):new Set},k=h=>s.some(v=>v.publisher==="kanonak.org"&&v.package_===h),R=new H,x=a("kanonak.org");for(let h of X)if(!(x.has(h)||k(h)))try{let v=await R.getHighestVersion("kanonak.org",h);if(!v)continue;let K=await R.getPackageUrl("kanonak.org",h,v),I=await fetch(K);if(!I.ok)continue;let ee=await I.text(),F=C(n,"kanonak.org");se(F,{recursive:!0}),oe(C(F,`${h}@${v}.kan.yml`),ee,"utf-8")}catch{}}let l=c;if(!e.repository){let n=(await r.getAllDocumentsAsync()).filter(a=>a.metadata.namespace_?.publisher===u),p=await V(n,c);for(let a of X)p.add(`kanonak.org/${a}`);l=new $(c,p)}let y=await new q(t).parseKanonaks(l),D=new z(y),j=new Map,A=new Map,N=new Map,M=new Set;for(let n of y){if(!(n instanceof Y))continue;let p=n.namespace||"";if(!w.has(p))continue;j.set(`${p}/${n.name}`,n);let a=p.split("/")[1]??"",[k,R]=a.split("@");if(!k||!R)continue;let x=E(R);x&&(M.has(a)||(M.add(a),A.has(k)||A.set(k,[]),A.get(k).push({verStr:R,version:x})),n.name===k&&N.set(a,n))}for(let n of A.values())n.sort((p,a)=>P(a.version,p.version));return{publisher:u,availablePublishers:m,catalog:y,lookRenderer:D,localNamespaces:w,rawByNsKey:b,bySubject:j,pkgVersions:A,pkgSelfByVer:N}}var g={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},f=(o,e,t,r)=>({status:o,headers:{"Content-Type":e,...r||{}},body:t}),S=o=>f(404,g[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${o}</p>`),ce=o=>({status:301,headers:{Location:o},body:""});function Z(o,e,t){let r=o.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(s=>s.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(s=>s.version.major===t.major&&s.version.minor===t.minor)?.verStr??null;case"exact":return r.find(s=>s.version.major===t.major&&s.version.minor===t.minor&&s.version.patch===t.patch)?.verStr??null;default:return null}}function ae(o,e,t=""){let{lookRenderer:r,publisher:s}=o;if(e==="/.well-known/kanonak.json")return f(200,g[".json"],JSON.stringify(B(s),null,2));if(e==="/index.txt"){let c=[...o.localNamespaces].map(l=>l.split("/")[1].replace("@","/")).sort();return f(200,g[".txt"],c.join(`
1
+ import{c as z}from"../chunk-ESYVKB25.js";import"../chunk-3NEUHF7E.js";import{a as W,d as _,f as U,g as G}from"../chunk-7RAM5KZZ.js";import{a as L,b as B,d as H,e as T}from"../chunk-4FZUKBBE.js";import{a as J}from"../chunk-NIGFQYVA.js";import"../chunk-SC5M74NM.js";import{c as q}from"../chunk-VJT6YUWK.js";import"../chunk-H2LEQLVD.js";import{a as O}from"../chunk-7CUTGGH3.js";import"../chunk-Q4DKP5DO.js";import{a as P,e as E}from"../chunk-FQHALFRR.js";import"../chunk-64TVBQFR.js";import{c as Y}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{readFileSync as ne,existsSync as te,readdirSync as re,writeFileSync as oe,mkdirSync as se}from"fs";import{join as C}from"path";function Q(o){let e=o.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function V(o,e){let t=new Set,r=[...o];for(;r.length>0;){let s=r.shift(),d=Q(s);if(!d||t.has(d))continue;t.add(d);let m=s.metadata?.imports;if(m)for(let[u,w]of Object.entries(m))for(let b of w)try{let i=await e.getHighestCompatibleVersionAsync(u,b);i&&r.push(i)}catch{}}return t}var $=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=Q(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var X=["core-kanonak","site","link","look-tokens","look-styles","look","universal-look"];async function ie(o,e={}){let t=new O,r=new L(t),s=[],d=[];for(let n of G(o)){let p;try{p=ne(n,"utf-8")}catch{continue}let a;try{a=t.parse(p).metadata?.namespace_}catch{continue}if(!a?.version)continue;let k=a.version;d.push({publisher:a.publisher,package_:a.package_,verStr:`${k.major}.${k.minor}.${k.patch}`,version:k,source:p})}d.sort((n,p)=>P(p.version,n.version));for(let n of d)await r.saveDocumentAsync(t.parse(n.source),`${n.publisher}/${n.package_}@${n.verStr}`),s.push({publisher:n.publisher,package_:n.package_,verStr:n.verStr,source:n.source});let m=[...new Set(s.map(n=>n.publisher))].sort(),u=e.publisher;if(u){if(!m.includes(u))throw new Error(`Publisher "${u}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)u=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${o}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let w=new Set,b=new Map;for(let n of s)n.publisher===u&&(w.add(`${n.publisher}/${n.package_}@${n.verStr}`),b.set(`${n.package_}@${n.verStr}`,n.source));let i=new W(_(),!0,t),c=e.repository??new U(r,i,new T(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0));if(!e.repository){let n=_(),p=h=>C(n,h),a=h=>{let v=p(h);return te(v)?new Set(re(v).filter(K=>K.endsWith(".kan.yml")).map(K=>K.split("@")[0])):new Set},k=h=>s.some(v=>v.publisher==="kanonak.org"&&v.package_===h),R=new H,x=a("kanonak.org");for(let h of X)if(!(x.has(h)||k(h)))try{let v=await R.getHighestVersion("kanonak.org",h);if(!v)continue;let K=await R.getPackageUrl("kanonak.org",h,v),I=await fetch(K);if(!I.ok)continue;let ee=await I.text(),F=C(n,"kanonak.org");se(F,{recursive:!0}),oe(C(F,`${h}@${v}.kan.yml`),ee,"utf-8")}catch{}}let l=c;if(!e.repository){let n=(await r.getAllDocumentsAsync()).filter(a=>a.metadata.namespace_?.publisher===u),p=await V(n,c);for(let a of X)p.add(`kanonak.org/${a}`);l=new $(c,p)}let y=await new q(t).parseKanonaks(l),D=new z(y),j=new Map,A=new Map,N=new Map,M=new Set;for(let n of y){if(!(n instanceof Y))continue;let p=n.namespace||"";if(!w.has(p))continue;j.set(`${p}/${n.name}`,n);let a=p.split("/")[1]??"",[k,R]=a.split("@");if(!k||!R)continue;let x=E(R);x&&(M.has(a)||(M.add(a),A.has(k)||A.set(k,[]),A.get(k).push({verStr:R,version:x})),n.name===k&&N.set(a,n))}for(let n of A.values())n.sort((p,a)=>P(a.version,p.version));return{publisher:u,availablePublishers:m,catalog:y,lookRenderer:D,localNamespaces:w,rawByNsKey:b,bySubject:j,pkgVersions:A,pkgSelfByVer:N}}var g={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},f=(o,e,t,r)=>({status:o,headers:{"Content-Type":e,...r||{}},body:t}),S=o=>f(404,g[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${o}</p>`),ce=o=>({status:301,headers:{Location:o},body:""});function Z(o,e,t){let r=o.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(s=>s.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(s=>s.version.major===t.major&&s.version.minor===t.minor)?.verStr??null;case"exact":return r.find(s=>s.version.major===t.major&&s.version.minor===t.minor&&s.version.patch===t.patch)?.verStr??null;default:return null}}function ae(o,e,t=""){let{lookRenderer:r,publisher:s}=o;if(e==="/.well-known/kanonak.json")return f(200,g[".json"],JSON.stringify(B(s),null,2));if(e==="/index.txt"){let c=[...o.localNamespaces].map(l=>l.split("/")[1].replace("@","/")).sort();return f(200,g[".txt"],c.join(`
2
2
  `)+`
3
3
  `)}if(e==="/"||e==="/index.html"||e==="/index.css"){let c=r.publisherSubject(s);return e==="/index.css"?f(200,g[".css"],r.renderStylesheet(c)):f(200,g[".html"],r.renderDocument(c,{rootIndex:!0}))}let d=".html",m=!1,u=e;for(let c of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(c)){d=c,m=!0,u=e.slice(0,-c.length);break}let w=!m&&/application\/yaml|text\/yaml/i.test(t),b=u.endsWith("/");b&&u!=="/"&&(u=u.slice(0,-1));let i=J.parse(u,s);if(!i)return S(e);if(i.kind==="package"){let c=Z(o,i.package_,i.versionSpec);if(!c)return S(e);if(d===".kan.yml"||w){let D=o.rawByNsKey.get(`${i.package_}@${c}`);return D!==void 0?f(200,g[".kan.yml"],D):S(e)}let l=o.pkgSelfByVer.get(`${i.package_}@${c}`);if(!l)return S(e);if(d===".css")return f(200,g[".css"],r.renderStylesheet(l));if(!b)return ce(u+"/");let y=i.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(l)){let D=(o.pkgVersions.get(i.package_)||[]).map(j=>j.verStr);return f(200,g[".html"],r.renderPackageVersionList(i.package_,D,l))}return f(200,g[".html"],r.renderDocument(l,y?{bareOverview:!0}:void 0))}if(i.kind==="resource"){let c=Z(o,i.package_,i.versionSpec);if(!c)return S(e);let l=o.bySubject.get(`${s}/${i.package_}@${c}/${i.name}`);if(!l)return S(e);switch(d){case".css":return f(200,g[".css"],r.renderStylesheet(l));case".svg":return f(200,g[".svg"],r.renderSvg(l));case".md":{let y=r.renderRawMarkdown(l);return y===void 0?S(e):f(200,g[".md"],y)}default:return f(200,g[".html"],r.renderDocument(l))}}return S(e)}export{$ as ClosureScopedRepository,V as deriveImportClosure,ie as loadServerModel,ae as route};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "3.58.0",
3
+ "version": "3.59.0",
4
4
  "description": "Kanonak Protocol SDK - Document repository and parsing implementations for TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -121,7 +121,7 @@
121
121
  "yaml-parser"
122
122
  ],
123
123
  "dependencies": {
124
- "@kanonak-protocol/types": "^3.58.0",
124
+ "@kanonak-protocol/types": "^3.59.0",
125
125
  "ignore": "^7.0.5",
126
126
  "js-yaml": "^4.1.0",
127
127
  "yaml": "^2.7.0"
@@ -1,2 +0,0 @@
1
- import{a as k}from"./chunk-7CUTGGH3.js";import{a as h,b as d,f as y,g as v}from"./chunk-FQHALFRR.js";var P=class{documents=new Map;documentContents=new Map;parser;constructor(t){this.parser=t}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){let s=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===t&&n.metadata?.namespace_?.package_===e&&s.push(n);return s}async getHighestCompatibleVersionAsync(t,e){let s=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e.packageName&&r.metadata?.namespace_?.version!==void 0&&s.push(r);if(s.length===0)return null;let n=s.filter(r=>{let a=r.metadata.namespace_.version;if(!a)return!1;switch(e.versionOperator){case 0:return d(a,e.version);case 1:return y(a,e.version);case 2:return v(a,e.version);case 3:return h(a,e.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((r,a)=>{let o=r.metadata.namespace_.version,c=a.metadata.namespace_.version;return!o&&!c?0:o?c?h(c,o):-1:1}),n[0])}async saveDocumentAsync(t,e){this.documents.set(e,t);let s=this.parser.save(t);this.documentContents.set(e,s)}async deleteDocumentAsync(t){this.documents.delete(t),this.documentContents.delete(t)}async clearNamespaceAsync(t,e){let s=[];for(let[n,r]of this.documents.entries())r.metadata?.namespace_?.publisher===t&&r.metadata?.namespace_?.package_===e&&s.push(n);for(let n of s)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let t=[];for(let e of this.documents.values())e.metadata?.namespace_&&t.push({identifier:e.metadata.namespace_.toString(),uri:`kanonak://${e.metadata.namespace_}`,hasParseError:!1});return t}async getDocumentContentAsync(t){let e=this.documentContents.get(t);if(e!==void 0)return e;let s=this.documents.get(t);return s!==void 0?this.parser.save(s):null}async getDocumentUriAsync(t){let e=this.documents.get(t);return e?e.metadata?.namespace_?`kanonak://${e.metadata.namespace_}`:`kanonak://${t}`:null}};var w="https://{publisher}/index.txt",D="https://{publisher}/{package}/{version}.kan.yml",C={version:1};function I(i){return{version:1,index:w.replaceAll("{publisher}",i),package:D.replaceAll("{publisher}",i),auth:"none"}}var m=class{cache=new Map;getConfig(t){let e=this.cache.get(t);return e||(e=this.fetchConfig(t),this.cache.set(t,e),e.catch(()=>{this.cache.get(t)===e&&this.cache.delete(t)})),e}async fetchConfig(t){let e=`https://${t}/.well-known/kanonak.json`,s;try{s=await fetch(e)}catch{return C}if(s.status===404)return C;if(!s.ok)throw new Error(`Failed to fetch publisher config: ${e} (${s.status} ${s.statusText})`);let n=await s.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${e}: missing or invalid "version" field`);let r={version:n.version};return typeof n.index=="string"&&(r.index=n.index),typeof n.package=="string"&&(r.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(r.auth=n.auth),r}resolveIndexUrl(t,e){let s=e.index??w;return x(s,{publisher:t})}resolvePackageUrl(t,e,s,n){let r=n.package??D;return x(r,{publisher:t,package:e,version:s})}};function x(i,t){let e=i;for(let[n,r]of Object.entries(t))e=e.replaceAll(`{${n}}`,r);let s=e.match(/\{[a-z]+\}/);if(s)throw new Error(`Unresolved variable ${s[0]} in URL template: ${i}`);return e}import{VersionOperator as g}from"@kanonak-protocol/types/document/models/enums";var u=class i{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new m,this.fetchFn=t?.fetchFn}async resolveVersion(t,e){let s=await this.getPackageVersions(t,e.packageName);if(s.length===0)return null;let n=s.filter(r=>this.isVersionCompatible(r,e.version,e.versionOperator));return n.length===0?null:(n.sort((r,a)=>this.compareVersionStrings(a,r)),n[0])}async getHighestVersion(t,e){let s=await this.getPackageVersions(t,e);return s.length===0?null:[...s].sort((r,a)=>this.compareVersionStrings(a,r))[0]}async listLatestPackages(t){let e=await this.getIndex(t),s=[];for(let[n,r]of e){if(r.length===0)continue;let a=[...r].sort((o,c)=>this.compareVersionStrings(c,o));s.push({packageName:n,version:a[0]})}return s.sort((n,r)=>n.packageName.localeCompare(r.packageName)),s}async getPackageUrl(t,e,s){let n=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,e,s,n)}async getPackageVersions(t,e){return(await this.getIndex(t)).get(e)??[]}getIndex(t){let e=this.indexCache.get(t);return e||(e=this.fetchIndex(t),this.indexCache.set(t,e),e.catch(()=>{this.indexCache.get(t)===e&&this.indexCache.delete(t)})),e}async fetchIndex(t){let e=await this.configResolver.getConfig(t),s=this.configResolver.resolveIndexUrl(t,e),n=this.fetchFn?await this.fetchFn(s,t):await fetch(s);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${s} (${n.status} ${n.statusText})`);let r=await n.text();return i.parseIndex(r)}static parseIndex(t){let e=new Map;for(let s of t.split(`
2
- `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("/");if(r===-1)continue;let a=n.substring(0,r),o=n.substring(r+1);if(!a||!o)continue;let c=e.get(a);c?c.push(o):e.set(a,[o])}return e}isVersionCompatible(t,e,s){let n=i.parseVersion(t);if(!n)return!1;switch(s){case g.Any:return!0;case g.Exact:return n.major===e.major&&n.minor===e.minor&&n.patch===e.patch;case g.Compatible:return n.major===e.major&&n.minor===e.minor&&n.patch>=e.patch;case g.Major:return n.major!==e.major?!1:n.minor>e.minor?!0:n.minor===e.minor?n.patch>=e.patch:!1;default:return!1}}static parseVersion(t){let e=t.split(".");if(e.length<2)return null;let s=parseInt(e[0],10),n=parseInt(e[1],10),r=e.length>=3?parseInt(e[2],10):0;return isNaN(s)||isNaN(n)||isNaN(r)?null:{major:s,minor:n,patch:r}}compareVersionStrings(t,e){let s=i.parseVersion(t),n=i.parseVersion(e);return!s&&!n?0:s?n?s.major!==n.major?s.major-n.major:s.minor!==n.minor?s.minor-n.minor:s.patch-n.patch:1:-1}};var F=class{parser=new k;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new u({fetchFn:t.fetchFn}):new u}async getHighestCompatibleVersionAsync(t,e){let s=await this.publisherIndex.resolveVersion(t,e);if(!s)return null;let n=`${t}/${e.packageName}@${s}`,r=this.documents.get(n);if(r)return r;if(this.getFromCache){let l=this.getFromCache(t,e.packageName,s);if(l){let f=this.parser.parse(l);return this.documents.set(n,f),this.contentCache.set(n,l),f}}let a=await this.publisherIndex.getPackageUrl(t,e.packageName,s),o=this.fetchFn?await this.fetchFn(a,t):await fetch(a);if(!o.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${o.status} ${o.statusText})`);let c=await o.text();this.onFetch&&this.onFetch(t,e.packageName,s,c);let p=this.parser.parse(c);return this.documents.set(n,p),this.contentCache.set(n,c),p}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,e){return Array.from(this.documents.values()).filter(s=>{let n=s.metadata.namespace_;return n&&n.publisher===t&&n.package_===e})}async saveDocumentAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,e){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let e=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!e)return null;let[,s,n,r]=e;return this.publisherIndex.getPackageUrl(s,n,r)}};export{P as a,I as b,m as c,u as d,F as e};