@kanonak-protocol/sdk 3.57.0 → 3.58.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,b as L,c as W,d as F}from"./chunk-VHUJSHH7.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-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}
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};
@@ -1,2 +1,2 @@
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,i=a.metadata.namespace_.version;return!o&&!i?0:o?i?h(i,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",C={version:1},u=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??D;return x(s,{publisher:t})}resolvePackageUrl(t,e,s,n){let r=n.package??F;return x(r,{publisher:t,package:e,version:s})}};function x(c,t){let e=c;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: ${c}`);return e}import{VersionOperator as g}from"@kanonak-protocol/types/document/models/enums";var m=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new u,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,i)=>this.compareVersionStrings(i,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 c.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 i=e.get(a);i?i.push(o):e.set(a,[o])}return e}isVersionCompatible(t,e,s){let n=c.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=c.parseVersion(t),n=c.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 w=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 m({fetchFn:t.fetchFn}):new m}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 i=await o.text();this.onFetch&&this.onFetch(t,e.packageName,s,i);let p=this.parser.parse(i);return this.documents.set(n,p),this.contentCache.set(n,i),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,u as b,m as c,w as d};
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};
@@ -1 +1 @@
1
- import{a as w,d as A}from"./chunk-VHUJSHH7.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-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};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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-H673KOGN.js";import{a as Ie,b as Ne,c as Oe,d as Ae}from"./chunk-VHUJSHH7.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 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).
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)}
@@ -4,6 +4,23 @@ export interface PublisherConfig {
4
4
  package?: string;
5
5
  auth?: 'none' | 'oauth' | 'bearer';
6
6
  }
7
+ /**
8
+ * The explicit, self-describing config a publisher advertises at
9
+ * `.well-known/kanonak.json`. `index` and `package` are FULL URLs (publisher
10
+ * domain baked in; `{package}`/`{version}` stay as the placeholders a client
11
+ * substitutes). Encoding the actual values — rather than omitting them and
12
+ * relying on defaults — lets any consumer (AI, the universal browser, another
13
+ * publisher) see exactly where the catalog and package sources live.
14
+ *
15
+ * Why full URLs (not relative paths): the trust/control anchor is THIS file's
16
+ * location — `https://<publisher>/.well-known/kanonak.json`, which only the
17
+ * publisher can serve. So whatever it declares is the publisher's authentic,
18
+ * authorized choice, INCLUDING delegating index/package hosting to a different
19
+ * endpoint (e.g. a CDN: `https://cdn.example.com/...`). Discovery-on-own-domain
20
+ * is the proof of control; full URLs are what make delegation possible. A
21
+ * misconfigured scheme/host only breaks the publisher's own resolution.
22
+ */
23
+ export declare function defaultPublisherConfig(publisher: string): PublisherConfig;
7
24
  export declare class PublisherConfigResolver {
8
25
  private readonly cache;
9
26
  getConfig(publisher: string): Promise<PublisherConfig>;
@@ -1 +1 @@
1
- import{a as o,b as e,c as r,d as n}from"../chunk-VHUJSHH7.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-6SGRDFL5.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
@@ -6,7 +6,7 @@ export { HttpKanonakDocumentRepository } from './HttpKanonakDocumentRepository.j
6
6
  export { LocalFirstRepository } from './LocalFirstRepository.js';
7
7
  export { buildLocalFirstRepository, collectKanonakFiles, type HttpCacheHooks, } from './buildLocalFirstRepository.js';
8
8
  export { PublisherIndex } from './PublisherIndex.js';
9
- export { PublisherConfigResolver } from './PublisherConfig.js';
9
+ export { PublisherConfigResolver, defaultPublisherConfig } from './PublisherConfig.js';
10
10
  export type { PublisherConfig } from './PublisherConfig.js';
11
11
  export { getGlobalCachePath } from './CachePaths.js';
12
12
  export type { IKanonakDocumentRepository, KanonakDocument, DocumentReference } from '@kanonak-protocol/types/document/models';
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as j,g as k,h as l}from"../chunk-H673KOGN.js";import{a,b as g,c as h,d as i}from"../chunk-VHUJSHH7.js";import"../chunk-7CUTGGH3.js";import"../chunk-FQHALFRR.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,i as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,j as LocalFirstRepository,g as PublisherConfigResolver,h as PublisherIndex,f as RepositoryFactory,l as buildLocalFirstRepository,k as collectKanonakFiles,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-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};
@@ -0,0 +1,36 @@
1
+ import type { IKanonakDocumentRepository, KanonakDocument, DocumentReference, Import } from '@kanonak-protocol/types/document/models';
2
+ /**
3
+ * The transitive import closure of `seedDocs`, as a set of `publisher/package`
4
+ * keys: every package reachable by following `imports:` recursively, each import
5
+ * resolved through `repo`. This is exactly the set of packages a render needs —
6
+ * what makes a render a pure function of its seed, independent of whatever else
7
+ * happens to be in the global cache. Unresolved imports are skipped (the page
8
+ * still renders, just without that layer). Cross-publisher imports are followed
9
+ * (an import names its own publisher), so the closure can span publishers.
10
+ */
11
+ export declare function deriveImportClosure(seedDocs: KanonakDocument[], repo: IKanonakDocumentRepository): Promise<Set<string>>;
12
+ /**
13
+ * Wraps a repository so the catalog enumeration (`getAllDocumentsAsync`) yields
14
+ * ONLY documents whose `publisher/package` is in `scope` — a render's resolved
15
+ * closure (its import closure ∪ the ambient render stack). Every OTHER method
16
+ * delegates unchanged, so reference resolution during parse still sees the full
17
+ * repository. This stops a polluted global cache (stray packages from other
18
+ * workspaces' installs) from leaking into a render via the open-world merge —
19
+ * the merge only happens over the documents this method returns. See
20
+ * kanonak-protocol/typescript#42.
21
+ */
22
+ export declare class ClosureScopedRepository implements IKanonakDocumentRepository {
23
+ private readonly inner;
24
+ private readonly scope;
25
+ constructor(inner: IKanonakDocumentRepository, scope: ReadonlySet<string>);
26
+ getAllDocumentsAsync(): Promise<KanonakDocument[]>;
27
+ getDocumentAsync(identifier: string): Promise<KanonakDocument | null>;
28
+ getDocumentsByNamespaceAsync(publisher: string, package_: string): Promise<KanonakDocument[]>;
29
+ getHighestCompatibleVersionAsync(publisher: string, import_: Import): Promise<KanonakDocument | null>;
30
+ saveDocumentAsync(document: KanonakDocument, identifier: string): Promise<void>;
31
+ deleteDocumentAsync(identifier: string): Promise<void>;
32
+ clearNamespaceAsync(publisher: string, package_: string): Promise<void>;
33
+ getAllDocumentReferencesAsync(): Promise<DocumentReference[]>;
34
+ getDocumentContentAsync(identifier: string): Promise<string | null>;
35
+ getDocumentUriAsync(identifier: string): Promise<string | null>;
36
+ }
@@ -1,3 +1,4 @@
1
1
  export { loadServerModel } from './loadServerModel.js';
2
2
  export { route } from './route.js';
3
+ export { deriveImportClosure, ClosureScopedRepository } from './closure.js';
3
4
  export type { ServerModel, RouteResponse, LoadServerModelOptions, PackageVersion, } from './types.js';
@@ -1,3 +1,3 @@
1
- import{c as U}from"../chunk-ESYVKB25.js";import"../chunk-3NEUHF7E.js";import{a as O,d as M,f as I,g as B}from"../chunk-H673KOGN.js";import{a as C,c as W,d as A}from"../chunk-VHUJSHH7.js";import{a as H}from"../chunk-NIGFQYVA.js";import{c as G}from"../chunk-VJT6YUWK.js";import"../chunk-H2LEQLVD.js";import{a as L}from"../chunk-7CUTGGH3.js";import"../chunk-Q4DKP5DO.js";import{a as V,e as E}from"../chunk-FQHALFRR.js";import"../chunk-64TVBQFR.js";import{c as T}from"../chunk-W6T7MOKY.js";import"../chunk-FUUTGGJS.js";import{readFileSync as q,existsSync as z,readdirSync as Q,writeFileSync as X,mkdirSync as Z}from"fs";import{join as K}from"path";var ee=["core-kanonak","site","link","look-tokens","look-styles","look","universal-look"];async function re(t,r={}){let o=new L,n=new C(o),s=[],v=[];for(let e of B(t)){let p;try{p=q(e,"utf-8")}catch{continue}let u;try{u=o.parse(p).metadata?.namespace_}catch{continue}if(!u?.version)continue;let k=u.version;v.push({publisher:u.publisher,package_:u.package_,verStr:`${k.major}.${k.minor}.${k.patch}`,version:k,source:p})}v.sort((e,p)=>V(p.version,e.version));for(let e of v)await n.saveDocumentAsync(o.parse(e.source),`${e.publisher}/${e.package_}@${e.verStr}`),s.push({publisher:e.publisher,package_:e.package_,verStr:e.verStr,source:e.source});let h=[...new Set(s.map(e=>e.publisher))].sort(),l=r.publisher;if(l){if(!h.includes(l))throw new Error(`Publisher "${l}" not found in workspace. Available: ${h.join(", ")||"(none)"}`)}else if(h.length===1)l=h[0];else throw h.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${h.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let $=new Set,R=new Map;for(let e of s)e.publisher===l&&($.add(`${e.publisher}/${e.package_}@${e.verStr}`),R.set(`${e.package_}@${e.verStr}`,e.source));let c=new O(M(),!0,o),i=r.repository??new I(n,c,new A(r.httpCache?{getFromCache:r.httpCache.getFromCache,onFetch:r.httpCache.onFetch}:void 0));if(!r.repository){let e=M(),p=d=>K(e,d),u=d=>{let m=p(d);return z(m)?new Set(Q(m).filter(x=>x.endsWith(".kan.yml")).map(x=>x.split("@")[0])):new Set},k=d=>s.some(m=>m.publisher==="kanonak.org"&&m.package_===d),j=new W,_=u("kanonak.org");for(let d of ee)if(!(_.has(d)||k(d)))try{let m=await j.getHighestVersion("kanonak.org",d);if(!m)continue;let x=await j.getPackageUrl("kanonak.org",d,m),F=await fetch(x);if(!F.ok)continue;let J=await F.text(),D=K(e,"kanonak.org");Z(D,{recursive:!0}),X(K(D,`${d}@${m}.kan.yml`),J,"utf-8")}catch{}}let a=await new G(o).parseKanonaks(i),y=new U(a),w=new Map,b=new Map,P=new Map,N=new Set;for(let e of a){if(!(e instanceof T))continue;let p=e.namespace||"";if(!$.has(p))continue;w.set(`${p}/${e.name}`,e);let u=p.split("/")[1]??"",[k,j]=u.split("@");if(!k||!j)continue;let _=E(j);_&&(N.has(u)||(N.add(u),b.has(k)||b.set(k,[]),b.get(k).push({verStr:j,version:_})),e.name===k&&P.set(u,e))}for(let e of b.values())e.sort((p,u)=>V(u.version,p.version));return{publisher:l,availablePublishers:h,catalog:a,lookRenderer:y,localNamespaces:$,rawByNsKey:R,bySubject:w,pkgVersions:b,pkgSelfByVer:P}}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=(t,r,o,n)=>({status:t,headers:{"Content-Type":r,...n||{}},body:o}),S=t=>f(404,g[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),ne=t=>({status:301,headers:{Location:t},body:""});function Y(t,r,o){let n=t.pkgVersions.get(r);if(!n||n.length===0)return null;switch(o.kind){case"any":return n[0].verStr;case"major-pin":return n.find(s=>s.version.major===o.major)?.verStr??null;case"minor-pin":return n.find(s=>s.version.major===o.major&&s.version.minor===o.minor)?.verStr??null;case"exact":return n.find(s=>s.version.major===o.major&&s.version.minor===o.minor&&s.version.patch===o.patch)?.verStr??null;default:return null}}function te(t,r,o=""){let{lookRenderer:n,publisher:s}=t;if(r==="/.well-known/kanonak.json")return f(200,g[".json"],JSON.stringify({version:1,auth:"none"},null,2));if(r==="/index.txt"){let i=[...t.localNamespaces].map(a=>a.split("/")[1].replace("@","/")).sort();return f(200,g[".txt"],i.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-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(`
2
2
  `)+`
3
- `)}if(r==="/"||r==="/index.html"||r==="/index.css"){let i=n.publisherSubject(s);return r==="/index.css"?f(200,g[".css"],n.renderStylesheet(i)):f(200,g[".html"],n.renderDocument(i,{rootIndex:!0}))}let v=".html",h=!1,l=r;for(let i of[".kan.yml",".css",".svg",".md",".html"])if(r.endsWith(i)){v=i,h=!0,l=r.slice(0,-i.length);break}let $=!h&&/application\/yaml|text\/yaml/i.test(o),R=l.endsWith("/");R&&l!=="/"&&(l=l.slice(0,-1));let c=H.parse(l,s);if(!c)return S(r);if(c.kind==="package"){let i=Y(t,c.package_,c.versionSpec);if(!i)return S(r);if(v===".kan.yml"||$){let w=t.rawByNsKey.get(`${c.package_}@${i}`);return w!==void 0?f(200,g[".kan.yml"],w):S(r)}let a=t.pkgSelfByVer.get(`${c.package_}@${i}`);if(!a)return S(r);if(v===".css")return f(200,g[".css"],n.renderStylesheet(a));if(!R)return ne(l+"/");let y=c.versionSpec.kind==="any";if(y&&!n.hasDeclaredView(a)){let w=(t.pkgVersions.get(c.package_)||[]).map(b=>b.verStr);return f(200,g[".html"],n.renderPackageVersionList(c.package_,w,a))}return f(200,g[".html"],n.renderDocument(a,y?{bareOverview:!0}:void 0))}if(c.kind==="resource"){let i=Y(t,c.package_,c.versionSpec);if(!i)return S(r);let a=t.bySubject.get(`${s}/${c.package_}@${i}/${c.name}`);if(!a)return S(r);switch(v){case".css":return f(200,g[".css"],n.renderStylesheet(a));case".svg":return f(200,g[".svg"],n.renderSvg(a));case".md":{let y=n.renderRawMarkdown(a);return y===void 0?S(r):f(200,g[".md"],y)}default:return f(200,g[".html"],n.renderDocument(a))}}return S(r)}export{re as loadServerModel,te as route};
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.57.0",
3
+ "version": "3.58.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.57.0",
124
+ "@kanonak-protocol/types": "^3.58.0",
125
125
  "ignore": "^7.0.5",
126
126
  "js-yaml": "^4.1.0",
127
127
  "yaml": "^2.7.0"