@kanonak-protocol/sdk 6.9.0 → 7.0.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.d.ts CHANGED
@@ -43,6 +43,8 @@ export { KanonakHttpError, httpError, describeResponse, retryAfterSecondsOf } fr
43
43
  export type { ProblemDetails } from './http/HttpError.js';
44
44
  export { parseLockFile, serializeLockFile, computeIntegrityAsync, assertIntegrityAsync, INTEGRITY_PREFIX, } from './lock/LockFile.js';
45
45
  export type { LockFile, LockEntry } from './lock/LockFile.js';
46
+ export { VERSION_INDEX_FILE, parseVersionIndex, serializeVersionIndex, indexedVersion, planVersionIndex, setYanked, } from './lock/VersionIndex.js';
47
+ export type { VersionIndex, IndexedVersion, PublishedSource, VersionIndexChange, VersionIndexRefusal, VersionIndexPlan, } from './lock/VersionIndex.js';
46
48
  export { PackageBuilder, ImportBook, contentAddressedName, sanitizeName, ProducerRepository, EntitlementProducer, EntitlementDeniedError, allowAllPolicy, noopMeter, } from './producer/index.js';
47
49
  export type { BuiltPackage, ImportEntry, IPackageProducer, ProduceResult, VersionRange, IEntitlementPolicy, IMeter, ProduceContext, PackageAddress, EntitlementDecision, RequestPrincipal, } from './producer/index.js';
48
50
  export { valuesOf, referenceUris, typeReferenceUris, subjectAddress } from './uri-helpers/index.js';
package/dist/browser.js CHANGED
@@ -1 +1 @@
1
- import{a as He,b as Ne,c as ge,d as Rr,e as fr,f as yr,g as kr,i as Cr,j as Sr,k as _r,l as Er,m as xr,n as Or,o as Ir,p as Ar,q as Hr,r as Nr,s as gr}from"./chunk-MUXGPSUC.js";import{a as Mr}from"./chunk-FYAZ345F.js";import{a as pr,b as lr,c as cr,d as mr,e as dr,f as ur,g as Pr,h as Kr,i as Dr,j as Tr,k as hr,l as Lr}from"./chunk-4NTZY2KP.js";import{a as R,b as f,c as y,e as k,g as S,h as _,i as E,j as x,k as O,m as I,o as A,p as H,q as N,r as g,s as M,t as K,u as D}from"./chunk-DAWT3ZAM.js";import{a as Me,b as Ke,c as De}from"./chunk-C5HHCD6P.js";import{a as Te}from"./chunk-TR7PC72M.js";import"./chunk-SC5M74NM.js";import{A as rr,B as or,C as tr,D as nr,E as ar,O as sr,a as he,b as Le,c as Ve,d as be,i as je,j as Ue,k as ve,l as we,n as Fe,o as Be,p as Ge,q as Ye,r as qe,s as We,t as Xe,u as ze,v as Qe,w as Je,x as Ze,y as $e,z as er}from"./chunk-IZBZDLCX.js";import"./chunk-QRF7AT2M.js";import{m as ir}from"./chunk-A4OVTNMT.js";import"./chunk-QHABFCRC.js";import{a as c,b as m,c as d,d as u,e as P}from"./chunk-5FVUBF7N.js";import{a as p}from"./chunk-YEUSFSC7.js";import{a as xe,g as Oe,h as Ie,k as Ae}from"./chunk-A5EAI5ZU.js";import{a as l}from"./chunk-VAZY57HJ.js";import"./chunk-PEJALHXK.js";import{O as oe,P as te,Q as ne,R as ae,S as ie,T as se,U as pe,V as le,W as ce,X as me,Y as de,Z as ue,a as W,b as X,ca as Pe,da as Re,ea as fe,fa as ye,ga as ke,h as J,i as Z,j as $,k as ee,l as re,ma as Ce,oa as Se}from"./chunk-TVMOJ2QS.js";import{H as _e,I as Ee,a as T,b as h,c as L,d as V,e as b,g as j,h as U,i as v,j as w,k as F,l as B,m as G,n as Y,o as q,s as z,t as Q}from"./chunk-6USORWEP.js";import"./chunk-F67UH4FD.js";import{c as e,d as r,e as o,f as t,g as n,h as a,i,k as s,l as C}from"./chunk-7IMLHHSA.js";export{S as ANY_PUBLISHER,Ze as AmbiguousReferenceRule,F as BooleanStatement,cr as CANONICAL_FORM_VERSION,Ir as CREDENTIAL_EXPIRY_SKEW_SECONDS,Sr as CREDENTIAL_HELPER_PROTOCOL_VERSION,Oe as Carrier,nr as ClassDefinitionRule,Ye as ClassHierarchyCycleRule,P as CredentialError,h as DefinedKanonak,Ne as EdgeType,V as EmbeddedKanonak,Fe as EmbeddedKanonakTypeRule,G as EmbeddedStatement,hr as EntitlementDeniedError,Lr as EntitlementProducer,ge as GraphBuilder,D as HttpKanonakDocumentRepository,A as INTEGRITY_PREFIX,ur as ImportBook,Be as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,R as KANONAK_USER_AGENT,T as Kanonak,Ke as KanonakDocumentPositions,c as KanonakHttpError,Ae as KanonakObjectParser,sr as KanonakObjectValidator,l as KanonakParser,C as KanonakUri,Te as KanonakUriBuilder,Ce as KanonakVocabulary,Y as ListStatement,ar as MarkdownLinkRule,q as MarkdownStatement,Qe as NamespaceImportCycleRule,je as NamespacePrefixRule,He as NodeType,w as NumberStatement,Cr as OAuthDiscovery,ke as OWL_HAS_KEY,er as ObjectPropertyValueValidationRule,Ve as OntologyValidationError,he as OntologyValidationResult,mr as PackageBuilder,Kr as ProducerRepository,rr as PropertyDomainRule,qe as PropertyHierarchyCycleRule,or as PropertyKindRangeConsistencyRule,Me as PropertyMetadata,$e as PropertyRangeReferenceRule,We as PropertyRangeRequiredRule,ve as PropertyTypeSpecificityRule,I as PublisherConfigResolver,K as PublisherIndex,b as ReferenceKanonak,B as ReferenceStatement,tr as ReservedNameShadowRule,Ue as ResourceNamingRule,W as ResourceResolver,Se as ResourceTypeClassifier,Z as SHACL_PACKAGE,J as SHACL_PUBLISHER,ae as SH_COMP_CLASS,ue as SH_COMP_CLOSED,ne as SH_COMP_DATATYPE,ye as SH_COMP_HAS_KEY,Pe as SH_COMP_HAS_VALUE,ie as SH_COMP_IN,te as SH_COMP_MAX_COUNT,me as SH_COMP_MAX_INCLUSIVE,le as SH_COMP_MAX_LENGTH,oe as SH_COMP_MIN_COUNT,ce as SH_COMP_MIN_INCLUSIVE,pe as SH_COMP_MIN_LENGTH,de as SH_COMP_NODE_KIND,se as SH_COMP_PATTERN,fe as SH_COMP_QUALIFIED_MAX_COUNT,Re as SH_COMP_QUALIFIED_MIN_COUNT,ee as SH_NODE_SHAPE,re as SH_PROPERTY_SHAPE,$ as SH_SHAPE,U as ScalarStatement,j as Statement,v as StringStatement,Xe as SubClassOfReferenceRule,ze as SubPropertyOfReferenceRule,L as SubjectKanonak,we as SubjectKanonakTypeRequiredRule,Hr as TOKEN_ENV,gr as TokenCredentialProvider,X as TypeResolver,Je as UnresolvedPredicateRule,Ge as UnresolvedReferenceRule,be as ValidationContext,Le as ValidationSeverity,Dr as allowAllPolicy,M as assertIntegrityAsync,ir as buildOntologyModel,pr as canonicalForm,lr as canonicalHash,Ie as carrierOf,_r as checkCredentialAnswer,Er as checkHelperAnswer,xr as checkHelperEraseAnswer,E as checkPackageUrlTemplate,_ as checkPackageUrlTemplates,e as compareVersions,g as computeIntegrityAsync,dr as contentAddressedName,Ar as createCredentialedFetch,t as createVersion,d as describeResponse,O as fillPackageUrlTemplate,Mr as findDerivation,o as formatVersion,y as getKanonakUserAgent,m as httpError,a as isCompatibleVersion,i as isMajorCompatible,k as kanonakFetch,kr as narrowestScope,Tr as noopMeter,Rr as normalizeHost,x as packageUrlTemplateFor,H as parseLockFile,fr as parseScope,n as parseVersionString,De as parseWithPositions,Or as parseWwwAuthenticate,s as pickHighestDocument,Q as referenceUris,u as retryAfterSecondsOf,Pr as sanitizeName,yr as scopeContains,N as serializeLockFile,f as setKanonakUserAgent,Ee as subjectAddress,Nr as tokenEnvKeyFor,z as typeReferenceUris,_e as valuesOf,r as versionsEqual,xe as walkDefinedKanonaks};
1
+ import{a as De,b as Ke,c as Te,d as Sr,e as _r,f as Er,g as Ir,i as Or,j as Ar,k as Nr,l as gr,m as Hr,n as Vr,o as Mr,p as hr,q as Dr,r as Kr,s as Tr}from"./chunk-RFSARH5S.js";import{a as Lr}from"./chunk-FYAZ345F.js";import{a as Pr,b as Rr,c as fr,d as yr,e as kr,f as xr,g as Cr,h as br,i as jr,j as Ur,k as vr,l as Fr}from"./chunk-4NTZY2KP.js";import{A as j,a as R,b as f,c as y,e as k,g as C,h as S,i as _,j as E,k as I,m as O,o as A,p as N,q as g,r as H,s as V,t as M,u as h,v as D,w as K,x as T,y as L,z as b}from"./chunk-AEH3NZLH.js";import{a as Le,b as be,c as je}from"./chunk-C5HHCD6P.js";import{a as Ue}from"./chunk-TR7PC72M.js";import"./chunk-SC5M74NM.js";import{A as sr,B as pr,C as lr,D as cr,E as dr,O as ur,a as ve,b as Fe,c as we,d as Be,i as Ge,j as Ye,k as Xe,l as qe,n as We,o as ze,p as Qe,q as Je,r as Ze,s as $e,t as er,u as rr,v as or,w as tr,x as nr,y as ar,z as ir}from"./chunk-IZBZDLCX.js";import"./chunk-QRF7AT2M.js";import{m as mr}from"./chunk-A4OVTNMT.js";import"./chunk-QHABFCRC.js";import{a as c,b as d,c as m,d as u,e as P}from"./chunk-5FVUBF7N.js";import{a as p}from"./chunk-YEUSFSC7.js";import{a as He,g as Ve,h as Me,k as he}from"./chunk-A5EAI5ZU.js";import{a as l}from"./chunk-VAZY57HJ.js";import"./chunk-PEJALHXK.js";import{O as pe,P as le,Q as ce,R as de,S as me,T as ue,U as Pe,V as Re,W as fe,X as ye,Y as ke,Z as xe,a as $,b as ee,ca as Ce,da as Se,ea as _e,fa as Ee,ga as Ie,h as te,i as ne,j as ae,k as ie,l as se,ma as Oe,oa as Ae}from"./chunk-TVMOJ2QS.js";import{H as Ne,I as ge,a as U,b as v,c as F,d as w,e as B,g as G,h as Y,i as X,j as q,k as W,l as z,m as Q,n as J,o as Z,s as re,t as oe}from"./chunk-6USORWEP.js";import"./chunk-F67UH4FD.js";import{c as e,d as r,e as o,f as t,g as n,h as a,i,k as s,l as x}from"./chunk-7IMLHHSA.js";export{C as ANY_PUBLISHER,nr as AmbiguousReferenceRule,W as BooleanStatement,fr as CANONICAL_FORM_VERSION,Mr as CREDENTIAL_EXPIRY_SKEW_SECONDS,Ar as CREDENTIAL_HELPER_PROTOCOL_VERSION,Ve as Carrier,cr as ClassDefinitionRule,Je as ClassHierarchyCycleRule,P as CredentialError,v as DefinedKanonak,Ke as EdgeType,w as EmbeddedKanonak,We as EmbeddedKanonakTypeRule,Q as EmbeddedStatement,vr as EntitlementDeniedError,Fr as EntitlementProducer,Te as GraphBuilder,j as HttpKanonakDocumentRepository,A as INTEGRITY_PREFIX,xr as ImportBook,ze as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,R as KANONAK_USER_AGENT,U as Kanonak,be as KanonakDocumentPositions,c as KanonakHttpError,he as KanonakObjectParser,ur as KanonakObjectValidator,l as KanonakParser,x as KanonakUri,Ue as KanonakUriBuilder,Oe as KanonakVocabulary,J as ListStatement,dr as MarkdownLinkRule,Z as MarkdownStatement,or as NamespaceImportCycleRule,Ge as NamespacePrefixRule,De as NodeType,q as NumberStatement,Or as OAuthDiscovery,Ie as OWL_HAS_KEY,ir as ObjectPropertyValueValidationRule,we as OntologyValidationError,ve as OntologyValidationResult,yr as PackageBuilder,br as ProducerRepository,sr as PropertyDomainRule,Ze as PropertyHierarchyCycleRule,pr as PropertyKindRangeConsistencyRule,Le as PropertyMetadata,ar as PropertyRangeReferenceRule,$e as PropertyRangeRequiredRule,Xe as PropertyTypeSpecificityRule,O as PublisherConfigResolver,b as PublisherIndex,B as ReferenceKanonak,z as ReferenceStatement,lr as ReservedNameShadowRule,Ye as ResourceNamingRule,$ as ResourceResolver,Ae as ResourceTypeClassifier,ne as SHACL_PACKAGE,te as SHACL_PUBLISHER,de as SH_COMP_CLASS,xe as SH_COMP_CLOSED,ce as SH_COMP_DATATYPE,Ee as SH_COMP_HAS_KEY,Ce as SH_COMP_HAS_VALUE,me as SH_COMP_IN,le as SH_COMP_MAX_COUNT,ye as SH_COMP_MAX_INCLUSIVE,Re as SH_COMP_MAX_LENGTH,pe as SH_COMP_MIN_COUNT,fe as SH_COMP_MIN_INCLUSIVE,Pe as SH_COMP_MIN_LENGTH,ke as SH_COMP_NODE_KIND,ue as SH_COMP_PATTERN,_e as SH_COMP_QUALIFIED_MAX_COUNT,Se as SH_COMP_QUALIFIED_MIN_COUNT,ie as SH_NODE_SHAPE,se as SH_PROPERTY_SHAPE,ae as SH_SHAPE,Y as ScalarStatement,G as Statement,X as StringStatement,er as SubClassOfReferenceRule,rr as SubPropertyOfReferenceRule,F as SubjectKanonak,qe as SubjectKanonakTypeRequiredRule,Dr as TOKEN_ENV,Tr as TokenCredentialProvider,ee as TypeResolver,tr as UnresolvedPredicateRule,Qe as UnresolvedReferenceRule,M as VERSION_INDEX_FILE,Be as ValidationContext,Fe as ValidationSeverity,jr as allowAllPolicy,V as assertIntegrityAsync,mr as buildOntologyModel,Pr as canonicalForm,Rr as canonicalHash,Me as carrierOf,Nr as checkCredentialAnswer,gr as checkHelperAnswer,Hr as checkHelperEraseAnswer,_ as checkPackageUrlTemplate,S as checkPackageUrlTemplates,e as compareVersions,H as computeIntegrityAsync,kr as contentAddressedName,hr as createCredentialedFetch,t as createVersion,m as describeResponse,I as fillPackageUrlTemplate,Lr as findDerivation,o as formatVersion,y as getKanonakUserAgent,d as httpError,K as indexedVersion,a as isCompatibleVersion,i as isMajorCompatible,k as kanonakFetch,Ir as narrowestScope,Ur as noopMeter,Sr as normalizeHost,E as packageUrlTemplateFor,N as parseLockFile,_r as parseScope,h as parseVersionIndex,n as parseVersionString,je as parseWithPositions,Vr as parseWwwAuthenticate,s as pickHighestDocument,T as planVersionIndex,oe as referenceUris,u as retryAfterSecondsOf,Cr as sanitizeName,Er as scopeContains,g as serializeLockFile,D as serializeVersionIndex,f as setKanonakUserAgent,L as setYanked,ge as subjectAddress,Kr as tokenEnvKeyFor,re as typeReferenceUris,Ne as valuesOf,r as versionsEqual,He as walkDefinedKanonaks};
@@ -0,0 +1 @@
1
+ import{A,n as R}from"./chunk-AEH3NZLH.js";import{a as P}from"./chunk-YEUSFSC7.js";import{a as f}from"./chunk-VAZY57HJ.js";import{c as C,g as K,j as I}from"./chunk-7IMLHHSA.js";import{a as F}from"./chunk-PC3DHZGV.js";import*as m from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";var h=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;return I(r,t)});return s.length===0?null:(s.sort((a,r)=>{let l=a.metadata.namespace_.version,u=r.metadata.namespace_.version;return C(u,l)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let l=o.split("/"),u=l[0],y=l[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,u,y)}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 m.mkdir(s,{recursive:!0});let a=this.parser.save(e);await m.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 m.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 m.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await m.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=b(n).toString(),s;for(let[l,u]of this.documentCache.entries())if(this.filePathsByIdentifier.get(l)===n&&u.metadata.namespace_){s=u.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 m.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await m.access(n),t=n}catch{return null}}try{return await m.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await m.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await m.access(n),t=n}catch{return null}}return b(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 m.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await m.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 l=s.metadata.namespace_.toString();this.documentCache.set(l,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(l,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 m.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 g from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),D=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new h(e,!0,o),this.workspace=new h(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 U}from"os";import{join as V}from"path";function d(){let i=process.env.KANONAK_PACKAGE_CACHE;return i||V(U(),".kanonak","packages")}var w=class i{static createComposite(e,t,n){let o=e??d(),s=t??".";return new D(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return i.createComposite(t,n,e)}};var k=class{repos;constructor(...e){this.repos=e}async firstAnswer(e,t,n){let o=[];for(let s of this.repos)try{let a=await e(s);if(t(a))return a}catch(a){o.push(a)}return x(o),n}async getHighestCompatibleVersionAsync(e,t){return this.firstAnswer(n=>n.getHighestCompatibleVersionAsync(e,t),n=>n!==null,null)}async getAllDocumentsAsync(){let e=[],t=new Set,n=[];for(let o of this.repos)try{for(let s of await o.getAllDocumentsAsync()){let a=s.metadata?.namespace_,r=a?a.version?`${a.publisher}/${a.package_}@${a.version.major}.${a.version.minor}.${a.version.patch}`:`${a.publisher}/${a.package_}`:void 0;if(r!==void 0){if(t.has(r))continue;t.add(r)}e.push(s)}}catch(s){n.push(s)}return x(n),e}async getDocumentAsync(e){return this.firstAnswer(t=>t.getDocumentAsync(e),t=>t!==null,null)}async getDocumentsByNamespaceAsync(e,t){return this.firstAnswer(n=>n.getDocumentsByNamespaceAsync(e,t),n=>n.length>0,[])}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){return this.firstAnswer(t=>t.getDocumentContentAsync(e),t=>!!t,null)}async getDocumentUriAsync(e){return this.firstAnswer(t=>t.getDocumentUriAsync(e),t=>!!t,null)}};function x(i){if(i.length===1)throw i[0];if(i.length>1)throw new Error(i.map(e=>e instanceof Error?e.message:String(e)).join("; "))}import{VersionOperator as j}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return R(this.lock,e,t)}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=K(n);if(o){let s={...t,versionOperator:j.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as E,readdirSync as _}from"fs";import{join as H}from"path";var T=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function N(i,e=[],t={}){let n=t.ignore??new F(i),o=s=>{for(let a of _(s,{withFileTypes:!0})){let r=H(s,a.name);if(a.isDirectory()){if(T.has(a.name))continue;if(!n.shouldIgnoreDirectory(r))o(r);else if(t.ignored){let l=B(r);l>0&&t.ignored.push({path:r,isDirectory:!0,kanonakFiles:l})}}else a.name.endsWith(".kan.yml")&&(n.shouldIgnore(r)?t.ignored?.push({path:r,isDirectory:!1,kanonakFiles:1}):e.push(r))}};return o(i),e}function B(i){let e=0;for(let t of _(i,{withFileTypes:!0}))t.isDirectory()?T.has(t.name)||(e+=B(H(i,t.name))):t.name.endsWith(".kan.yml")&&e++;return e}async function W(i,e=new f,t={}){let n=new P(e);for(let l of N(i))try{let u=E(l,"utf-8"),p=e.parse(u),y=p.metadata?.namespace_;y?.version&&await n.saveDocumentAsync(p,y.toString(),u)}catch{}let o=new h(d(),!0,e);if(t.offline)return new k(n,o);let s=new Map,a=t.httpCache??{getFromCache:(l,u,p)=>s.get(`${l}|${u}|${p}`)??null,onFetch:(l,u,p,y)=>{s.set(`${l}|${u}|${p}`,y)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch,...t.fetchFn?{fetchFn:t.fetchFn}:{},...t.packageUrlTemplates?{packageUrlTemplates:t.packageUrlTemplates}:{}});return new k(n,o,r)}export{h as a,S as b,D as c,d,w as e,k as f,v as g,N as h,W as i};
@@ -0,0 +1,3 @@
1
+ import{a as E}from"./chunk-SC5M74NM.js";import{b as k,d as M,e as I}from"./chunk-5FVUBF7N.js";import{a as H}from"./chunk-VAZY57HJ.js";import{c as T,e as d,g as x,j,m as N}from"./chunk-7IMLHHSA.js";var re="@kanonak-protocol/sdk (+https://kanonak.org)",_=re;function ye(s){_=s}function we(){return _}function w(s){let e;try{e=typeof s=="string"?new URL(s):s}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(s)}`)}if(e.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${e.href} (only https:// is supported).`)}var se=new Set([429,502,503,504]),oe=4,ie=500,X=2e4;function m(s,e){w(s);let t=new Headers(e?.headers);return t.has("User-Agent")||t.set("User-Agent",_),ae(s,{...e,headers:t})}var R=oe;function ve(s){R=Math.max(0,s)}async function ae(s,e){let t;for(let r=0;r<=R;r++){let n;try{n=await fetch(s,e)}catch(i){if(t=i,r>=R)throw i;await W(B(r,void 0));continue}if(!se.has(n.status)||r>=R)return n;let o=M(n.headers.get("retry-after"));if(o!==void 0&&o*1e3>X)return n;await W(B(r,o))}throw t??new Error("kanonakFetch: exhausted retries")}function B(s,e){if(e!==void 0)return e*1e3;let t=Math.min(X,ie*2**s);return Math.floor(t/2+Math.random()*(t/2))}function W(s){return new Promise(e=>setTimeout(e,s))}var b="*",V=["publisher","package","version"];function q(s,e,t){let r=t?` in ${t}`:"";if(typeof s!="object"||s===null||Array.isArray(s))throw new Error(`${e}${r} must be an object mapping a publisher, or "${b}", to a package URL template`);let n={};for(let[o,i]of Object.entries(s)){let a=o===b;if(!a&&!ge(o))throw new Error(`${e}${r} names "${o}", which is not a publisher (a publisher is a bare domain, e.g. example.org)`);n[o]=ce(i,`${e}["${o}"]${r}`,a)}return Object.freeze(n)}function ce(s,e,t){if(typeof s!="string"||s.trim()==="")throw new Error(`${e} must be a package URL template string`);if(!s.startsWith("https://"))throw new Error(`${e} must be an absolute https:// URL template (got "${s}")`);let r=(s.match(/\{[^{}]*\}/g)??[]).filter(i=>!V.includes(i.slice(1,-1)));if(r.length>0)throw new Error(`${e} has the unknown placeholder ${r[0]}; a package URL template takes {publisher}, {package} and {version}`);let o=(t?V:V.filter(i=>i!=="publisher")).filter(i=>!s.includes(`{${i}}`)).map(i=>`{${i}}`);if(o.length>0)throw new Error(`${e} must contain ${o.join(", ")}`+(t?", so that one template addresses every publisher's packages":"")+` (got "${s}")`);return s}function O(s,e){if(s)return Object.hasOwn(s,e)?s[e]:Object.hasOwn(s,b)?s[b]:void 0}function P(s,e,t,r){let n={publisher:e,package:t,version:r},o=s;for(let[a,c]of Object.entries(n))o=o.replaceAll(`{${a}}`,c);let i=o.match(/\{[a-z]+\}/);if(i)throw new Error(`Unresolved variable ${i[0]} in URL template: ${s}`);return w(o),o}function ge(s){if(s.trim()!==s)return!1;try{let e=N(s);return e.kind==="publisher"&&e.publisher===s}catch{return!1}}var le="https://{publisher}/{package}/{version}.kan.yml",Y={version:1};function Ce(){return{version:1}}var C=class{constructor(e){this.fetchFn=e}fetchFn;cache=new Map;getConfig(e){let t=this.cache.get(e);return t||(t=this.fetchConfig(e),this.cache.set(e,t),t.catch(()=>{this.cache.get(e)===t&&this.cache.delete(e)})),t}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await(this.fetchFn?this.fetchFn(t,e):m(t))}catch(i){if(i instanceof I)throw i;return Y}if(r.status===404)return Y;if(!r.ok)throw await k("publisher config",t,r);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let o={version:n.version};return typeof n.package_url_template=="string"&&(he(t,"package_url_template",n.package_url_template),o.package_url_template=n.package_url_template),Array.isArray(n.featured_packages)&&n.featured_packages.every(i=>typeof i=="string")&&(o.featured_packages=n.featured_packages),o}resolvePackageUrl(e,t,r,n){let o=n.package_url_template??le;return P(o,e,t,r)}};function he(s,e,t){if(!t.startsWith("https://"))throw new Error(`Invalid publisher config at ${s}: ${e} must be an absolute https:// URL template (got "${t}").`)}import G from"js-yaml";function Le(s,e,t){return s.packages[`${e}/${t}`]?.version}var ue=`# This file is generated by Kanonak CLI. Do not edit manually.
2
+ `,F="sha256:";function z(s){let e=G.load(s);return!e||typeof e!="object"||e.version!=="1"?null:{version:"1",lastUpdated:e.lastUpdated??"",packages:e.packages??{}}}function Te(s){let e={};for(let r of Object.keys(s.packages).sort())e[r]=s.packages[r];let t=G.dump({...s,packages:e},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return ue+t}async function D(s){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s)),t=Array.from(new Uint8Array(e),r=>r.toString(16).padStart(2,"0")).join("");return`${F}${t}`}async function J(s,e,t,r){let n=await D(e);if(n!==t)throw new Error(`Integrity mismatch for ${s}: the lock declares ${t||"(no integrity)"} but the bytes from ${r} hash to ${n}.`)}import Z from"js-yaml";var K="kanonak.index",U="1",pe=`# This file is generated by Kanonak CLI. Do not edit manually.
3
+ `,de=/^[0-9a-f]{64}$/;function ee(s,e){let t=o=>{throw new Error(`${e} is not a kanonak.index: ${o}.`)},r=Z.load(s);if(!A(r))return t("it is not a YAML mapping");if(Q(r,["version","publisher","packages"],"the top level",t),r.version!==U&&t(`its version is ${JSON.stringify(r.version)}, and this SDK reads "${U}"`),(typeof r.publisher!="string"||r.publisher==="")&&t("it names no publisher"),!A(r.packages))return t("its packages are not a mapping");let n={};for(let[o,i]of Object.entries(r.packages)){if(!A(i))return t(`${o}'s versions are not a mapping`);n[o]={};for(let[a,c]of Object.entries(i)){let l=`${o}@${a}`,g=x(a);if((!g||d(g)!==a)&&t(`${l} is not a MAJOR.MINOR.PATCH version`),!A(c))return t(`${l}'s entry is not a mapping`);Q(c,["integrity","yanked"],l,t),(typeof c.integrity!="string"||!c.integrity.startsWith(F)||!de.test(c.integrity.slice(F.length)))&&t(`${l}'s integrity is not ${F} and 64 lowercase hex digits`),c.yanked!==void 0&&c.yanked!==!0&&t(`${l}'s yanked is ${JSON.stringify(c.yanked)}; it is true, or absent`),n[o][a]=c.yanked?{integrity:c.integrity,yanked:!0}:{integrity:c.integrity}}}return{version:U,publisher:r.publisher,packages:n}}function Ke(s){let e={};for(let r of Object.keys(s.packages).sort()){let n=s.packages[r];e[r]={};for(let o of fe(Object.keys(n)))e[r][o]=n[o]}let t=Z.dump({version:s.version,publisher:s.publisher,packages:e},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return pe+t}function Se(s,e,t){return s.packages[e]?.[d(t)]}async function je(s){let{publisher:e,current:t,sources:r,served:n}=s;for(let[g,h]of[[t,"the workspace"],[n,"the origin"]])if(g&&g.publisher!==e)throw new Error(`The kanonak.index ${h} holds is ${g.publisher}'s, not ${e}'s.`);let o={version:U,publisher:e,packages:{}},i=[],a=[],c=new Set,l=[...r].sort((g,h)=>g.package_<h.package_?-1:g.package_>h.package_?1:T(g.version,h.version));for(let{package_:g,version:h,source:p}of l){let u=d(h),y=`${g}@${u}`;if(c.has(y))throw new Error(`The workspace holds ${e}/${y} twice.`);c.add(y);let f=await D(p),$=n?.packages[g]?.[u];if($&&$.integrity!==f){a.push({kind:"changed",package_:g,version:u,message:`${e}/${y} is published with ${$.integrity}, and its source now hashes to ${f}. A published version never changes: restore its bytes, and make the change as a new version.`});continue}let v=t?.packages[g]?.[u];v?v.integrity!==f&&i.push({kind:"rehashed",package_:g,version:u,message:$?`restored ${e}/${y} to the sha256 it was published with: ${v.integrity} \u2192 ${f}`:`rehashed ${e}/${y}, which is not published yet: ${v.integrity} \u2192 ${f}`}):i.push({kind:"added",package_:g,version:u,message:`added ${e}/${y} (${f})`});let ne=v?v.yanked:$?.yanked;(o.packages[g]??={})[u]=ne?{integrity:f,yanked:!0}:{integrity:f}}for(let[g,h]of Object.entries(n?.packages??{}))for(let p of Object.keys(h))c.has(`${g}@${p}`)||a.push({kind:"removed",package_:g,version:p,message:`${e}/${g}@${p} is published, and the workspace no longer holds its source. A published version is never removed, and a yanked one is still served: restore its source.`});for(let[g,h]of Object.entries(t?.packages??{}))for(let p of Object.keys(h)){let u=`${g}@${p}`;c.has(u)||n?.packages[g]?.[p]||i.push({kind:"removed",package_:g,version:p,message:`removed ${e}/${u}, which is not published and whose source is gone`})}return{index:o,changes:i,refusals:a}}function He(s,e,t,r){let n=d(t),o=s.packages[e]?.[n];if(!o)throw new Error(`${s.publisher}'s kanonak.index has no entry for ${e}@${n}, so it can't be ${r?"yanked":"unyanked"}.`);let i={...s.packages[e],[n]:r?{integrity:o.integrity,yanked:!0}:{integrity:o.integrity}};return{...s,packages:{...s.packages,[e]:i}}}function fe(s){return s.map(e=>({text:e,version:x(e)})).map(({text:e,version:t})=>{if(!t)throw new Error(`"${e}" is not a MAJOR.MINOR.PATCH version, so it can't be in a kanonak.index.`);return{text:e,version:t}}).sort((e,t)=>T(e.version,t.version)).map(({text:e})=>e)}function A(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Q(s,e,t,r){for(let n of Object.keys(s))e.includes(n)||r(`${t} has "${n}", which the format doesn't have`)}var L=class{configResolver;fetchFn;packageUrlTemplates;lockCache=new Map;packageLockCache=new Map;versionIndexCache=new Map;constructor(e){this.configResolver=e?.configResolver??new C(e?.fetchFn),this.fetchFn=e?.fetchFn,this.packageUrlTemplates=e?.packageUrlTemplates?q(e.packageUrlTemplates,"packageUrlTemplates"):void 0}getConfig(e){return this.configResolver.getConfig(e)}async getPackageUrl(e,t,r){let n=O(this.packageUrlTemplates,e);if(n)return P(n,e,t,r);let o=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,o)}lockedSourceUrl(e,t,r){let n=O(this.packageUrlTemplates,e);return n?P(n,e,t,r.version):r.resolved}async fetchLockedSource(e,t,r){let n=`${e}/${t}@${r.version}`,o=this.lockedSourceUrl(e,t,r);w(o);let i=this.fetchFn?await this.fetchFn(o,e):await m(o);if(!i.ok)throw await k(n,o,i);let a=await i.text();return await J(n,a,r.integrity,o),{url:o,content:a}}getLock(e){let t=this.lockCache.get(e);return t||(t=this.fetchLock(e),this.lockCache.set(e,t),t.catch(()=>{this.lockCache.get(e)===t&&this.lockCache.delete(e)})),t}async getPackageLockEntry(e,t){let r=`${e}/${t}`,n=this.packageLockCache.get(r);return n||(n=this.fetchLock(e,t),this.packageLockCache.set(r,n),n.catch(()=>{this.packageLockCache.get(r)===n&&this.packageLockCache.delete(r)})),(await n)?.packages[r]??null}getVersionIndex(e){let t=this.versionIndexCache.get(e);return t||(t=this.fetchVersionIndex(e),this.versionIndexCache.set(e,t),t.catch(()=>{this.versionIndexCache.get(e)===t&&this.versionIndexCache.delete(e)})),t}async fetchVersionIndex(e){let t=`https://${e}/${K}`,r=this.fetchFn?await this.fetchFn(t,e):await m(t);if(r.status===404)return null;if(!r.ok)throw await k(`${e}'s ${K}`,t,r);let n=ee(await r.text(),t);if(n.publisher!==e)throw new Error(`${t} is ${n.publisher}'s index, not ${e}'s.`);return n}async fetchLock(e,t){let r=t?`https://${e}/${t}/kanonak.lock`:`https://${e}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(r,e):await m(r)}catch(o){if(o instanceof I)throw o;return null}if(n.status===404)return null;if(!n.ok)throw await k("publisher lock",r,n);return z(await n.text())}};import{VersionOperator as S}from"@kanonak-protocol/types/document/models/enums";function ke(s,e){let t=x(s);return t?j(t,e):!1}var te=class{parser=new H;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=new L({...e?.fetchFn?{fetchFn:e.fetchFn}:{},...e?.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}})}async getHighestCompatibleVersionAsync(e,t){if(t.versionOperator===S.Exact){let o=await this.fromMemoOrCache(e,t.packageName,d(t.version));if(o)return o}let n=(await this.publisherIndex.getLock(e))?.packages[`${e}/${t.packageName}`]??await this.publisherIndex.getPackageLockEntry(e,t.packageName)??void 0;return n&&ke(n.version,t)?this.fetchPinned(e,t.packageName,n):n&&t.versionOperator!==S.Exact?null:this.resolveByDirectFetch(e,t)}async fetchPinned(e,t,r){let n=r.version,o=`${e}/${t}@${n}`,i=await this.fromMemoOrCache(e,t,n);if(i)return i;let{content:a}=await this.publisherIndex.fetchLockedSource(e,t,r),c=this.parser.parse(a);return E(c,e,t,n),this.onFetch&&await this.onFetch(e,t,n,a),this.documents.set(o,c),this.contentCache.set(o,a),c}async fromMemoOrCache(e,t,r){let n=`${e}/${t}@${r}`,o=this.documents.get(n);if(o)return o;if(!this.getFromCache)return null;let i=await this.getFromCache(e,t,r);if(i==null)return null;let a;try{a=this.parser.parse(i),E(a,e,t,r)}catch(c){throw new Error(`Cached content for ${n} is not a usable copy of that package \u2014 refusing to fall through to a fetch that would hide it. ${c.message}`,{cause:c})}return this.documents.set(n,a),this.contentCache.set(n,i),a}async resolveByDirectFetch(e,t){let r=t.packageName,o=t.versionOperator===S.Exact?await this.publisherIndex.getPackageUrl(e,r,d(t.version)):`https://${e}/${r}.kan.yml`,i=await this.fetchFollowing(o,e);if(!i)return null;let a=this.parser.parse(i.content),c=a.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${e}/${r}`);let l=d(c.version);E(a,e,r,l);let g=`${e}/${r}@${l}`;return this.onFetch&&await this.onFetch(e,r,l,i.content),this.documents.set(g,a),this.contentCache.set(g,i.content),a}async fetchFollowing(e,t,r=4){let n=e;for(let o=0;o<r;o++){w(n);let i=this.fetchFn?await this.fetchFn(n,t):await m(n,{redirect:"manual"});if(i.status===301||i.status===302){let a=i.headers.get("location");if(!a)throw new Error(`Redirect with no Location header from ${n}`);n=new URL(a,n).toString();continue}if(i.status===404)return null;if(!i.ok)throw await k("Kanonak package",n,i);return{url:n,content:await i.text()}}throw new Error(`Too many redirects resolving ${e}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,o]=t;return this.publisherIndex.getPackageUrl(r,n,o)}};export{re as a,ye as b,we as c,w as d,m as e,ve as f,b as g,q as h,ce as i,O as j,P as k,Ce as l,C as m,Le as n,F as o,z as p,Te as q,D as r,J as s,K as t,ee as u,Ke as v,Se as w,je as x,He as y,L as z,te as A};
@@ -1,2 +1,2 @@
1
- import{e as j}from"./chunk-DAWT3ZAM.js";import{a as I,b as K,c as ee,e as T}from"./chunk-5FVUBF7N.js";import{k as re}from"./chunk-A5EAI5ZU.js";import{oa as _,ra as z}from"./chunk-TVMOJ2QS.js";import{c as G,o as te}from"./chunk-6USORWEP.js";var se=(i=>(i.Class="Class",i.DatatypeProperty="DatatypeProperty",i.ObjectProperty="ObjectProperty",i.AnnotationProperty="AnnotationProperty",i.Instance="Instance",i.Datatype="Datatype",i.Shape="Shape",i.Unknown="Unknown",i))(se||{}),ae=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(ae||{}),H=class{static async buildFromRepository(e,r){let s=await new re().parseKanonaks(e),o=await e.getAllDocumentsAsync(),c=[],p=[],i=new Set,h=new Set,b=new Map;for(let g of s){let a=g;if(a.name&&(_.isClassType(a)&&i.add(a.name),g instanceof G)){let d=z(s,g);(d==="ObjectProperty"||d==="Property")&&h.add(a.name)}}for(let g of o)for(let[a,d]of Object.entries(g.body))h.has(a)&&d?.range&&typeof d.range=="string"&&b.set(a,d.range);let w=new Map;for(let g of s){let a=g;a.name&&w.set(a.name,a)}for(let g of o){let a=g.metadata.namespace_,d=a?`${a.publisher}/${a.package_}`:"",u=a?.version?`${a.version.major}.${a.version.minor}.${a.version.patch}`:"",y=ne(g);for(let[f,l]of Object.entries(g.body)){if(!l||typeof l!="object")continue;let A=w.get(f),m="Unknown";if(A){let E=A,k=A instanceof G?z(s,A):void 0;_.isClassType(E)?m="Class":k==="ObjectProperty"?m="ObjectProperty":k==="DatatypeProperty"?m="DatatypeProperty":k==="AnnotationProperty"?m="AnnotationProperty":_.isDatatypeType(E)?m="Datatype":k==="Property"?m="ObjectProperty":_.isShapeType(E)?m="Shape":_.isInstanceOfKnownClass(E,i)&&(m="Instance")}let C=d&&u?`${d}/${f}@${u}`:f,R={};for(let[E,k]of Object.entries(l))E!=="type"&&(typeof k!="object"||k===null)&&(R[E]=k);c.push({id:C,label:l.label??f,type:m,namespace:d,properties:R}),oe(C,l,m,i,h,p,d,u,y,r),q(C,l,h,b,c,p,d,u,y),Ce(C,A,p)}}return{nodes:c,edges:p}}static buildFromDocument(e,r){let n=[],s=[],o=e.metadata.namespace_,c=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",p=o?`${o.publisher}/${o.package_}`:"",i=new Set,h=new Set,b=new Map,w=ne(e);for(let[d,u]of Object.entries(e.body)){let y=u?.type;y&&(be(y,w)&&i.add(d),Pe(y,w)&&(h.add(d),u.range&&typeof u.range=="string"&&b.set(d,u.range)))}for(let[d,u]of Object.entries(e.body)){if(!u||typeof u!="object")continue;let y=u.type,f=Ae(y,d,i,w),l=p&&c?`${p}/${d}@${c}`:d,A={};for(let[m,C]of Object.entries(u))m!=="type"&&(typeof C!="object"||C===null)&&(A[m]=C);n.push({id:l,label:u.label??d,type:f,namespace:p,properties:A}),oe(l,u,f,i,h,s,p,c,w,r),q(l,u,h,b,n,s,p,c,w)}let g=new Set(n.map(d=>d.id)),a=s.filter(d=>g.has(d.source)&&g.has(d.target));return{nodes:n,edges:a}}};function ne(t,e){let r=new Map;if(t.metadata?.imports)for(let[n,s]of Object.entries(t.metadata.imports))for(let o of s){let c=o.alias??o.packageName,p=o.version,i=`${p.major}.${p.minor}.${p.patch}`;r.set(c,{publisher:n,package_:o.packageName,version:i})}return r}var ie={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ke=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function W(t,e){if(t.includes(".")){let r=t.indexOf("."),n=t.substring(0,r),s=t.substring(r+1),o=e.get(n);if(o)return`${o.publisher}/${o.package_}/${s}`}return null}function be(t,e){let r=W(t,e);return r?ie[r]==="Class":!1}function Pe(t,e){let r=W(t,e);return r?ke.has(r):!1}function Ae(t,e,r,n){if(!t||t==="Package")return"Unknown";let s=W(t,n);if(s){let c=ie[s];if(c)return c;let p=s.split("/").pop()?.split("@")[0]??"";return r.has(p)?"Instance":"Unknown"}let o=t.split(".").pop()??t;return r.has(o)?"Instance":"Unknown"}var ce=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function oe(t,e,r,n,s,o,c,p,i,h){let b=e.type,w=e.subClassOf;if(w){let f=Array.isArray(w)?w:[w];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subClassOf",label:"subClassOf"})}let g=e.subPropertyOf;if(g){let f=Array.isArray(g)?g:[g];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subPropertyOf",label:"subPropertyOf"})}let a=e.domain,d=e.range;if(h?.includePropertyEdges){let f=[[a,"domain","domain"],[d,"range","range"]];for(let[l,A,m]of f)if(l!=null)for(let C of Array.isArray(l)?l:[l])typeof C=="string"&&o.push({source:t,target:O(C,c,p,i),type:A,label:m})}if(r==="Instance"&&b){let f=b.split(".").pop()??b;o.push({source:t,target:O(f,c,p,i),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[f,l]of Object.entries(e)){if(ce.has(f)||!s.has(f))continue;let A=Array.isArray(l)?l:[l];for(let m of A)typeof m=="string"&&Ee(m)&&o.push({source:t,target:O(m,c,p,i),type:"propertyValue",label:f,propertyId:O(f,c,p,i)})}if((r==="ObjectProperty"||r==="DatatypeProperty"||a&&d)&&a&&d){let f=typeof a=="string"?a:null,l=typeof d=="string"?d:null;f&&l&&o.push({source:O(f,c,p,i),target:O(l,c,p,i),type:"objectRelationship",label:e.label??t.split("/").pop()??"",propertyId:t})}}function q(t,e,r,n,s,o,c,p,i){for(let[h,b]of Object.entries(e)){if(ce.has(h)||typeof b!="object"||b===null||Array.isArray(b))continue;let w=b,g=`${t}/${h}`,a=n.get(h),d=a?a.split(".").pop()??a:"Unknown",u={};for(let[f,l]of Object.entries(w))(typeof l!="object"||l===null)&&(u[f]=l);s.push({id:g,label:`${d} (embedded)`,type:"Instance",namespace:c,properties:u});let y=c&&p?`${c}/${h}@${p}`:h;o.push({source:t,target:g,type:"propertyValue",label:h,propertyId:r.has(h)?y:void 0}),a&&o.push({source:g,target:O(d,c,p,i),type:"instanceOf",label:"type (inferred)"}),q(g,w,r,n,s,o,c,p,i)}}function Ce(t,e,r){let n=e?.statement;if(Array.isArray(n))for(let s of n){if(!(s instanceof te))continue;let o=s.predicate?.subject?.name??"";for(let c of s.links){let p=c.target?.subject;if(!p)continue;let i=p.version,h=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";r.push({source:t,target:`${p.publisher}/${p.package_}/${p.name}${h}`,type:"embeddedLink",label:o})}}}function Ee(t){return!(!t||t.includes(" ")||t.includes(`
1
+ import{e as j}from"./chunk-AEH3NZLH.js";import{a as I,b as K,c as ee,e as T}from"./chunk-5FVUBF7N.js";import{k as re}from"./chunk-A5EAI5ZU.js";import{oa as _,ra as z}from"./chunk-TVMOJ2QS.js";import{c as G,o as te}from"./chunk-6USORWEP.js";var se=(i=>(i.Class="Class",i.DatatypeProperty="DatatypeProperty",i.ObjectProperty="ObjectProperty",i.AnnotationProperty="AnnotationProperty",i.Instance="Instance",i.Datatype="Datatype",i.Shape="Shape",i.Unknown="Unknown",i))(se||{}),ae=(i=>(i.InstanceOf="instanceOf",i.SubClassOf="subClassOf",i.Domain="domain",i.Range="range",i.ObjectRelationship="objectRelationship",i.SubPropertyOf="subPropertyOf",i.PropertyValue="propertyValue",i.EmbeddedLink="embeddedLink",i))(ae||{}),H=class{static async buildFromRepository(e,r){let s=await new re().parseKanonaks(e),o=await e.getAllDocumentsAsync(),c=[],p=[],i=new Set,h=new Set,b=new Map;for(let g of s){let a=g;if(a.name&&(_.isClassType(a)&&i.add(a.name),g instanceof G)){let d=z(s,g);(d==="ObjectProperty"||d==="Property")&&h.add(a.name)}}for(let g of o)for(let[a,d]of Object.entries(g.body))h.has(a)&&d?.range&&typeof d.range=="string"&&b.set(a,d.range);let w=new Map;for(let g of s){let a=g;a.name&&w.set(a.name,a)}for(let g of o){let a=g.metadata.namespace_,d=a?`${a.publisher}/${a.package_}`:"",u=a?.version?`${a.version.major}.${a.version.minor}.${a.version.patch}`:"",y=ne(g);for(let[f,l]of Object.entries(g.body)){if(!l||typeof l!="object")continue;let A=w.get(f),m="Unknown";if(A){let E=A,k=A instanceof G?z(s,A):void 0;_.isClassType(E)?m="Class":k==="ObjectProperty"?m="ObjectProperty":k==="DatatypeProperty"?m="DatatypeProperty":k==="AnnotationProperty"?m="AnnotationProperty":_.isDatatypeType(E)?m="Datatype":k==="Property"?m="ObjectProperty":_.isShapeType(E)?m="Shape":_.isInstanceOfKnownClass(E,i)&&(m="Instance")}let C=d&&u?`${d}/${f}@${u}`:f,R={};for(let[E,k]of Object.entries(l))E!=="type"&&(typeof k!="object"||k===null)&&(R[E]=k);c.push({id:C,label:l.label??f,type:m,namespace:d,properties:R}),oe(C,l,m,i,h,p,d,u,y,r),q(C,l,h,b,c,p,d,u,y),Ce(C,A,p)}}return{nodes:c,edges:p}}static buildFromDocument(e,r){let n=[],s=[],o=e.metadata.namespace_,c=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",p=o?`${o.publisher}/${o.package_}`:"",i=new Set,h=new Set,b=new Map,w=ne(e);for(let[d,u]of Object.entries(e.body)){let y=u?.type;y&&(be(y,w)&&i.add(d),Pe(y,w)&&(h.add(d),u.range&&typeof u.range=="string"&&b.set(d,u.range)))}for(let[d,u]of Object.entries(e.body)){if(!u||typeof u!="object")continue;let y=u.type,f=Ae(y,d,i,w),l=p&&c?`${p}/${d}@${c}`:d,A={};for(let[m,C]of Object.entries(u))m!=="type"&&(typeof C!="object"||C===null)&&(A[m]=C);n.push({id:l,label:u.label??d,type:f,namespace:p,properties:A}),oe(l,u,f,i,h,s,p,c,w,r),q(l,u,h,b,n,s,p,c,w)}let g=new Set(n.map(d=>d.id)),a=s.filter(d=>g.has(d.source)&&g.has(d.target));return{nodes:n,edges:a}}};function ne(t,e){let r=new Map;if(t.metadata?.imports)for(let[n,s]of Object.entries(t.metadata.imports))for(let o of s){let c=o.alias??o.packageName,p=o.version,i=`${p.major}.${p.minor}.${p.patch}`;r.set(c,{publisher:n,package_:o.packageName,version:i})}return r}var ie={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ke=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function W(t,e){if(t.includes(".")){let r=t.indexOf("."),n=t.substring(0,r),s=t.substring(r+1),o=e.get(n);if(o)return`${o.publisher}/${o.package_}/${s}`}return null}function be(t,e){let r=W(t,e);return r?ie[r]==="Class":!1}function Pe(t,e){let r=W(t,e);return r?ke.has(r):!1}function Ae(t,e,r,n){if(!t||t==="Package")return"Unknown";let s=W(t,n);if(s){let c=ie[s];if(c)return c;let p=s.split("/").pop()?.split("@")[0]??"";return r.has(p)?"Instance":"Unknown"}let o=t.split(".").pop()??t;return r.has(o)?"Instance":"Unknown"}var ce=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function oe(t,e,r,n,s,o,c,p,i,h){let b=e.type,w=e.subClassOf;if(w){let f=Array.isArray(w)?w:[w];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subClassOf",label:"subClassOf"})}let g=e.subPropertyOf;if(g){let f=Array.isArray(g)?g:[g];for(let l of f)typeof l=="string"&&o.push({source:t,target:O(l,c,p,i),type:"subPropertyOf",label:"subPropertyOf"})}let a=e.domain,d=e.range;if(h?.includePropertyEdges){let f=[[a,"domain","domain"],[d,"range","range"]];for(let[l,A,m]of f)if(l!=null)for(let C of Array.isArray(l)?l:[l])typeof C=="string"&&o.push({source:t,target:O(C,c,p,i),type:A,label:m})}if(r==="Instance"&&b){let f=b.split(".").pop()??b;o.push({source:t,target:O(f,c,p,i),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[f,l]of Object.entries(e)){if(ce.has(f)||!s.has(f))continue;let A=Array.isArray(l)?l:[l];for(let m of A)typeof m=="string"&&Ee(m)&&o.push({source:t,target:O(m,c,p,i),type:"propertyValue",label:f,propertyId:O(f,c,p,i)})}if((r==="ObjectProperty"||r==="DatatypeProperty"||a&&d)&&a&&d){let f=typeof a=="string"?a:null,l=typeof d=="string"?d:null;f&&l&&o.push({source:O(f,c,p,i),target:O(l,c,p,i),type:"objectRelationship",label:e.label??t.split("/").pop()??"",propertyId:t})}}function q(t,e,r,n,s,o,c,p,i){for(let[h,b]of Object.entries(e)){if(ce.has(h)||typeof b!="object"||b===null||Array.isArray(b))continue;let w=b,g=`${t}/${h}`,a=n.get(h),d=a?a.split(".").pop()??a:"Unknown",u={};for(let[f,l]of Object.entries(w))(typeof l!="object"||l===null)&&(u[f]=l);s.push({id:g,label:`${d} (embedded)`,type:"Instance",namespace:c,properties:u});let y=c&&p?`${c}/${h}@${p}`:h;o.push({source:t,target:g,type:"propertyValue",label:h,propertyId:r.has(h)?y:void 0}),a&&o.push({source:g,target:O(d,c,p,i),type:"instanceOf",label:"type (inferred)"}),q(g,w,r,n,s,o,c,p,i)}}function Ce(t,e,r){let n=e?.statement;if(Array.isArray(n))for(let s of n){if(!(s instanceof te))continue;let o=s.predicate?.subject?.name??"";for(let c of s.links){let p=c.target?.subject;if(!p)continue;let i=p.version,h=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"";r.push({source:t,target:`${p.publisher}/${p.package_}/${p.name}${h}`,type:"embeddedLink",label:o})}}}function Ee(t){return!(!t||t.includes(" ")||t.includes(`
2
2
  `)||t.startsWith("http://")||t.startsWith("https://")||/^\d{4}-\d{2}/.test(t)||/^\d+(\.\d+)?$/.test(t))}function O(t,e,r,n){if(t.includes("@")&&t.includes("/"))return t;if(t.includes(".")){let s=t.indexOf("."),o=t.substring(0,s),c=t.substring(s+1);if(n){let p=n.get(o);if(p)return`${p.publisher}/${p.package_}/${c}@${p.version}`}return e&&r?`${e}/${c}@${r}`:c}return e&&r?`${e}/${t}@${r}`:t}function M(t){let e=t.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}function v(t){let e;try{e=new URL(t)}catch{throw new Error(`credential scope '${t}' is not an absolute URL`)}if(e.protocol!=="https:")throw new Error(`credential scope '${t}' is not https`);if(e.username||e.password)throw new Error(`credential scope '${t}' carries userinfo`);if(e.search||t.includes("?"))throw new Error(`credential scope '${t}' has a query`);if(e.hash||t.includes("#"))throw new Error(`credential scope '${t}' has a fragment`);let r=e.pathname;return{origin:e.origin,prefix:r.endsWith("/")?r:`${r}/`}}function N(t,e){let r=typeof t=="string"?v(t):t,n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="https:"||n.origin!==r.origin)return!1;let s=n.pathname;return s.startsWith(r.prefix)||`${s}/`===r.prefix}function V(t,e){let r,n=-1;for(let s of t){let o=v(s.scope);N(o,e)&&o.prefix.length>n&&(r=s,n=o.prefix.length)}return r}var Oe="key_thumbprint",x=class{cache=new Map;wellKnownCache=new Map;metadataUrlCache=new Map;async protectedResourceMetadata(e){let r=new URL(e).href,n=this.wellKnownCache.get(r);return n||(n=this.fetchWellKnown(r),this.wellKnownCache.set(r,n)),n}async protectedResourceMetadataAt(e,r){let n=new URL(e).href,s=this.metadataUrlCache.get(n);s||(s=this.fetchMetadataAt(n),this.metadataUrlCache.set(n,s));let o=await s,c;try{c=N(v(o.resource),r)}catch(p){throw new Error(`Protected resource metadata at ${n} names an unusable resource '${o.resource}': ${p.message}`)}if(!c)throw new Error(`Protected resource metadata at ${n} names the resource '${o.resource}', which does not contain the requested ${r}. RFC 9728 \xA73.3 forbids using it.`);return o}async fetchWellKnown(e){let r=new URL(e),n=r.pathname==="/"?"":r.pathname,s=`${r.origin}/.well-known/oauth-protected-resource${n}`,o=await j(s,{redirect:"manual"});if(o.status===404||o.status===410||o.status>=300&&o.status<400)return null;if(!o.ok)throw await K("protected resource metadata",s,o);if(!pe(o.headers.get("content-type")))return null;let c=de(s,await o.text());if(!URL.canParse(c.resource)||new URL(c.resource).href!==e)throw new Error(`Protected resource metadata at ${s} names the resource '${c.resource}', not '${e}'. RFC 9728 \xA73.3 forbids using it.`);return c}async fetchMetadataAt(e){let r=await j(e,{redirect:"manual"});if(!r.ok)throw await K("protected resource metadata",e,r);if(!pe(r.headers.get("content-type")))throw new Error(`Protected resource metadata at ${e} is not a JSON document (${r.headers.get("content-type")??"no content type"})`);return de(e,await r.text())}async discover(e){let r=M(e);if(this.cache.has(r))return this.cache.get(r);let n=`https://${r}/.well-known/oauth-authorization-server`,s=await this.tryEndpoint(n);if(!s){let o=`https://${r}/.well-known/openid-configuration`;s=await this.tryEndpoint(o)}return this.cache.set(r,s),s}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(r=>r.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(r=>r.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let r;try{r=await fetch(e)}catch(s){let o=s instanceof Error?s.message:String(s);return o.includes("ENOTFOUND")||o.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${o})`),console.error(" If the server is behind a VPN, ensure you are connected.")):o.includes("CERT")||o.includes("SSL")||o.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${o})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${o}`),null}if(!r.ok)return r.status===404||(r.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):r.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${r.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await r.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:$(n.issuer),authorizationEndpoint:$(n.authorization_endpoint),tokenEndpoint:$(n.token_endpoint),registrationEndpoint:$(n.registration_endpoint),revocationEndpoint:$(n.revocation_endpoint),scopesSupported:S(n.scopes_supported),responseTypesSupported:S(n.response_types_supported),grantTypesSupported:S(n.grant_types_supported),codeChallengeMethodsSupported:S(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:S(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:S(n.dpop_signing_alg_values_supported),enrollmentEndpoint:$(n.enrollment_endpoint),enrollmentIssuanceProtocols:S(n.enrollment_issuance_protocols),enrollmentKeyTypes:S(n.enrollment_key_types),enrollmentScopesSupported:S(n.enrollment_scopes_supported),enrollmentConsentBindingParam:$(n.enrollment_consent_binding_param),sessionEndpoint:$(n.session_endpoint),sessionEndpointAuthMethod:$(n.session_endpoint_auth_method)}}};function pe(t){let e=(t??"").split(";")[0].trim().toLowerCase();return e==="application/json"||e.endsWith("+json")}function de(t,e){let r;try{r=JSON.parse(e)}catch{throw new Error(`Protected resource metadata at ${t} is not valid JSON`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`Protected resource metadata at ${t} is not a JSON object`);let n=r;if(typeof n.resource!="string")throw new Error(`Protected resource metadata at ${t} has no "resource"`);let s=n.authorization_servers;if(s!==void 0&&!(Array.isArray(s)&&s.every(o=>typeof o=="string")))throw new Error(`Protected resource metadata at ${t} has an "authorization_servers" that is not a list of strings`);return{resource:n.resource,authorizationServers:s??[]}}function $(t){return typeof t=="string"?t:null}function S(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):null}var D=1,$e=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Se=/[\r\n\0]/;function P(t,e){return{ok:!1,problem:t,message:e}}function L(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U(t,e,r){if(!L(e))return P("malformed","the answer is not a JSON object");if(e.status==="declined")return e.reason!==void 0&&typeof e.reason!="string"?P("reason",`a decline's "reason" must be a string`):{ok:!0,answer:e.reason===void 0?{status:"declined"}:{status:"declined",reason:e.reason}};if(e.status!=="credential")return P("status",`"status" must be "credential" or "declined", not ${JSON.stringify(e.status)}`);let n=e.headers;if(!L(n)||Object.keys(n).length===0)return P("headers",'a credential needs "headers": an object with at least one header');let s={};for(let[i,h]of Object.entries(n)){if(!$e.test(i))return P("headers",`header name ${JSON.stringify(i)} is not a valid field name`);if(typeof h!="string"||Se.test(h))return P("headers",`header '${i}' must be a string without CR, LF or NUL`);s[i]=h}if(typeof e.scope!="string")return P("scope",'a credential needs a "scope" string');let o;try{o=v(e.scope)}catch(i){return P("scope",i.message)}if(!N(o,t.resource))return P("scope-excludes-resource",`scope '${e.scope}' does not contain the requested resource ${t.resource}`);let c;if(e.expiresAt!==void 0){if(typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt))return P("expires-at",'"expiresAt" must be a number of Unix seconds');if(e.expiresAt<=r)return P("expired",`the credential expired at ${e.expiresAt} (now ${Math.floor(r)})`);c=e.expiresAt}let p={status:"credential",headers:s,scope:e.scope};return c!==void 0&&(p.expiresAt=c),{ok:!0,answer:p}}function Re(t,e,r){return L(e)?e.version!==D?P("version",`"version" must be ${D}, not ${JSON.stringify(e.version)}`):U(t,e,r):P("malformed","the answer is not a JSON object")}function Te(t){return L(t)?t.version!==D?P("version",`"version" must be ${D}, not ${JSON.stringify(t.version)}`):t.status!=="erased"?P("status",`"status" must be "erased", not ${JSON.stringify(t.status)}`):{ok:!0,answer:{status:"erased"}}:P("malformed","the answer is not a JSON object")}function B(t){let e=new J(t),r=[];for(e.skipListSeparators();!e.atEnd();){let n=e.token();if(!n)throw e.error("expected an auth-scheme");let s={scheme:n,params:{}};r.push(s);let o=e.skipSpaces();if(e.atEnd()||e.peek()===","){e.skipListSeparators();continue}if(!o)throw e.error(`expected a space after the auth-scheme '${n}'`);let c=e.tryParam();if(c)for(ue(s,c,e);e.skipOws(),!e.atEnd();){if(e.peek()!==",")throw e.error('expected "," between auth-params');if(e.skipListSeparators(),e.atEnd())break;let p=e.pos,i=e.tryParam();if(!i){e.pos=p;break}ue(s,i,e)}else{let p=e.token68();if(!p)throw e.error(`expected a token68 or auth-params after '${n}'`);if(s.token68=p,e.skipOws(),!e.atEnd()&&e.peek()!==",")throw e.error("unexpected text after token68")}e.skipListSeparators()}return r}function ue(t,[e,r],n){if(Object.prototype.hasOwnProperty.call(t.params,e))throw n.error(`auth-param '${e}' appears twice in the '${t.scheme}' challenge`);t.params[e]=r}var ve=/[!#$%&'*+\-.^_`|~0-9A-Za-z]/,xe=/[A-Za-z0-9\-._~+/]/,J=class{constructor(e){this.s=e}s;pos=0;atEnd(){return this.pos>=this.s.length}peek(){return this.s[this.pos]}error(e){return new Error(`Malformed WWW-Authenticate (${e} at offset ${this.pos}): ${this.s}`)}skipSpaces(){let e=this.pos;for(;!this.atEnd()&&(this.peek()===" "||this.peek()===" ");)this.pos++;return this.pos>e}skipOws(){this.skipSpaces()}skipListSeparators(){for(;;){if(this.skipOws(),this.peek()!==",")return;this.pos++}}token(){let e=this.pos;for(;!this.atEnd()&&ve.test(this.peek());)this.pos++;return this.s.slice(e,this.pos)}token68(){let e=this.pos;for(;!this.atEnd()&&xe.test(this.peek());)this.pos++;if(this.pos===e)return"";for(;!this.atEnd()&&this.peek()==="=";)this.pos++;return this.s.slice(e,this.pos)}tryParam(){let e=this.pos,r=this.token();if(!r)return null;if(this.skipOws(),this.peek()!=="=")return this.pos=e,null;this.pos++,this.skipOws();let n;if(this.peek()==='"')n=this.quotedString();else if(n=this.token(),!n)return this.pos=e,null;return[r.toLowerCase(),n]}quotedString(){this.pos++;let e="";for(;;){if(this.atEnd())throw this.error("unterminated quoted-string");let r=this.s[this.pos++];if(r==='"')return e;if(r==="\\"){if(this.atEnd())throw this.error("unterminated quoted-pair");e+=this.s[this.pos++]}else e+=r}}};var ye=30;function _e(t,e={}){let r=e.discovery??new x,n=e.nowSeconds??(()=>Date.now()/1e3),s=[],o=new WeakSet,c=new Map,p=new Map,i=a=>{let d=n();return s=s.filter(u=>u.expiresAt===void 0||u.expiresAt-ye>d),V(s,a)},h=(a,d)=>{let u=(p.get(a)??Promise.resolve()).then(d);return p.set(a,u.then(()=>{},()=>{})),u},b=a=>{let d=c.get(a);return d||(d=r.protectedResourceMetadata(a).then(u=>u!==null,u=>{if(u instanceof I&&(u.status===401||u.status===403))return!0;throw new T(`Could not learn whether ${a} requires a credential: ${me(u)}`)}),c.set(a,d)),d},w=async(a,d)=>{let u=U(d,await le(()=>a.get(d),d.resource),n());if(!u.ok)throw new T(`The credential provider answered for ${d.resource} outside the protocol (${u.problem}): ${u.message}`);let y=u.answer;if(y.status==="declined")return y.reason===void 0?{}:{declined:y.reason};let f={headers:y.headers,scope:y.scope};return y.expiresAt!==void 0&&(f.expiresAt=y.expiresAt),s=s.filter(l=>l.scope!==f.scope),s.push(f),f},g=(a,d,u)=>j(a,{method:d,redirect:"manual",headers:u?.headers??{}});return async(a,d,u="GET")=>{let y=new URL(a).origin,f=i(a);if(!f&&t&&await b(y)){let k=await h(y,async()=>i(a)??w(t,{resource:a,method:u}));fe(k)&&(f=k)}let l=await g(a,u,f);if(l.status!==401&&l.status!==403)return l;let A=ge(l,a),m=l.status===401;if(!m&&!he(A))return l;if(c.set(y,Promise.resolve(!0)),!t)throw await Y(`${a} requires a credential, and no credential provider is configured`,l);let C={resource:a,method:u,challenges:A},R=await h(y,async()=>{let k=i(a);if(k&&k!==f)return k;if(m&&f&&!o.has(f)){o.add(f);let Q=f;s=s.filter(we=>we!==Q),await le(()=>t.erase({...C,scope:Q.scope}),a)}return w(t,C)});if(!fe(R)){let k=R.declined?`: ${R.declined}`:"";throw await Y(`${a} requires a credential, and the credential provider declined${k}`,l)}let E=await g(a,u,R);if(E.status===401||E.status===403&&he(ge(E,a)))throw await Y(`${a} rejected the credential for ${R.scope} after asking the provider again`,E);return E}}async function le(t,e){try{return await t()}catch(r){throw r instanceof T?r:new T(`The credential provider failed for ${e}: ${me(r)}`)}}function me(t){return t instanceof Error?t.message:String(t)}function fe(t){return"scope"in t}function he(t){return t.some(e=>e.params.error==="insufficient_scope")}function ge(t,e){let r=t.headers.get("www-authenticate");if(!r)return[];try{return B(r)}catch(n){throw new T(`${e} answered ${t.status} with a challenge that cannot be read: ${n.message}`)}}async function Y(t,e){return new T(`${t}. The server answered ${await ee(e)}`)}var F="KANONAK_TOKEN";function Ne(){return typeof process<"u"&&process.env?process.env:{}}function Z(t){return`${F}_${M(t).toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}var X=class{tokens;env;discovery;constructor(e={}){this.tokens=e.tokens??{},this.env=e.env??Ne(),this.discovery=e.discovery??new x}async get(e){let r=await this.metadataFor(e);if("declined"in r)return{status:"declined",reason:r.declined};let n=r.metadata;if(n.authorizationServers.length===0)return{status:"declined",reason:`the protected-resource metadata for ${n.resource} names no authorization server`};let s=n.authorizationServers.map(o=>new URL(o).host);for(let o of s){let c=this.tokens[o]??this.env[Z(o)]??this.env[F];if(c)return{status:"credential",headers:{Authorization:`Bearer ${c}`},scope:n.resource}}return{status:"declined",reason:`no token is configured for ${s.join(" or ")}: set ${s.map(Z).join(" or ")}, or ${F}`}}async erase(){}async metadataFor(e){let r=e.challenges?.find(o=>o.params.resource_metadata!==void 0)?.params.resource_metadata;if(r!==void 0)return{metadata:await this.discovery.protectedResourceMetadataAt(r,e.resource)};let n=new URL(e.resource).origin,s;try{s=await this.discovery.protectedResourceMetadata(n)}catch(o){if(o instanceof I&&(o.status===401||o.status===403))return{declined:`${n} requires a credential even for its protected-resource metadata, and its challenge names no resource_metadata`};throw o}return s?{metadata:s}:{declined:`${n} publishes no RFC 9728 protected-resource metadata naming its authorization server, so no token is presented to it`}}};export{se as a,ae as b,H as c,M as d,v as e,N as f,V as g,Oe as h,x as i,D as j,U as k,Re as l,Te as m,B as n,ye as o,_e as p,F as q,Z as r,X as s};
@@ -0,0 +1 @@
1
+ import{o as i,p as r,q as t,u as o,v as s}from"./chunk-AEH3NZLH.js";import{readFileSync as c,writeFileSync as u,existsSync as a}from"fs";import{createHash as d}from"crypto";var l="kanonak.lock";function g(e=l){return a(e)?r(c(e,"utf-8")):null}function k(e,n=l){e.lastUpdated=new Date().toISOString(),u(n,t(e),"utf-8")}function y(e){let n=d("sha256").update(e).digest("hex");return`${i}${n}`}import{readFileSync as f,writeFileSync as x,existsSync as p}from"fs";function v(e){return p(e)?o(f(e,"utf-8"),e):null}function w(e,n){x(n,s(e),"utf-8")}export{g as a,k as b,y as c,v as d,w as e};
package/dist/index.d.ts CHANGED
@@ -35,8 +35,8 @@ export type { PackageUrlTemplatesConfigOptions } from './config/packageUrlTempla
35
35
  export { kanonakFetch, assertHttpsUrl, setKanonakFetchRetries, setKanonakUserAgent, getKanonakUserAgent, KANONAK_USER_AGENT, } from './http/kanonakFetch.js';
36
36
  export { KanonakHttpError, httpError, describeResponse, retryAfterSecondsOf } from './http/HttpError.js';
37
37
  export type { ProblemDetails } from './http/HttpError.js';
38
- export { loadLockFile, saveLockFile, computeIntegrity, parseLockFile, serializeLockFile, computeIntegrityAsync, assertIntegrityAsync, lockedVersion, INTEGRITY_PREFIX, } from './lock/index.js';
39
- export type { LockFile, LockEntry } from './lock/index.js';
38
+ export { loadLockFile, saveLockFile, computeIntegrity, parseLockFile, serializeLockFile, computeIntegrityAsync, assertIntegrityAsync, lockedVersion, INTEGRITY_PREFIX, VERSION_INDEX_FILE, parseVersionIndex, serializeVersionIndex, indexedVersion, planVersionIndex, setYanked, loadVersionIndex, saveVersionIndex, } from './lock/index.js';
39
+ export type { LockFile, LockEntry, VersionIndex, IndexedVersion, PublishedSource, VersionIndexChange, VersionIndexRefusal, VersionIndexPlan, } from './lock/index.js';
40
40
  export { findDerivation } from './derivation/index.js';
41
41
  export type { DerivationEntityUri, TransformationReferenceTuple, DerivationLookupResult, } from './derivation/index.js';
42
42
  export { LookRenderer, resolveDisplayValue, URI_DISPLAY_LABEL, URI_DISPLAY_SUMMARY, supportedBandKeys } from './look/index.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as Xt,b as Yt,c as Qt,d as Jt,e as z}from"./chunk-IXCD4K3K.js";import{a as to,b as ro,c as ao}from"./chunk-6PIWCHH6.js";import{a as Bt,b as Gt,c as zt,d as sa,e as ca,f as da,g as ua,h as la,i as pa,j as Ze,k as fa,l as en,m as nn,n as ma,o as ha,p as Sa,q as ve,r as ga,s as on}from"./chunk-MUXGPSUC.js";import{a as ka}from"./chunk-FYAZ345F.js";import{a as oa,b as ta,c as ra,d as ne,e as aa,f as ia,g as Je,h as ya,i as Ea,j as Ca,k as ba,l as _a}from"./chunk-4NTZY2KP.js";import{a as Wo,b as qo,c as Bo,d as Go,e as zo,f as mt,g as ht,h as gt,i as kt}from"./chunk-DFXL2C6U.js";import{a as Zo,b as et,c as nt,d as ot,e as tt,f as rt,g as Me,h as Ue,i as $e,j as ct,k as dt,m as ut,n as Sn,o as gn,p as kn,q as yn,r as En,s as Cn,t as lt,u as ft}from"./chunk-DAWT3ZAM.js";import{a as Zt,b as er,c as nr,d as or,e as tr,f as rr}from"./chunk-C5HHCD6P.js";import{a as ar,b as sr}from"./chunk-TR7PC72M.js";import{a as pt}from"./chunk-SC5M74NM.js";import{A as xr,B as Ir,C as Lr,D as Mr,E as Ur,F as $r,G as Vr,H as Hr,I as Xr,J as Yr,K as Qr,L as Jr,M as Zr,N as ea,O as na,a as cr,b as dr,c as ur,d as lr,e as pr,f as Jn,g as Zn,h as fr,i as mr,j as hr,k as Sr,l as gr,m as kr,n as yr,o as Er,p as Cr,q as br,r as _r,s as Pr,t as Rr,u as vr,v as wr,w as Kr,x as Or,y as Nr,z as Ar}from"./chunk-IZBZDLCX.js";import{a as Yn,b as Qn}from"./chunk-QRF7AT2M.js";import{c as eo,d as jr,e as Tr,f as Dr,g as Fr,i as Wr,j as qr,m as Br,o as Qe,q as no,s as oo,u as Gr,v as zr}from"./chunk-A4OVTNMT.js";import"./chunk-QHABFCRC.js";import{a as Xo,b as Yo,c as Qo,d as Jo,e as L}from"./chunk-5FVUBF7N.js";import{a as Le}from"./chunk-YEUSFSC7.js";import{a as Xe,g as T,h as Ye,i as Wt,j as qt,k as U}from"./chunk-A5EAI5ZU.js";import{a as X}from"./chunk-VAZY57HJ.js";import{a as ir}from"./chunk-PEJALHXK.js";import{$ as Re,A as Un,B as $n,C as Vn,D as Hn,E as jn,F as Tn,G as Dn,H as Fn,I as Wn,J as qn,K as De,L as Bn,M as Gn,N as zn,O as me,P as he,Q as Se,R as ge,S as ke,T as ye,U as Ee,V as Ce,W as be,X as _e,Y as Pe,Z,_ as Xn,a as At,aa as Fe,b as xt,ba as We,c as Q,ca as W,d as Lt,da as H,e as Mt,ea as j,fa as q,g as Ut,ga as qe,h as le,i as pe,j as _n,ja as $t,k as J,ka as Vt,l as fe,m as Pn,ma as Ht,n as Rn,o as je,oa as jt,p as vn,pa as E,q as wn,qa as Ge,r as Kn,ra as Tt,s as On,sa as ze,t as Te,u as Nn,v as An,va as Dt,w as xn,wa as Ft,x as In,xa as G,y as Ln,z as Mn}from"./chunk-TVMOJ2QS.js";import{B as F,C as A,D as ue,E as k,F as Y,G as He,H as ee,I as B,K as Be,a as yt,b as Et,c as g,d as M,e as O,f as Ct,g as bt,h as _t,i as Pt,j as Rt,k as vt,l as wt,m as Kt,n as Ot,o as Nt,p,s as It,t as D,u as Ve,v as bn,w as de,y as N}from"./chunk-6USORWEP.js";import"./chunk-F67UH4FD.js";import{a as Mo,b as Uo,c as ce,d as $o,e as V,f as Vo,g as Ho,h as jo,i as To,j as Do,k as Fo,l as at,m as it,n as st}from"./chunk-7IMLHHSA.js";import"./chunk-BA5J2DKJ.js";import{a as St}from"./chunk-PC3DHZGV.js";async function io(n){let e=await new U().parseKanonaks(n);return{kind:"merged",catalog:e,reasoning:new z().reasonOver(e)}}async function so(n,e){let t=new Set(n.map(oe)),o=new Set,a=[];if(await Yn(n,e,{onDocument:l=>o.add(oe(l)),onUnresolvedEdge:l=>a.push(l)}),a.length>0){let l=a.map(h=>`${h.fromNamespace} imports ${h.publisher}/${h.packageName} ${h.constraint} (${h.reason})`);throw new Error(`Cannot build the conformance scope: ${a.length} import(s) did not resolve:
1
+ import{a as tr,b as rr,c as ir,d as ar,e as z}from"./chunk-IXCD4K3K.js";import{a as uo,b as lo,c as po,d as fo,e as mo}from"./chunk-RXIKK3KZ.js";import{a as er,b as nr,c as or,d as hi,e as Si,f as gi,g as ki,h as yi,i as Ei,j as Ze,k as Ci,l as en,m as nn,n as bi,o as _i,p as Pi,q as ve,r as Ri,s as on}from"./chunk-RFSARH5S.js";import{a as vi}from"./chunk-FYAZ345F.js";import{a as ui,b as li,c as pi,d as ne,e as fi,f as mi,g as Je,h as wi,i as xi,j as Ki,k as Ii,l as Oi}from"./chunk-4NTZY2KP.js";import{a as Jo,b as Zo,c as et,d as nt,e as ot,f as bt,g as _t,h as Rt,i as vt}from"./chunk-7PTZF5LK.js";import{A as Ct,a as st,b as ct,c as dt,d as ut,e as lt,f as pt,g as Ve,h as Me,i as Ue,j as St,k as gt,m as kt,n as Sn,o as gn,p as kn,q as yn,r as En,s as Cn,t as bn,u as _n,v as Pn,w as Rn,x as vn,y as wn,z as yt}from"./chunk-AEH3NZLH.js";import{a as sr,b as cr,c as dr,d as ur,e as lr,f as pr}from"./chunk-C5HHCD6P.js";import{a as fr,b as hr}from"./chunk-TR7PC72M.js";import{a as Et}from"./chunk-SC5M74NM.js";import{A as jr,B as Dr,C as Tr,D as Fr,E as Wr,F as qr,G as Br,H as Gr,I as ti,J as ri,K as ii,L as ai,M as si,N as ci,O as di,a as Sr,b as gr,c as kr,d as yr,e as Er,f as ro,g as io,h as Cr,i as br,j as _r,k as Pr,l as Rr,m as vr,n as wr,o as xr,p as Kr,q as Ir,r as Or,s as Nr,t as Ar,u as Lr,v as Vr,w as Mr,x as Ur,y as $r,z as Hr}from"./chunk-IZBZDLCX.js";import{a as oo,b as to}from"./chunk-QRF7AT2M.js";import{c as ao,d as zr,e as Xr,f as Yr,g as Qr,i as Jr,j as Zr,m as ei,o as Qe,q as so,s as co,u as ni,v as oi}from"./chunk-A4OVTNMT.js";import"./chunk-QHABFCRC.js";import{a as tt,b as rt,c as it,d as at,e as L}from"./chunk-5FVUBF7N.js";import{a as Le}from"./chunk-YEUSFSC7.js";import{a as Xe,g as D,h as Ye,i as Jt,j as Zt,k as M}from"./chunk-A5EAI5ZU.js";import{a as X}from"./chunk-VAZY57HJ.js";import{a as mr}from"./chunk-PEJALHXK.js";import{$ as Re,A as Tn,B as Fn,C as Wn,D as qn,E as Bn,F as Gn,G as zn,H as Xn,I as Yn,J as Qn,K as Te,L as Jn,M as Zn,N as eo,O as me,P as he,Q as Se,R as ge,S as ke,T as ye,U as Ee,V as Ce,W as be,X as _e,Y as Pe,Z,_ as no,a as Ht,aa as Fe,b as jt,ba as We,c as Q,ca as W,d as Tt,da as H,e as Ft,ea as j,fa as q,g as Wt,ga as qe,h as le,i as pe,j as Kn,ja as qt,k as J,ka as Bt,l as fe,m as In,ma as Gt,n as On,o as je,oa as zt,p as Nn,pa as E,q as An,qa as Ge,r as Ln,ra as Xt,s as Vn,sa as ze,t as De,u as Mn,v as Un,va as Yt,w as $n,wa as Qt,x as Hn,xa as G,y as jn,z as Dn}from"./chunk-TVMOJ2QS.js";import{B as F,C as O,D as ue,E as k,F as Y,G as He,H as ee,I as B,K as Be,a as wt,b as xt,c as g,d as V,e as K,f as Kt,g as It,h as Ot,i as Nt,j as At,k as Lt,l as Vt,m as Mt,n as Ut,o as $t,p,s as Dt,t as T,u as $e,v as xn,w as de,y as I}from"./chunk-6USORWEP.js";import"./chunk-F67UH4FD.js";import{a as Fo,b as Wo,c as ce,d as qo,e as $,f as Bo,g as Go,h as zo,i as Xo,j as Yo,k as Qo,l as ft,m as mt,n as ht}from"./chunk-7IMLHHSA.js";import"./chunk-BA5J2DKJ.js";import{a as Pt}from"./chunk-PC3DHZGV.js";async function ho(n){let e=await new M().parseKanonaks(n);return{kind:"merged",catalog:e,reasoning:new z().reasonOver(e)}}async function So(n,e){let t=new Set(n.map(oe)),o=new Set,i=[];if(await oo(n,e,{onDocument:l=>o.add(oe(l)),onUnresolvedEdge:l=>i.push(l)}),i.length>0){let l=i.map(h=>`${h.fromNamespace} imports ${h.publisher}/${h.packageName} ${h.constraint} (${h.reason})`);throw new Error(`Cannot build the conformance scope: ${i.length} import(s) did not resolve:
2
2
  ${l.join(`
3
- `)}`)}let r=new Qn(e,o),d=new Set((await r.getAllDocumentsAsync()).map(oe)),i=[...t].filter(l=>!d.has(l));if(i.length>0)throw new Error(`scopeFromClosureAsync: ${i.join(", ")} is not a document of the repository the closure is resolved through.`);let c={},u=await new U().parseKanonaks(r,c),s=c.authored.filter(l=>l instanceof g&&t.has(l.sourceDoc)),f=new Set(s.map(B)),m=await Pa(n,s,e);return{kind:"merged",catalog:u,reasoning:new z().reasonOver(u),focus:f,links:m}}async function Pa(n,e,t){let o=[],a=new Map,r=new Map;for(let d of n){let i=oe(d),c=e.filter(u=>u.sourceDoc===i);for(let{key:u,references:s,target:f,failure:m}of await Jn(d,c,t)){let l=f?oe(f):void 0;if(r.has(u)&&r.get(u)!==l)throw new Error(`scopeFromClosureAsync: the seeds link ${u} at different versions (${r.get(u)??"unresolved"} and ${l??"unresolved"}); judge them in separate scopes.`);r.has(u)||(r.set(u,l),f&&o.push(...await new U().parseKanonaks(new Be(f,t))));for(let{uri:h}of s)f?Zn(f,h.name)||a.set(p(h),`${l} defines no resource named '${h.name}'`):a.set(p(h),`its package ${u} could not be resolved${m?` (${m})`:""}`)}}return r.size>0?{subjects:o,unresolved:a}:void 0}function oe(n){let e=n.metadata?.namespace_;if(!e)throw new Error("scopeFromClosureAsync: a document has no namespace, so it cannot be identified.");return e.toString()}function co(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function uo(n,e){let t=e??new Le(new X);return{kind:"standalone",catalog:await new U().parseKanonaks(new Be(n,t))}}function $(n){return typeof n=="number"?n:void 0}function Ra(n){if(!n)return;let e=p(n);if(e===p(Fn))return"IRI";if(e===p(Wn))return"BlankNode";if(e===p(qn))return"Literal"}function po(n){if(!n)return;let e=p(n);if(e===p(Bn))return"Violation";if(e===p(Gn))return"Warning";if(e===p(zn))return"Info"}function fo(n,e,t,o){let a=k(e,je);if(!a)return;let r={path:a},d=$(A(e,vn)),i=$(A(e,wn));d!==void 0&&(r.minCount=d),i!==void 0&&(r.maxCount=i);let c=$(A(e,xn)),u=$(A(e,In));c!==void 0&&(r.minLength=c),u!==void 0&&(r.maxLength=u);let s=$(A(e,Ln)),f=$(A(e,Mn));s!==void 0&&(r.minInclusive=s),f!==void 0&&(r.maxInclusive=f);let m=ue(e,Nn);if(m!==void 0){let S=ue(e,An);r.pattern=S!==void 0?{regex:m,flags:S}:{regex:m}}if(F(e,Te)){let S=[],K=[];for(let{item:C}of Ve(e,Te))"literal"in C?S.push(C.value):C instanceof O&&K.push(C.subject);S.length>0&&(r.inValues=S),K.length>0&&(r.inRefs=K)}let l=k(e,Kn);l&&(r.datatype=l);let h=k(e,On);h&&(r.classRef=h);let y=Ra(k(e,Dn));y&&(r.nodeKind=y);let R=k(e,Xn);if(R&&(r.hasValue=R),F(e,Re)||F(e,Fe)||F(e,We)){let S={},K=$(A(e,Fe)),C=$(A(e,We));K!==void 0&&(S.minCount=K),C!==void 0&&(S.maxCount=C);let x=va(n,e,o);"problem"in x?S.problem=x.problem:S.shape=x.shape,r.qualified=S}let v=ue(e,Un);v!==void 0&&(r.message=v);let w=po(k(e,De))??t;return w&&(r.severity=w),r}function va(n,e,t){let o=Y(e,Re);if(o)return lo(n,o,void 0,t);let a=k(e,Re);if(!a)return{problem:"sh:qualifiedValueShape is missing"};let r=p(a);if(t.has(r))return{problem:`sh:qualifiedValueShape '${a.name}' leads back to itself (a cycle through named shapes)`};let d=N(n,a);return d?lo(n,d,r,t):{problem:`sh:qualifiedValueShape '${a.name}' does not resolve`}}function lo(n,e,t,o){let a=t?new Set([...o,t]):o,r=de(e,J);if((de(e,fe)||F(e,je))&&!r){let c=fo(n,e,void 0,a);return c?{shape:{kind:"property",constraint:c}}:{problem:"the qualified property shape has no sh:path"}}return e instanceof g&&!r?{problem:`sh:qualifiedValueShape '${e.name}' is not a shape`}:{shape:{kind:"node",shape:mo(n,e,a)}}}function mo(n,e,t){let o=po(k(e,De)),a={name:e instanceof g?e.name:"(inline shape)",uri:e instanceof g?E(e):void 0,targetClass:k(e,Pn),targetNodes:D(e,$n),targetSubjectsOf:D(e,Vn),targetObjectsOf:D(e,Hn),closed:A(e,jn)===!0,ignoredProperties:[],severity:o,properties:[]};a.ignoredProperties.push(...D(e,Tn));for(let{item:r}of Ve(e,Rn)){let d;if(r instanceof M?d=r:r instanceof O&&(d=N(n,r.subject)),!d)continue;let i=fo(n,d,o,t);i&&a.properties.push(i)}return a}function we(n){let e=[];for(let t of n){if(!(t instanceof g)||!de(t,J))continue;let o=E(t);e.push(mo(n,t,new Set(o?[p(o)]:[])))}return e}function Ke(n){let e=new Map;for(let t of n)if(t instanceof g)for(let o of bn(t,qe)){let a=E(t);if(!a)throw new Error(`owl.hasKey on '${t.namespace}/${t.name}': the class has no resolvable URI.`);if(o.length===0)throw new Error(`owl.hasKey on '${t.name}' lists no properties; a key needs at least one.`);let r=o.map(({item:d})=>{let i=d instanceof O?N(n,d.subject):void 0;if(!i||!ze(n,i)){let c=d instanceof O?`'${p(d.subject)}'`:"a value that is not a reference";throw new Error(`owl.hasKey on '${t.name}' lists ${c}, which is not a property defined in scope; a key lists properties.`)}return d.subject});e.set(`${p(a)}|${r.map(p).join(",")}`,{classUri:a,className:t.name,properties:r})}return[...e.values()]}var _="kanonak.org/transformations",te="values";var Oe="allowed",rn="expected",b=n=>({type:`${_}/VarRef`,varName:n}),tn=n=>({type:`${_}/IntegerLiteral`,integerLiteral:n}),wa=n=>({type:`${_}/DecimalLiteral`,decimalLiteral:n}),ho=n=>Number.isInteger(n)?tn(n):wa(n),So=n=>({type:`${_}/Count`,source:n}),go=(n,e)=>({type:`${_}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),ko=(n,e)=>({type:`${_}/LessThanOrEqual`,compareLeft:n,compareRight:e});function an(n,e){if(!e||e.length===0)return n;let t=new Set(["i","m","s"]),o=[...new Set(e.split(""))];if(o.filter(r=>!t.has(r)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${o.sort().join("")})${n}`}function Ne(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:go(So(b(te)),tn(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:ko(So(b(te)),tn(n.maxCount))}),n.hasValue!==void 0&&e.push({component:"hasValue",per:"node",expr:{type:`${_}/Contains`,haystack:b(te),needle:b(rn)}}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${_}/Contains`,haystack:b(Oe),needle:b("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${_}/Matches`,matchSource:b("v"),pattern:an(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${_}/Matches`,matchSource:b("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${_}/Matches`,matchSource:b("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:go(b("v"),ho(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:ko(b("v"),ho(n.maxInclusive))}),e}import{evaluate as Oa,ExpressionError as Na}from"@kanonak-protocol/expression";function Co(n,e){let t=yo(e)?e:we(e),o=[],a=n.catalog.filter(c=>c instanceof g).map(Ae),r=new Map;Aa(a,r);let d=n.links?[...n.catalog,...n.links.subjects]:n.catalog,i={scope:n,membership:new cn(n),values:d,embeddedFocus:r};for(let c of t)for(let u of xa(i,c,a))sn(n,u)&&_o(i,c,u,o);if(!yo(e))for(let c of Ke(e))Ia(i,c,a,o);return{conforms:!o.some(c=>c.severity==="Violation"),results:o}}function yo(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function bo(n){let e=n.predicate;return e instanceof O?e:void 0}function sn(n,e){return!n.focus||e.subject!==void 0&&n.focus.has(e.subject)}function Ae(n){let e=B(n);return{node:n,key:e,uri:E(n),subject:e,label:n.name}}function un(n,e,t){return{node:n,key:e,subject:t,label:e.includes("#")?e.slice(e.indexOf("#")):e}}function Aa(n,e){for(let t of n)Xe([t.node],({kanonak:o,address:a})=>{o instanceof M&&!e.has(o)&&e.set(o,un(o,a,t.subject))})}var cn=class{constructor(e){this.scope=e}scope;ancestors=new Map;defined;defines(e){return this.defined??=new Set(this.scope.catalog.filter(t=>t instanceof g).map(B)),this.defined.has(p(e))}isInstance(e,t){let o=p(t);return e.some(a=>p(a)===o||this.ancestorsOf(a).has(o))}ancestorsOf(e){let t=e.version&&typeof e.version.major=="number"?`${p(e)}@${V(e.version)}`:p(e),o=this.ancestors.get(t);return o||(o=this.scope.reasoning?new Set(this.scope.reasoning.getSuperclasses(e)):new Set(Ge(this.scope.catalog,e).map(a=>p(a))),this.ancestors.set(t,o)),o}};function xa(n,e,t){let{scope:o}=n,a=new Map,r=i=>{a.set(i.key,i)},d=()=>[...t,...n.embeddedFocus.values()];if(e.targetClass){let i=e.targetClass;for(let c of d())n.membership.isInstance(G(c.node),i)&&r(c)}for(let i of e.targetNodes){let c=N(o.catalog,i);c instanceof g&&r(Ae(c))}for(let i of e.targetSubjectsOf){let c=p(i);for(let u of d())u.node.statement.some(s=>{let f=bo(s);return f&&p(f.subject)===c})&&r(u)}for(let i of e.targetObjectsOf)for(let c of d())for(let u of ee(c.node,i,o.catalog,c.key))u.kind==="subject"?r(Ae(u.node)):u.kind==="embedded"&&r(n.embeddedFocus.get(u.node)??un(u.node,u.address,c.subject));return[...a.values()]}function Ia(n,e,t,o){let a=new Map;for(let c of t)n.membership.isInstance(G(c.node),e.classUri)&&a.set(c.key,c);let r=[];for(let c of[...a.values()].sort((u,s)=>u.key<s.key?-1:u.key>s.key?1:0)){let u=e.properties.map(s=>La(n,c,s));u.every(s=>s.size>0)&&r.push({focus:c,values:u})}let d=new Map;r.forEach(({values:c},u)=>{for(let s of c[0].keys()){let f=d.get(s);f?f.push(u):d.set(s,[u])}});let i=new Set;for(let c of d.values())for(let u=0;u<c.length;u++)for(let s=u+1;s<c.length;s++){let f=`${c[u]}:${c[s]}`;if(i.has(f))continue;let m=r[c[u]],l=r[c[s]],h=m.values.map((w,S)=>[...w.keys()].find(K=>l.values[S].has(K)));if(h.some(w=>w===void 0))continue;i.add(f);let[y,R]=sn(n.scope,m.focus)?[m.focus,l.focus]:sn(n.scope,l.focus)?[l.focus,m.focus]:[void 0,void 0];if(!y||!R)continue;let v=e.properties.map((w,S)=>`${w.name} = ${m.values[S].get(h[S])}`).join(", ");o.push({focusNode:y.key,focusUri:y.uri,valueRef:R.uri,constraintComponent:q,severity:"Violation",message:`'${y.label}' and '${R.label}' are distinct instances of ${e.className} with the same key (${v}); its owl.hasKey makes the key unique.`})}}function La(n,e,t){let o=new Map;for(let a of ee(e.node,t,n.scope.catalog,e.key))switch(a.kind){case"subject":case"unresolved":o.set(`ref:${p(a.uri)}`,a.uri.name);break;case"literal":o.set(`${typeof a.value}:${String(a.value)}`,JSON.stringify(a.value));break;case"embedded":break}return o}function Ma(n,e,t){return e.node?ee(e.node,t,n.values,e.key).map(o=>Ua(n,o,e.subject)):[]}function Ua(n,e,t){switch(e.kind){case"subject":return{kernel:{ref:p(e.uri)},kind:"reference",ref:e.uri,subject:e.node};case"unresolved":return{kernel:{ref:p(e.uri)},kind:"reference",ref:e.uri};case"embedded":{let o=n.embeddedFocus.get(e.node)??un(e.node,e.address,t);return{kernel:{ref:o.key},kind:"embedded",embedded:o}}case"literal":return typeof e.value=="boolean"?{kernel:e.value?1:0,kind:"boolean",literal:e.value}:{kernel:e.value,kind:typeof e.value=="number"?"number":"string",literal:e.value}}}function _o(n,e,t,o){for(let a of e.properties)Ro(n,e,t,a,o);e.closed&&Ga(e,t,o)}function dn(n,e,t,o,a={},r){return{focusNode:e.key,focusUri:e.uri,constraintComponent:t,severity:r??Po(n),message:o,sourceShape:n.name,sourceShapeUri:n.uri,...a}}function Po(n){return n.severity??"Violation"}var $a={minCount:me,maxCount:he,hasValue:W,in:ke,pattern:ye,minLength:Ee,maxLength:Ce,minInclusive:be,maxInclusive:_e};function Ro(n,e,t,o,a){let r=Ma(n,t,o.path),d=o.severity??Po(e),i=o.path.name,c=[...(o.inValues??[]).map(s=>typeof s=="boolean"?s?1:0:s),...(o.inRefs??[]).map(s=>({ref:p(s)}))],u=(s,f,m)=>{let l=dn(e,t,s,o.message??f,{resultPath:o.path,value:m?.literal,valueRef:m?.ref},d);return a.push(l),l};for(let s of Ne(o)){let f=$a[s.component];if(s.per==="node"){let m={[te]:r.map(l=>l.kernel),[Oe]:c};o.hasValue&&(m[rn]={ref:p(o.hasValue)}),Eo(s,m)||u(f,Va(s,i,o,r.length));continue}for(let m of r){if((s.component==="pattern"||s.component==="minLength"||s.component==="maxLength")&&m.kind!=="string"){u(f,`'${i}' value is not a string; ${s.component} applies to string values.`,m);continue}Eo(s,{v:m.kernel,[Oe]:c})||u(f,Fa(s,i,o,m),m)}}if(o.nodeKind)for(let s of r)Wa(o.nodeKind,s)||u(Pe,`'${i}' value is ${s.kind}; nodeKind requires ${o.nodeKind}.`,s);if(o.datatype)for(let s of r){let f=qa(o.datatype,s);f&&u(Se,`'${i}' ${f}`,s)}if(o.classRef)for(let s of r){let f=Ba(n,o.classRef,s);f&&u(ge,`'${i}' ${f}`,s)}o.qualified&&Ha(n,o,r,i,u)}function Va(n,e,t,o){switch(n.component){case"minCount":return`'${e}' has ${o} value(s); minCount is ${t.minCount}.`;case"maxCount":return`'${e}' has ${o} value(s); maxCount is ${t.maxCount}.`;case"hasValue":return`'${e}' has no value equal to ${t.hasValue?p(t.hasValue):"(unset)"}.`;default:return`'${e}' violates ${n.component}.`}}function Ha(n,e,t,o,a){let r=e.qualified,d=r.maxCount!==void 0?j:H,i=(u,s)=>{vo.add(a(d,u,s))};if(!r.shape){i(`'${o}' qualified value shape cannot be evaluated: ${r.problem??"it could not be built"}.`);return}let c=0;for(let u of t){let s=u.ref?p(u.ref):u.embedded?u.embedded.label:JSON.stringify(u.literal),f=ja(n,u);if(!f){i(`'${o}' value ${s} does not resolve in this scope; whether it conforms to the qualified shape cannot be decided.`,u);continue}let m=Da(n,r.shape,f);if(m.kind==="undecided"){i(`'${o}' value ${s}: whether it conforms to the qualified shape cannot be decided \u2014 ${m.reason}`,u);continue}m.kind==="conforms"&&c++}r.minCount!==void 0&&c<r.minCount&&a(H,`'${o}' has ${c} value(s) that conform to the qualified shape; qualifiedMinCount is ${r.minCount}.`),r.maxCount!==void 0&&c>r.maxCount&&a(j,`'${o}' has ${c} value(s) that conform to the qualified shape; qualifiedMaxCount is ${r.maxCount}.`)}function ja(n,e){switch(e.kind){case"reference":return e.subject?Ae(e.subject):void 0;case"embedded":return e.embedded;default:{let t=JSON.stringify(e.literal);return{key:t,label:t}}}}var Ta={name:"(qualified value shape)",targetNodes:[],targetSubjectsOf:[],targetObjectsOf:[],closed:!1,ignoredProperties:[],properties:[]},vo=new WeakSet;function Da(n,e,t){let o=[];e.kind==="property"?Ro(n,Ta,t,e.constraint,o):_o(n,e.shape,t,o);let a=o.find(r=>vo.has(r));return a?{kind:"undecided",reason:a.message}:o.length===0?{kind:"conforms"}:{kind:"fails"}}function Fa(n,e,t,o){let a=o.ref?p(o.ref):o.embedded?o.embedded.label:JSON.stringify(o.literal);switch(n.component){case"in":return`'${e}' value ${a} is not in the permitted set.`;case"pattern":return`'${e}' value ${a} does not match pattern ${t.pattern?.regex}.`;case"minLength":return`'${e}' value ${a} is shorter than minLength ${t.minLength}.`;case"maxLength":return`'${e}' value ${a} is longer than maxLength ${t.maxLength}.`;case"minInclusive":return`'${e}' value ${a} is below minInclusive ${t.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${a} is above maxInclusive ${t.maxInclusive} (or not numeric).`;default:return`'${e}' value ${a} violates ${n.component}.`}}function Eo(n,e){let t=o=>{let a=o.varName;if(o.type==="kanonak.org/transformations/VarRef"&&typeof a=="string"&&a in e)return e[a];throw new Na(`Conformance lowering produced an unexpected leaf '${o.type}'`)};return Oa(n.expr,void 0,t)===1}function Wa(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function qa(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let t=Ye(n);if(t!==void 0)switch(t){case T.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case T.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case T.Decimal:case T.Double:case T.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function Ba(n,e,t){if(t.kind==="embedded"&&t.embedded?.node){let d=G(t.embedded.node);return d.length===0?`value ${t.embedded.label} has no type; sh:class requires an instance of ${e.name}.`:n.membership.isInstance(d,e)?void 0:`value ${t.embedded.label} is not an instance of ${e.name}.`}if(t.kind!=="reference"||!t.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;let o=t.subject;if(!o){let d=n.scope.links?.unresolved.get(p(t.ref));return d?`value ${p(t.ref)} is a link that does not dereference: ${d} (sh:class ${e.name}).`:`value ${p(t.ref)} does not resolve in this scope (sh:class ${e.name}).`}let a=G(o);if(n.membership.isInstance(a,e))return;let r=a.filter(d=>!n.membership.defines(d));return r.length>0?`value ${p(t.ref)} is typed ${r.map(p).join(", ")}, which this scope does not define, so it cannot be shown to be an instance of ${e.name}. A class is in scope when the judged document imports the package that defines it.`:`value ${p(t.ref)} is not an instance of ${e.name}.`}function Ga(n,e,t){if(!e.node)return;let o=new Set([...n.properties.map(r=>p(r.path)),...n.ignoredProperties.map(r=>p(r))]),a=new Set;for(let r of e.node.statement){let d=bo(r);if(!d)continue;let i=p(d.subject);o.has(i)||a.has(i)||(a.add(i),t.push(dn(n,e,Z,`'${e.label}' carries undeclared property '${d.subject.name}' (closed shape).`,{resultPath:d.subject})))}for(let r of e.node.unresolvedPredicates)a.has(r.key)||(a.add(r.key),t.push(dn(n,e,Z,`'${e.label}' carries unresolvable property '${r.key}' (closed shape).`,{value:r.key})))}var za="1.1.0",Xa=new Set([W,H,j].map(n=>n.name)),Ya=new Set([q].map(n=>n.name));function Qa(n){let e=new Set(n.results.map(t=>t.constraintComponent.name));return[...e].some(t=>Ya.has(t))?"1.3.0":[...e].some(t=>Xa.has(t))?"1.2.0":za}async function wo(n){let e=new ne(n.repository),t=e.imports(),o=t.ensure(le,pe,Qa(n.result),"sh"),a=(i,c)=>i&&i.version&&typeof i.version.major=="number"?`${t.ensure(i.publisher,i.package_,V(i.version),i.package_)}.${i.name}`:c,r={},d=[];return n.result.results.forEach((i,c)=>{let u=`result-${c+1}`;d.push(u);let s={type:`${o}.ValidationResult`,[`${o}.focusNode`]:a(i.focusUri,i.focusNode),[`${o}.resultMessage`]:i.message,[`${o}.resultSeverity`]:`${o}.${i.severity}`,[`${o}.sourceConstraintComponent`]:`${o}.${i.constraintComponent.name}`};i.resultPath&&(s[`${o}.resultPath`]=a(i.resultPath,p(i.resultPath))),i.sourceShapeUri&&i.sourceShape!==void 0&&(s[`${o}.sourceShape`]=a(i.sourceShapeUri,i.sourceShape)),i.valueRef?s[`${o}.value`]=a(i.valueRef,p(i.valueRef)):i.value!==void 0&&(s[`${o}.value`]=i.value),r[u]=s}),r.report={type:`${o}.ValidationReport`,[`${o}.conforms`]:n.result.conforms,...d.length>0?{[`${o}.result`]:d}:{}},e.buildContentAddressed({publisher:n.publisher,book:t,body:r,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as tc}from"@kanonak-protocol/types/document/models/enums";import{spawn as Ja}from"child_process";var Oo=12e4,Za=4096,re=class{argv;interactive;timeoutMs;stderr;now;constructor(e){this.argv=No(e.command),this.interactive=e.interactive??!1,this.timeoutMs=e.timeoutMs??Oo,this.stderr=e.stderr??process.stderr,this.now=e.nowSeconds??(()=>Date.now()/1e3)}get command(){return this.argv.join(" ")}async get(e){let t=await this.run("get",this.wireRequest("get",e)),o=en(e,t,this.now());if(!o.ok)throw new L(`credential helper '${this.command}' answered get for ${e.resource} outside the protocol (${o.problem}): ${o.message}`);return o.answer}async erase(e){let t=await this.run("erase",{...this.wireRequest("erase",e),scope:e.scope}),o=nn(t);if(!o.ok)throw new L(`credential helper '${this.command}' answered erase for ${e.resource} outside the protocol (${o.problem}): ${o.message}`)}wireRequest(e,t){let o={version:Ze,operation:e,resource:t.resource,method:t.method};return t.challenges&&(o.challenges=t.challenges),o.interactive=this.interactive,o}run(e,t){let o=`credential helper '${this.command}' ${e}`;return new Promise((a,r)=>{let d=!1,i=l=>{d||(d=!0,l())},c;try{c=Ja(this.argv[0],[...this.argv.slice(1),e],{stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(l){r(Ko(o,l));return}let u=[],s="",f=!1,m=setTimeout(()=>{f=!0,c.kill()},this.timeoutMs);c.stdout.on("data",l=>u.push(l)),c.stderr.on("data",l=>{this.stderr.write(l),s=(s+l.toString("utf8")).slice(-Za)}),c.on("error",l=>{clearTimeout(m),i(()=>r(Ko(o,l)))}),c.on("close",(l,h)=>{clearTimeout(m);let y=s.trim()?`: ${s.trim()}`:"";if(f){i(()=>r(new L(`${o} did not finish within ${Math.round(this.timeoutMs/1e3)}s${y}`)));return}if(l!==0){let v=l!==null?`exit ${l}`:`signal ${h}`;i(()=>r(new L(`${o} failed (${v})${y}`)));return}let R=Buffer.concat(u).toString("utf8").trim();try{let v=JSON.parse(R);i(()=>a(v))}catch{i(()=>r(new L(`${o} exited 0 without printing one JSON answer${y}`)))}}),c.stdin.on("error",()=>{}),c.stdin.end(`${JSON.stringify(t)}
4
- `)})}};function No(n){let e=n.trim().split(/\s+/).filter(t=>t!=="");if(e.length===0)throw new Error("the credential helper command is empty");return e}function Ko(n,e){let t=e.code,o="";return t==="ENOENT"&&(o=" (not found: give its path, or put it on PATH)"),t==="EINVAL"&&process.platform==="win32"&&(o=" (a .cmd or .bat file cannot run without a shell: configure an executable, e.g. `node path/to/helper.js`)"),new L(`${n} could not be started: ${e.message}${o}`)}import{existsSync as ei,readFileSync as ni}from"fs";import{homedir as oi}from"os";import{join as ti}from"path";function ae(){return ti(oi(),".kanonak","config.json")}function ie(n){if(!ei(n))return;let e;try{e=JSON.parse(ni(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${n} must hold a JSON object`);return e}var ln="KANONAK_CREDENTIAL_HELPER";function ri(n={}){let e=n.env??process.env,t=n.configPath??ae(),o=ai(e,t);if(o){let r=Object.keys(e).filter(d=>(d===ve||d.startsWith(`${ve}_`))&&(e[d]??"").trim()!=="").sort();if(r.length>0)throw new Error(`A credential helper is configured (${o.source}: ${o.command}) and so is ${r.join(", ")}. Configure one or the other.`);return new re({command:o.command,interactive:n.interactive??!1})}let a={env:e};return n.discovery&&(a.discovery=n.discovery),new on(a)}function ai(n,e){let t=(n[ln]??"").trim();if(t)return{command:t,source:ln};let o=ie(e)?.credentialHelper;if(o!==void 0){if(typeof o!="string"||o.trim()==="")throw new Error(`"credentialHelper" in ${e} must be a non-empty command line`);return{command:o.trim(),source:e}}}var pn="KANONAK_PACKAGE_URL_TEMPLATE";function ii(n={}){let e=n.env??process.env,t=n.configPath??ae(),o=ie(t)?.packageUrlTemplates,a=o===void 0?{}:{...Ue(o,"packageUrlTemplates",t)},r=(e[pn]??"").trim();return r&&(a[Me]=$e(r,pn,!0)),Object.keys(a).length>0?Object.freeze(a):void 0}var P="kanonak.org",I="view",Ao="core-kanonak",si={publisher:P,package_:I,name:"rootView"},ci={publisher:P,package_:I,name:"bind"},di={publisher:P,package_:I,name:"produces"},ui={publisher:P,package_:I,name:"projections"},li={publisher:P,package_:I,name:"where"},pi={publisher:P,package_:I,name:"value"},fi={publisher:P,package_:I,name:"as"},xe=class{constructor(e,t=new X){this.repository=e;this.parser=t;this.objectParser=new U(this.parser),this.builder=new ne(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let o=await this.objectParser.parseKanonaks(this.repository),a=this.resolveView(o,e),r=k(a,ci);if(!r)throw new Error(`View ${a.namespace}/${a.name} declares no view.bind; cannot materialize.`);let d=k(a,di);if(!d)throw new Error(`View ${a.namespace}/${a.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let i=mi(a),c=xo(o,P,Ao),u=xo(o,P,I),s=this.builder.imports(),f=s.ensure(P,Ao,c,"ck"),m=s.ensure(P,I,u,"v"),l=s.ref(d),h=new oo(this.repository,this.parser,this.objectParser),y=new no(h,o),R=this.readProjections(o,a),v=gi(a,li),w=this.findInstances(o,r,await this.reason(t)),S={},K=new Set;for(let se of w){if(!await this.passesWhere(y,o,v,se))continue;let Ie={type:l};for(let mn of R){let Lo=await this.evaluateValue(y,o,mn.value,se),hn=this.builder.serializeValue(Io(Lo),s);hn!==void 0&&(Ie[s.ref(mn.as)]=hn)}let fn=E(se);fn&&(Ie[`${m}.derivedFrom`]=s.ref(fn)),S[this.rowName(se,K)]=Ie}let C={};t.resolvedAt&&(C[`${f}.resolvedAt`]=t.resolvedAt),t.invocationId&&(C[`${f}.id`]=t.invocationId);let x=await this.builder.buildContentAddressed({publisher:i,book:s,body:S,contentHashProperty:`${f}.contentHash`,header:C});return{yaml:x.yaml,contentHash:x.contentHash,packageName:x.packageName,publisher:x.publisher,rowCount:x.resourceCount}}resolveView(e,t){let o=N(e,t);if(!o)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let a=k(o,si);if(a){let r=N(e,a);if(!r)throw new Error(`ViewPackage ${t.name} names rootView ${a.name}, which is not in the catalog.`);return r}return o}readProjections(e,t){let o=[];for(let a of He(t,ui)){let r=a instanceof M?a:a instanceof O?N(e,a.subject):void 0;if(!r)continue;let d=Y(r,pi),i=k(r,fi);d&&i&&o.push({value:d,as:i})}return o}async reason(e){return new z({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,o){let a=Si(e),r=[],d=new Set;for(let i of o.getInstancesOfClass(t)){if(d.has(i))continue;d.add(i);let c=a.get(i);c&&r.push(c)}return r.sort((i,c)=>{let u=Q(E(i)),s=Q(E(c));return u<s?-1:u>s?1:0}),r}async passesWhere(e,t,o,a){for(let r of o){let d=await this.evaluateValue(e,t,r,a);if(!ki(d))return!1}return!0}async evaluateValue(e,t,o,a){let r=eo(o,"view-projection",{catalog:t,depth:0}),d=new Map([["input",a]]);return e.evaluate(r,d)}rowName(e,t){let o=Je(e.name)||"row",a=o,r=2;for(;t.has(a);)a=`${o}-${r++}`;return t.add(a),a}};function Io(n){return Qe(n)?n.value:Array.isArray(n)?n.map(Io):n}function mi(n){let e=E(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function xo(n,e,t){let o=hi(n,e,t);if(!o)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return o}function hi(n,e,t){let o;for(let a of n){if(!(a instanceof g))continue;let r=E(a);!r||r.publisher!==e||r.package_!==t||!r.version||(!o||ce(r.version,o)>0)&&(o=r.version)}return o?V(o):void 0}function Si(n){let e=new Map,t=new Map;for(let o of n){if(!(o instanceof g))continue;let a=E(o);if(!a||!a.version)continue;let r=Q(a),d=t.get(r);(!d||ce(a.version,d)>0)&&(t.set(r,a.version),e.set(r,o))}return e}function gi(n,e){let t=Y(n,e);return t?[t]:He(n,e).filter(o=>o instanceof M)}function ki(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Qe(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{Me as ANY_PUBLISHER,Or as AmbiguousReferenceRule,vt as BooleanStatement,ra as CANONICAL_FORM_VERSION,ha as CREDENTIAL_EXPIRY_SKEW_SECONDS,ln as CREDENTIAL_HELPER_ENV,Ze as CREDENTIAL_HELPER_PROTOCOL_VERSION,Oo as CREDENTIAL_HELPER_TIMEOUT_MS,T as Carrier,Mr as ClassDefinitionRule,br as ClassHierarchyCycleRule,Bo as CompositeKanonakDocumentRepository,L as CredentialError,la as DEFAULT_CONSENT_BINDING_PARAM,Et as DefinedKanonak,ea as DiamondNameClashRule,$r as DisplayLensScopeRule,qo as DocumentLocation,Gt as EdgeType,M as EmbeddedKanonak,yr as EmbeddedKanonakTypeRule,Kt as EmbeddedStatement,ba as EntitlementDeniedError,_a as EntitlementProducer,re as ExecCredentialProvider,Wo as FileSystemKanonakDocumentRepository,St as GitIgnoreFilter,zt as GraphBuilder,ft as HttpKanonakDocumentRepository,gn as INTEGRITY_PREFIX,ia as ImportBook,Er as ImportExistenceRule,Le as InMemoryKanonakDocumentRepository,Zo as KANONAK_USER_AGENT,yt as Kanonak,er as KanonakDocumentPositions,Xo as KanonakHttpError,U as KanonakObjectParser,na as KanonakObjectValidator,X as KanonakParser,at as KanonakUri,ar as KanonakUriBuilder,ir as KanonakUrlResolver,Ht as KanonakVocabulary,Fr as LINE_STYLES,fr as LinkTargetRule,Ot as ListStatement,Ct as LiteralKanonak,mt as LocalFirstRepository,ht as LockAwareRepository,Yr as LookBandPathRule,Gr as LookRenderer,Vr as LookSemanticSvgPathRule,Ur as MarkdownLinkRule,Nt as MarkdownStatement,wr as NamespaceImportCycleRule,mr as NamespacePrefixRule,Bt as NodeType,Rt as NumberStatement,pa as OAuthDiscovery,qe as OWL_HAS_KEY,Qt as OWL_RL_CLASSIFICATION_RULES,Ar as ObjectPropertyValueValidationRule,ur as OntologyValidationError,cr as OntologyValidationResult,Zr as OwlOneOfRule,pn as PACKAGE_URL_TEMPLATE_ENV,ne as PackageBuilder,kr as PackageHeaderRule,ya as ProducerRepository,xr as PropertyDomainRule,_r as PropertyHierarchyCycleRule,Ir as PropertyKindRangeConsistencyRule,Zt as PropertyMetadata,Nr as PropertyRangeReferenceRule,Pr as PropertyRangeRequiredRule,Sr as PropertyTypeSpecificityRule,ut as PublisherConfigResolver,lt as PublisherIndex,Yt as RDFS_RULES,z as Reasoner,Jt as ReasoningResult,O as ReferenceKanonak,wt as ReferenceStatement,zo as RepositoryFactory,Lr as ReservedNameShadowRule,hr as ResourceNamingRule,At as ResourceResolver,jt as ResourceTypeClassifier,pe as SHACL_PACKAGE,le as SHACL_PUBLISHER,ge as SH_COMP_CLASS,Z as SH_COMP_CLOSED,Se as SH_COMP_DATATYPE,q as SH_COMP_HAS_KEY,W as SH_COMP_HAS_VALUE,ke as SH_COMP_IN,he as SH_COMP_MAX_COUNT,_e as SH_COMP_MAX_INCLUSIVE,Ce as SH_COMP_MAX_LENGTH,me as SH_COMP_MIN_COUNT,be as SH_COMP_MIN_INCLUSIVE,Ee as SH_COMP_MIN_LENGTH,Pe as SH_COMP_NODE_KIND,ye as SH_COMP_PATTERN,j as SH_COMP_QUALIFIED_MAX_COUNT,H as SH_COMP_QUALIFIED_MIN_COUNT,J as SH_NODE_SHAPE,fe as SH_PROPERTY_SHAPE,_n as SH_SHAPE,_t as ScalarStatement,Xr as SequenceNarrativeRule,Jr as ShaclShapeRule,bt as Statement,Pt as StringStatement,Rr as SubClassOfReferenceRule,vr as SubPropertyOfReferenceRule,g as SubjectKanonak,gr as SubjectKanonakTypeRequiredRule,ve as TOKEN_ENV,on as TokenCredentialProvider,Xt as TripleStore,Hr as TxExpressionCompilesRule,Qr as TxExpressionPathRule,xt as TypeResolver,jr as URI_DISPLAY_LABEL,Tr as URI_DISPLAY_SUMMARY,Kr as UnresolvedPredicateRule,Cr as UnresolvedReferenceRule,pr as ValidationCache,lr as ValidationContext,dr as ValidationSeverity,tc as VersionOperator,xe as ViewMaterializer,Ea as allowAllPolicy,ot as assertHttpsUrl,Cn as assertIntegrityAsync,pt as assertPackageIdentity,Ke as buildKeysModel,kt as buildLocalFirstRepository,Br as buildOntologyModel,wo as buildReportPackageAsync,we as buildShapesModel,$t as builtinHomePackages,Vt as builtinUri,oa as canonicalForm,ta as canonicalHash,Ye as carrierOf,fa as checkCredentialAnswer,en as checkHelperAnswer,nn as checkHelperEraseAnswer,$e as checkPackageUrlTemplate,Ue as checkPackageUrlTemplates,gt as collectKanonakFiles,ce as compareVersions,ao as computeIntegrity,En as computeIntegrityAsync,aa as contentAddressedName,G as contextTypesOf,Sa as createCredentialedFetch,Vo as createVersion,ri as credentialProviderFromConfig,Qo as describeResponse,Co as evaluateConformance,qt as extractMarkdownLinks,dt as fillPackageUrlTemplate,ka as findDerivation,Wt as findMalformedReferences,or as findMarkdownLinkAt,an as foldFlagsIntoPattern,st as formatKanonakAddress,V as formatVersion,Go as getGlobalCachePath,nt as getKanonakUserAgent,Yo as httpError,jo as isCompatibleVersion,To as isMajorCompatible,ze as isPropertySubject,tt as kanonakFetch,to as loadLockFile,Sn as lockedVersion,Ne as lowerConstraint,Lt as makeUriKey,ua as narrowestScope,Ca as noopMeter,sa as normalizeHost,ct as packageUrlTemplateFor,ii as packageUrlTemplatesFromConfig,it as parseKanonakAddress,kn as parseLockFile,ca as parseScope,Ho as parseVersionString,nr as parseWithPositions,ma as parseWwwAuthenticate,Fo as pickHighestDocument,Dt as propertiesInScope,Tt as propertyClassOf,Wr as readSequenceConnectors,ie as readUserConfig,sr as referenceSpelling,D as referenceUris,Dr as resolveDisplayValue,Ft as resolvePropertyStep,Jo as retryAfterSecondsOf,Je as sanitizeName,Do as satisfiesVersionOperator,ro as saveLockFile,da as scopeContains,co as scopeFromCatalog,so as scopeFromClosureAsync,uo as scopeFromDocumentAsync,io as scopeFromRepositoryAsync,yn as serializeLockFile,rt as setKanonakFetchRetries,et as setKanonakUserAgent,rr as sourceSymbolAt,tr as sourceSymbols,No as splitCommandLine,B as subjectAddress,E as subjectUri,Ge as superClassChain,zr as supportedBandKeys,ga as tokenEnvKeyFor,Mt as tripleKey,It as typeReferenceUris,Q as uriKey,Ut as uriTriple,ae as userConfigPath,ee as valuesOf,Mo as versionOperatorFromChar,Uo as versionOperatorToChar,$o as versionsEqual,Xe as walkDefinedKanonaks,qr as walkSequence};
3
+ `)}`)}let r=new to(e,o),d=new Set((await r.getAllDocumentsAsync()).map(oe)),a=[...t].filter(l=>!d.has(l));if(a.length>0)throw new Error(`scopeFromClosureAsync: ${a.join(", ")} is not a document of the repository the closure is resolved through.`);let c={},u=await new M().parseKanonaks(r,c),s=c.authored.filter(l=>l instanceof g&&t.has(l.sourceDoc)),f=new Set(s.map(B)),m=await Ni(n,s,e);return{kind:"merged",catalog:u,reasoning:new z().reasonOver(u),focus:f,links:m}}async function Ni(n,e,t){let o=[],i=new Map,r=new Map;for(let d of n){let a=oe(d),c=e.filter(u=>u.sourceDoc===a);for(let{key:u,references:s,target:f,failure:m}of await ro(d,c,t)){let l=f?oe(f):void 0;if(r.has(u)&&r.get(u)!==l)throw new Error(`scopeFromClosureAsync: the seeds link ${u} at different versions (${r.get(u)??"unresolved"} and ${l??"unresolved"}); judge them in separate scopes.`);r.has(u)||(r.set(u,l),f&&o.push(...await new M().parseKanonaks(new Be(f,t))));for(let{uri:h}of s)f?io(f,h.name)||i.set(p(h),`${l} defines no resource named '${h.name}'`):i.set(p(h),`its package ${u} could not be resolved${m?` (${m})`:""}`)}}return r.size>0?{subjects:o,unresolved:i}:void 0}function oe(n){let e=n.metadata?.namespace_;if(!e)throw new Error("scopeFromClosureAsync: a document has no namespace, so it cannot be identified.");return e.toString()}function go(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function ko(n,e){let t=e??new Le(new X);return{kind:"standalone",catalog:await new M().parseKanonaks(new Be(n,t))}}function U(n){return typeof n=="number"?n:void 0}function Ai(n){if(!n)return;let e=p(n);if(e===p(Xn))return"IRI";if(e===p(Yn))return"BlankNode";if(e===p(Qn))return"Literal"}function Eo(n){if(!n)return;let e=p(n);if(e===p(Jn))return"Violation";if(e===p(Zn))return"Warning";if(e===p(eo))return"Info"}function Co(n,e,t,o){let i=k(e,je);if(!i)return;let r={path:i},d=U(O(e,Nn)),a=U(O(e,An));d!==void 0&&(r.minCount=d),a!==void 0&&(r.maxCount=a);let c=U(O(e,$n)),u=U(O(e,Hn));c!==void 0&&(r.minLength=c),u!==void 0&&(r.maxLength=u);let s=U(O(e,jn)),f=U(O(e,Dn));s!==void 0&&(r.minInclusive=s),f!==void 0&&(r.maxInclusive=f);let m=ue(e,Mn);if(m!==void 0){let S=ue(e,Un);r.pattern=S!==void 0?{regex:m,flags:S}:{regex:m}}if(F(e,De)){let S=[],x=[];for(let{item:C}of $e(e,De))"literal"in C?S.push(C.value):C instanceof K&&x.push(C.subject);S.length>0&&(r.inValues=S),x.length>0&&(r.inRefs=x)}let l=k(e,Ln);l&&(r.datatype=l);let h=k(e,Vn);h&&(r.classRef=h);let y=Ai(k(e,zn));y&&(r.nodeKind=y);let R=k(e,no);if(R&&(r.hasValue=R),F(e,Re)||F(e,Fe)||F(e,We)){let S={},x=U(O(e,Fe)),C=U(O(e,We));x!==void 0&&(S.minCount=x),C!==void 0&&(S.maxCount=C);let N=Li(n,e,o);"problem"in N?S.problem=N.problem:S.shape=N.shape,r.qualified=S}let v=ue(e,Tn);v!==void 0&&(r.message=v);let w=Eo(k(e,Te))??t;return w&&(r.severity=w),r}function Li(n,e,t){let o=Y(e,Re);if(o)return yo(n,o,void 0,t);let i=k(e,Re);if(!i)return{problem:"sh:qualifiedValueShape is missing"};let r=p(i);if(t.has(r))return{problem:`sh:qualifiedValueShape '${i.name}' leads back to itself (a cycle through named shapes)`};let d=I(n,i);return d?yo(n,d,r,t):{problem:`sh:qualifiedValueShape '${i.name}' does not resolve`}}function yo(n,e,t,o){let i=t?new Set([...o,t]):o,r=de(e,J);if((de(e,fe)||F(e,je))&&!r){let c=Co(n,e,void 0,i);return c?{shape:{kind:"property",constraint:c}}:{problem:"the qualified property shape has no sh:path"}}return e instanceof g&&!r?{problem:`sh:qualifiedValueShape '${e.name}' is not a shape`}:{shape:{kind:"node",shape:bo(n,e,i)}}}function bo(n,e,t){let o=Eo(k(e,Te)),i={name:e instanceof g?e.name:"(inline shape)",uri:e instanceof g?E(e):void 0,targetClass:k(e,In),targetNodes:T(e,Fn),targetSubjectsOf:T(e,Wn),targetObjectsOf:T(e,qn),closed:O(e,Bn)===!0,ignoredProperties:[],severity:o,properties:[]};i.ignoredProperties.push(...T(e,Gn));for(let{item:r}of $e(e,On)){let d;if(r instanceof V?d=r:r instanceof K&&(d=I(n,r.subject)),!d)continue;let a=Co(n,d,o,t);a&&i.properties.push(a)}return i}function we(n){let e=[];for(let t of n){if(!(t instanceof g)||!de(t,J))continue;let o=E(t);e.push(bo(n,t,new Set(o?[p(o)]:[])))}return e}function xe(n){let e=new Map;for(let t of n)if(t instanceof g)for(let o of xn(t,qe)){let i=E(t);if(!i)throw new Error(`owl.hasKey on '${t.namespace}/${t.name}': the class has no resolvable URI.`);if(o.length===0)throw new Error(`owl.hasKey on '${t.name}' lists no properties; a key needs at least one.`);let r=o.map(({item:d})=>{let a=d instanceof K?I(n,d.subject):void 0;if(!a||!ze(n,a)){let c=d instanceof K?`'${p(d.subject)}'`:"a value that is not a reference";throw new Error(`owl.hasKey on '${t.name}' lists ${c}, which is not a property defined in scope; a key lists properties.`)}return d.subject});e.set(`${p(i)}|${r.map(p).join(",")}`,{classUri:i,className:t.name,properties:r})}return[...e.values()]}var _="kanonak.org/transformations",te="values";var Ke="allowed",rn="expected",b=n=>({type:`${_}/VarRef`,varName:n}),tn=n=>({type:`${_}/IntegerLiteral`,integerLiteral:n}),Vi=n=>({type:`${_}/DecimalLiteral`,decimalLiteral:n}),_o=n=>Number.isInteger(n)?tn(n):Vi(n),Po=n=>({type:`${_}/Count`,source:n}),Ro=(n,e)=>({type:`${_}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),vo=(n,e)=>({type:`${_}/LessThanOrEqual`,compareLeft:n,compareRight:e});function an(n,e){if(!e||e.length===0)return n;let t=new Set(["i","m","s"]),o=[...new Set(e.split(""))];if(o.filter(r=>!t.has(r)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${o.sort().join("")})${n}`}function Ie(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Ro(Po(b(te)),tn(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:vo(Po(b(te)),tn(n.maxCount))}),n.hasValue!==void 0&&e.push({component:"hasValue",per:"node",expr:{type:`${_}/Contains`,haystack:b(te),needle:b(rn)}}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${_}/Contains`,haystack:b(Ke),needle:b("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${_}/Matches`,matchSource:b("v"),pattern:an(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${_}/Matches`,matchSource:b("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${_}/Matches`,matchSource:b("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Ro(b("v"),_o(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:vo(b("v"),_o(n.maxInclusive))}),e}import{evaluate as Ui,ExpressionError as $i}from"@kanonak-protocol/expression";function Ko(n,e){let t=wo(e)?e:we(e),o=[],i=n.catalog.filter(c=>c instanceof g).map(Oe),r=new Map;Hi(i,r);let d=n.links?[...n.catalog,...n.links.subjects]:n.catalog,a={scope:n,membership:new cn(n),values:d,embeddedFocus:r};for(let c of t)for(let u of ji(a,c,i))sn(n,u)&&Oo(a,c,u,o);if(!wo(e))for(let c of xe(e))Di(a,c,i,o);return{conforms:!o.some(c=>c.severity==="Violation"),results:o}}function wo(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function Io(n){let e=n.predicate;return e instanceof K?e:void 0}function sn(n,e){return!n.focus||e.subject!==void 0&&n.focus.has(e.subject)}function Oe(n){let e=B(n);return{node:n,key:e,uri:E(n),subject:e,label:n.name}}function un(n,e,t){return{node:n,key:e,subject:t,label:e.includes("#")?e.slice(e.indexOf("#")):e}}function Hi(n,e){for(let t of n)Xe([t.node],({kanonak:o,address:i})=>{o instanceof V&&!e.has(o)&&e.set(o,un(o,i,t.subject))})}var cn=class{constructor(e){this.scope=e}scope;ancestors=new Map;defined;defines(e){return this.defined??=new Set(this.scope.catalog.filter(t=>t instanceof g).map(B)),this.defined.has(p(e))}isInstance(e,t){let o=p(t);return e.some(i=>p(i)===o||this.ancestorsOf(i).has(o))}ancestorsOf(e){let t=e.version&&typeof e.version.major=="number"?`${p(e)}@${$(e.version)}`:p(e),o=this.ancestors.get(t);return o||(o=this.scope.reasoning?new Set(this.scope.reasoning.getSuperclasses(e)):new Set(Ge(this.scope.catalog,e).map(i=>p(i))),this.ancestors.set(t,o)),o}};function ji(n,e,t){let{scope:o}=n,i=new Map,r=a=>{i.set(a.key,a)},d=()=>[...t,...n.embeddedFocus.values()];if(e.targetClass){let a=e.targetClass;for(let c of d())n.membership.isInstance(G(c.node),a)&&r(c)}for(let a of e.targetNodes){let c=I(o.catalog,a);c instanceof g&&r(Oe(c))}for(let a of e.targetSubjectsOf){let c=p(a);for(let u of d())u.node.statement.some(s=>{let f=Io(s);return f&&p(f.subject)===c})&&r(u)}for(let a of e.targetObjectsOf)for(let c of d())for(let u of ee(c.node,a,o.catalog,c.key))u.kind==="subject"?r(Oe(u.node)):u.kind==="embedded"&&r(n.embeddedFocus.get(u.node)??un(u.node,u.address,c.subject));return[...i.values()]}function Di(n,e,t,o){let i=new Map;for(let c of t)n.membership.isInstance(G(c.node),e.classUri)&&i.set(c.key,c);let r=[];for(let c of[...i.values()].sort((u,s)=>u.key<s.key?-1:u.key>s.key?1:0)){let u=e.properties.map(s=>Ti(n,c,s));u.every(s=>s.size>0)&&r.push({focus:c,values:u})}let d=new Map;r.forEach(({values:c},u)=>{for(let s of c[0].keys()){let f=d.get(s);f?f.push(u):d.set(s,[u])}});let a=new Set;for(let c of d.values())for(let u=0;u<c.length;u++)for(let s=u+1;s<c.length;s++){let f=`${c[u]}:${c[s]}`;if(a.has(f))continue;let m=r[c[u]],l=r[c[s]],h=m.values.map((w,S)=>[...w.keys()].find(x=>l.values[S].has(x)));if(h.some(w=>w===void 0))continue;a.add(f);let[y,R]=sn(n.scope,m.focus)?[m.focus,l.focus]:sn(n.scope,l.focus)?[l.focus,m.focus]:[void 0,void 0];if(!y||!R)continue;let v=e.properties.map((w,S)=>`${w.name} = ${m.values[S].get(h[S])}`).join(", ");o.push({focusNode:y.key,focusUri:y.uri,valueRef:R.uri,constraintComponent:q,severity:"Violation",message:`'${y.label}' and '${R.label}' are distinct instances of ${e.className} with the same key (${v}); its owl.hasKey makes the key unique.`})}}function Ti(n,e,t){let o=new Map;for(let i of ee(e.node,t,n.scope.catalog,e.key))switch(i.kind){case"subject":case"unresolved":o.set(`ref:${p(i.uri)}`,i.uri.name);break;case"literal":o.set(`${typeof i.value}:${String(i.value)}`,JSON.stringify(i.value));break;case"embedded":break}return o}function Fi(n,e,t){return e.node?ee(e.node,t,n.values,e.key).map(o=>Wi(n,o,e.subject)):[]}function Wi(n,e,t){switch(e.kind){case"subject":return{kernel:{ref:p(e.uri)},kind:"reference",ref:e.uri,subject:e.node};case"unresolved":return{kernel:{ref:p(e.uri)},kind:"reference",ref:e.uri};case"embedded":{let o=n.embeddedFocus.get(e.node)??un(e.node,e.address,t);return{kernel:{ref:o.key},kind:"embedded",embedded:o}}case"literal":return typeof e.value=="boolean"?{kernel:e.value?1:0,kind:"boolean",literal:e.value}:{kernel:e.value,kind:typeof e.value=="number"?"number":"string",literal:e.value}}}function Oo(n,e,t,o){for(let i of e.properties)Ao(n,e,t,i,o);e.closed&&na(e,t,o)}function dn(n,e,t,o,i={},r){return{focusNode:e.key,focusUri:e.uri,constraintComponent:t,severity:r??No(n),message:o,sourceShape:n.name,sourceShapeUri:n.uri,...i}}function No(n){return n.severity??"Violation"}var qi={minCount:me,maxCount:he,hasValue:W,in:ke,pattern:ye,minLength:Ee,maxLength:Ce,minInclusive:be,maxInclusive:_e};function Ao(n,e,t,o,i){let r=Fi(n,t,o.path),d=o.severity??No(e),a=o.path.name,c=[...(o.inValues??[]).map(s=>typeof s=="boolean"?s?1:0:s),...(o.inRefs??[]).map(s=>({ref:p(s)}))],u=(s,f,m)=>{let l=dn(e,t,s,o.message??f,{resultPath:o.path,value:m?.literal,valueRef:m?.ref},d);return i.push(l),l};for(let s of Ie(o)){let f=qi[s.component];if(s.per==="node"){let m={[te]:r.map(l=>l.kernel),[Ke]:c};o.hasValue&&(m[rn]={ref:p(o.hasValue)}),xo(s,m)||u(f,Bi(s,a,o,r.length));continue}for(let m of r){if((s.component==="pattern"||s.component==="minLength"||s.component==="maxLength")&&m.kind!=="string"){u(f,`'${a}' value is not a string; ${s.component} applies to string values.`,m);continue}xo(s,{v:m.kernel,[Ke]:c})||u(f,Qi(s,a,o,m),m)}}if(o.nodeKind)for(let s of r)Ji(o.nodeKind,s)||u(Pe,`'${a}' value is ${s.kind}; nodeKind requires ${o.nodeKind}.`,s);if(o.datatype)for(let s of r){let f=Zi(o.datatype,s);f&&u(Se,`'${a}' ${f}`,s)}if(o.classRef)for(let s of r){let f=ea(n,o.classRef,s);f&&u(ge,`'${a}' ${f}`,s)}o.qualified&&Gi(n,o,r,a,u)}function Bi(n,e,t,o){switch(n.component){case"minCount":return`'${e}' has ${o} value(s); minCount is ${t.minCount}.`;case"maxCount":return`'${e}' has ${o} value(s); maxCount is ${t.maxCount}.`;case"hasValue":return`'${e}' has no value equal to ${t.hasValue?p(t.hasValue):"(unset)"}.`;default:return`'${e}' violates ${n.component}.`}}function Gi(n,e,t,o,i){let r=e.qualified,d=r.maxCount!==void 0?j:H,a=(u,s)=>{Lo.add(i(d,u,s))};if(!r.shape){a(`'${o}' qualified value shape cannot be evaluated: ${r.problem??"it could not be built"}.`);return}let c=0;for(let u of t){let s=u.ref?p(u.ref):u.embedded?u.embedded.label:JSON.stringify(u.literal),f=zi(n,u);if(!f){a(`'${o}' value ${s} does not resolve in this scope; whether it conforms to the qualified shape cannot be decided.`,u);continue}let m=Yi(n,r.shape,f);if(m.kind==="undecided"){a(`'${o}' value ${s}: whether it conforms to the qualified shape cannot be decided \u2014 ${m.reason}`,u);continue}m.kind==="conforms"&&c++}r.minCount!==void 0&&c<r.minCount&&i(H,`'${o}' has ${c} value(s) that conform to the qualified shape; qualifiedMinCount is ${r.minCount}.`),r.maxCount!==void 0&&c>r.maxCount&&i(j,`'${o}' has ${c} value(s) that conform to the qualified shape; qualifiedMaxCount is ${r.maxCount}.`)}function zi(n,e){switch(e.kind){case"reference":return e.subject?Oe(e.subject):void 0;case"embedded":return e.embedded;default:{let t=JSON.stringify(e.literal);return{key:t,label:t}}}}var Xi={name:"(qualified value shape)",targetNodes:[],targetSubjectsOf:[],targetObjectsOf:[],closed:!1,ignoredProperties:[],properties:[]},Lo=new WeakSet;function Yi(n,e,t){let o=[];e.kind==="property"?Ao(n,Xi,t,e.constraint,o):Oo(n,e.shape,t,o);let i=o.find(r=>Lo.has(r));return i?{kind:"undecided",reason:i.message}:o.length===0?{kind:"conforms"}:{kind:"fails"}}function Qi(n,e,t,o){let i=o.ref?p(o.ref):o.embedded?o.embedded.label:JSON.stringify(o.literal);switch(n.component){case"in":return`'${e}' value ${i} is not in the permitted set.`;case"pattern":return`'${e}' value ${i} does not match pattern ${t.pattern?.regex}.`;case"minLength":return`'${e}' value ${i} is shorter than minLength ${t.minLength}.`;case"maxLength":return`'${e}' value ${i} is longer than maxLength ${t.maxLength}.`;case"minInclusive":return`'${e}' value ${i} is below minInclusive ${t.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${i} is above maxInclusive ${t.maxInclusive} (or not numeric).`;default:return`'${e}' value ${i} violates ${n.component}.`}}function xo(n,e){let t=o=>{let i=o.varName;if(o.type==="kanonak.org/transformations/VarRef"&&typeof i=="string"&&i in e)return e[i];throw new $i(`Conformance lowering produced an unexpected leaf '${o.type}'`)};return Ui(n.expr,void 0,t)===1}function Ji(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function Zi(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let t=Ye(n);if(t!==void 0)switch(t){case D.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case D.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case D.Decimal:case D.Double:case D.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function ea(n,e,t){if(t.kind==="embedded"&&t.embedded?.node){let d=G(t.embedded.node);return d.length===0?`value ${t.embedded.label} has no type; sh:class requires an instance of ${e.name}.`:n.membership.isInstance(d,e)?void 0:`value ${t.embedded.label} is not an instance of ${e.name}.`}if(t.kind!=="reference"||!t.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;let o=t.subject;if(!o){let d=n.scope.links?.unresolved.get(p(t.ref));return d?`value ${p(t.ref)} is a link that does not dereference: ${d} (sh:class ${e.name}).`:`value ${p(t.ref)} does not resolve in this scope (sh:class ${e.name}).`}let i=G(o);if(n.membership.isInstance(i,e))return;let r=i.filter(d=>!n.membership.defines(d));return r.length>0?`value ${p(t.ref)} is typed ${r.map(p).join(", ")}, which this scope does not define, so it cannot be shown to be an instance of ${e.name}. A class is in scope when the judged document imports the package that defines it.`:`value ${p(t.ref)} is not an instance of ${e.name}.`}function na(n,e,t){if(!e.node)return;let o=new Set([...n.properties.map(r=>p(r.path)),...n.ignoredProperties.map(r=>p(r))]),i=new Set;for(let r of e.node.statement){let d=Io(r);if(!d)continue;let a=p(d.subject);o.has(a)||i.has(a)||(i.add(a),t.push(dn(n,e,Z,`'${e.label}' carries undeclared property '${d.subject.name}' (closed shape).`,{resultPath:d.subject})))}for(let r of e.node.unresolvedPredicates)i.has(r.key)||(i.add(r.key),t.push(dn(n,e,Z,`'${e.label}' carries unresolvable property '${r.key}' (closed shape).`,{value:r.key})))}var oa="1.1.0",ta=new Set([W,H,j].map(n=>n.name)),ra=new Set([q].map(n=>n.name));function ia(n){let e=new Set(n.results.map(t=>t.constraintComponent.name));return[...e].some(t=>ra.has(t))?"1.3.0":[...e].some(t=>ta.has(t))?"1.2.0":oa}async function Vo(n){let e=new ne(n.repository),t=e.imports(),o=t.ensure(le,pe,ia(n.result),"sh"),i=(a,c)=>a&&a.version&&typeof a.version.major=="number"?`${t.ensure(a.publisher,a.package_,$(a.version),a.package_)}.${a.name}`:c,r={},d=[];return n.result.results.forEach((a,c)=>{let u=`result-${c+1}`;d.push(u);let s={type:`${o}.ValidationResult`,[`${o}.focusNode`]:i(a.focusUri,a.focusNode),[`${o}.resultMessage`]:a.message,[`${o}.resultSeverity`]:`${o}.${a.severity}`,[`${o}.sourceConstraintComponent`]:`${o}.${a.constraintComponent.name}`};a.resultPath&&(s[`${o}.resultPath`]=i(a.resultPath,p(a.resultPath))),a.sourceShapeUri&&a.sourceShape!==void 0&&(s[`${o}.sourceShape`]=i(a.sourceShapeUri,a.sourceShape)),a.valueRef?s[`${o}.value`]=i(a.valueRef,p(a.valueRef)):a.value!==void 0&&(s[`${o}.value`]=a.value),r[u]=s}),r.report={type:`${o}.ValidationReport`,[`${o}.conforms`]:n.result.conforms,...d.length>0?{[`${o}.result`]:d}:{}},e.buildContentAddressed({publisher:n.publisher,book:t,body:r,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as fc}from"@kanonak-protocol/types/document/models/enums";import{spawn as aa}from"child_process";var Uo=12e4,sa=4096,re=class{argv;interactive;timeoutMs;stderr;now;constructor(e){this.argv=$o(e.command),this.interactive=e.interactive??!1,this.timeoutMs=e.timeoutMs??Uo,this.stderr=e.stderr??process.stderr,this.now=e.nowSeconds??(()=>Date.now()/1e3)}get command(){return this.argv.join(" ")}async get(e){let t=await this.run("get",this.wireRequest("get",e)),o=en(e,t,this.now());if(!o.ok)throw new L(`credential helper '${this.command}' answered get for ${e.resource} outside the protocol (${o.problem}): ${o.message}`);return o.answer}async erase(e){let t=await this.run("erase",{...this.wireRequest("erase",e),scope:e.scope}),o=nn(t);if(!o.ok)throw new L(`credential helper '${this.command}' answered erase for ${e.resource} outside the protocol (${o.problem}): ${o.message}`)}wireRequest(e,t){let o={version:Ze,operation:e,resource:t.resource,method:t.method};return t.challenges&&(o.challenges=t.challenges),o.interactive=this.interactive,o}run(e,t){let o=`credential helper '${this.command}' ${e}`;return new Promise((i,r)=>{let d=!1,a=l=>{d||(d=!0,l())},c;try{c=aa(this.argv[0],[...this.argv.slice(1),e],{stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(l){r(Mo(o,l));return}let u=[],s="",f=!1,m=setTimeout(()=>{f=!0,c.kill()},this.timeoutMs);c.stdout.on("data",l=>u.push(l)),c.stderr.on("data",l=>{this.stderr.write(l),s=(s+l.toString("utf8")).slice(-sa)}),c.on("error",l=>{clearTimeout(m),a(()=>r(Mo(o,l)))}),c.on("close",(l,h)=>{clearTimeout(m);let y=s.trim()?`: ${s.trim()}`:"";if(f){a(()=>r(new L(`${o} did not finish within ${Math.round(this.timeoutMs/1e3)}s${y}`)));return}if(l!==0){let v=l!==null?`exit ${l}`:`signal ${h}`;a(()=>r(new L(`${o} failed (${v})${y}`)));return}let R=Buffer.concat(u).toString("utf8").trim();try{let v=JSON.parse(R);a(()=>i(v))}catch{a(()=>r(new L(`${o} exited 0 without printing one JSON answer${y}`)))}}),c.stdin.on("error",()=>{}),c.stdin.end(`${JSON.stringify(t)}
4
+ `)})}};function $o(n){let e=n.trim().split(/\s+/).filter(t=>t!=="");if(e.length===0)throw new Error("the credential helper command is empty");return e}function Mo(n,e){let t=e.code,o="";return t==="ENOENT"&&(o=" (not found: give its path, or put it on PATH)"),t==="EINVAL"&&process.platform==="win32"&&(o=" (a .cmd or .bat file cannot run without a shell: configure an executable, e.g. `node path/to/helper.js`)"),new L(`${n} could not be started: ${e.message}${o}`)}import{existsSync as ca,readFileSync as da}from"fs";import{homedir as ua}from"os";import{join as la}from"path";function ie(){return la(ua(),".kanonak","config.json")}function ae(n){if(!ca(n))return;let e;try{e=JSON.parse(da(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${n} must hold a JSON object`);return e}var ln="KANONAK_CREDENTIAL_HELPER";function pa(n={}){let e=n.env??process.env,t=n.configPath??ie(),o=fa(e,t);if(o){let r=Object.keys(e).filter(d=>(d===ve||d.startsWith(`${ve}_`))&&(e[d]??"").trim()!=="").sort();if(r.length>0)throw new Error(`A credential helper is configured (${o.source}: ${o.command}) and so is ${r.join(", ")}. Configure one or the other.`);return new re({command:o.command,interactive:n.interactive??!1})}let i={env:e};return n.discovery&&(i.discovery=n.discovery),new on(i)}function fa(n,e){let t=(n[ln]??"").trim();if(t)return{command:t,source:ln};let o=ae(e)?.credentialHelper;if(o!==void 0){if(typeof o!="string"||o.trim()==="")throw new Error(`"credentialHelper" in ${e} must be a non-empty command line`);return{command:o.trim(),source:e}}}var pn="KANONAK_PACKAGE_URL_TEMPLATE";function ma(n={}){let e=n.env??process.env,t=n.configPath??ie(),o=ae(t)?.packageUrlTemplates,i=o===void 0?{}:{...Me(o,"packageUrlTemplates",t)},r=(e[pn]??"").trim();return r&&(i[Ve]=Ue(r,pn,!0)),Object.keys(i).length>0?Object.freeze(i):void 0}var P="kanonak.org",A="view",Ho="core-kanonak",ha={publisher:P,package_:A,name:"rootView"},Sa={publisher:P,package_:A,name:"bind"},ga={publisher:P,package_:A,name:"produces"},ka={publisher:P,package_:A,name:"projections"},ya={publisher:P,package_:A,name:"where"},Ea={publisher:P,package_:A,name:"value"},Ca={publisher:P,package_:A,name:"as"},Ne=class{constructor(e,t=new X){this.repository=e;this.parser=t;this.objectParser=new M(this.parser),this.builder=new ne(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let o=await this.objectParser.parseKanonaks(this.repository),i=this.resolveView(o,e),r=k(i,Sa);if(!r)throw new Error(`View ${i.namespace}/${i.name} declares no view.bind; cannot materialize.`);let d=k(i,ga);if(!d)throw new Error(`View ${i.namespace}/${i.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let a=ba(i),c=jo(o,P,Ho),u=jo(o,P,A),s=this.builder.imports(),f=s.ensure(P,Ho,c,"ck"),m=s.ensure(P,A,u,"v"),l=s.ref(d),h=new co(this.repository,this.parser,this.objectParser),y=new so(h,o),R=this.readProjections(o,i),v=Ra(i,ya),w=this.findInstances(o,r,await this.reason(t)),S={},x=new Set;for(let se of w){if(!await this.passesWhere(y,o,v,se))continue;let Ae={type:l};for(let mn of R){let To=await this.evaluateValue(y,o,mn.value,se),hn=this.builder.serializeValue(Do(To),s);hn!==void 0&&(Ae[s.ref(mn.as)]=hn)}let fn=E(se);fn&&(Ae[`${m}.derivedFrom`]=s.ref(fn)),S[this.rowName(se,x)]=Ae}let C={};t.resolvedAt&&(C[`${f}.resolvedAt`]=t.resolvedAt),t.invocationId&&(C[`${f}.id`]=t.invocationId);let N=await this.builder.buildContentAddressed({publisher:a,book:s,body:S,contentHashProperty:`${f}.contentHash`,header:C});return{yaml:N.yaml,contentHash:N.contentHash,packageName:N.packageName,publisher:N.publisher,rowCount:N.resourceCount}}resolveView(e,t){let o=I(e,t);if(!o)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let i=k(o,ha);if(i){let r=I(e,i);if(!r)throw new Error(`ViewPackage ${t.name} names rootView ${i.name}, which is not in the catalog.`);return r}return o}readProjections(e,t){let o=[];for(let i of He(t,ka)){let r=i instanceof V?i:i instanceof K?I(e,i.subject):void 0;if(!r)continue;let d=Y(r,Ea),a=k(r,Ca);d&&a&&o.push({value:d,as:a})}return o}async reason(e){return new z({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,o){let i=Pa(e),r=[],d=new Set;for(let a of o.getInstancesOfClass(t)){if(d.has(a))continue;d.add(a);let c=i.get(a);c&&r.push(c)}return r.sort((a,c)=>{let u=Q(E(a)),s=Q(E(c));return u<s?-1:u>s?1:0}),r}async passesWhere(e,t,o,i){for(let r of o){let d=await this.evaluateValue(e,t,r,i);if(!va(d))return!1}return!0}async evaluateValue(e,t,o,i){let r=ao(o,"view-projection",{catalog:t,depth:0}),d=new Map([["input",i]]);return e.evaluate(r,d)}rowName(e,t){let o=Je(e.name)||"row",i=o,r=2;for(;t.has(i);)i=`${o}-${r++}`;return t.add(i),i}};function Do(n){return Qe(n)?n.value:Array.isArray(n)?n.map(Do):n}function ba(n){let e=E(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function jo(n,e,t){let o=_a(n,e,t);if(!o)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return o}function _a(n,e,t){let o;for(let i of n){if(!(i instanceof g))continue;let r=E(i);!r||r.publisher!==e||r.package_!==t||!r.version||(!o||ce(r.version,o)>0)&&(o=r.version)}return o?$(o):void 0}function Pa(n){let e=new Map,t=new Map;for(let o of n){if(!(o instanceof g))continue;let i=E(o);if(!i||!i.version)continue;let r=Q(i),d=t.get(r);(!d||ce(i.version,d)>0)&&(t.set(r,i.version),e.set(r,o))}return e}function Ra(n,e){let t=Y(n,e);return t?[t]:He(n,e).filter(o=>o instanceof V)}function va(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Qe(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{Ve as ANY_PUBLISHER,Ur as AmbiguousReferenceRule,Lt as BooleanStatement,pi as CANONICAL_FORM_VERSION,_i as CREDENTIAL_EXPIRY_SKEW_SECONDS,ln as CREDENTIAL_HELPER_ENV,Ze as CREDENTIAL_HELPER_PROTOCOL_VERSION,Uo as CREDENTIAL_HELPER_TIMEOUT_MS,D as Carrier,Fr as ClassDefinitionRule,Ir as ClassHierarchyCycleRule,et as CompositeKanonakDocumentRepository,L as CredentialError,yi as DEFAULT_CONSENT_BINDING_PARAM,xt as DefinedKanonak,ci as DiamondNameClashRule,qr as DisplayLensScopeRule,Zo as DocumentLocation,nr as EdgeType,V as EmbeddedKanonak,wr as EmbeddedKanonakTypeRule,Mt as EmbeddedStatement,Ii as EntitlementDeniedError,Oi as EntitlementProducer,re as ExecCredentialProvider,Jo as FileSystemKanonakDocumentRepository,Pt as GitIgnoreFilter,or as GraphBuilder,Ct as HttpKanonakDocumentRepository,gn as INTEGRITY_PREFIX,mi as ImportBook,xr as ImportExistenceRule,Le as InMemoryKanonakDocumentRepository,st as KANONAK_USER_AGENT,wt as Kanonak,cr as KanonakDocumentPositions,tt as KanonakHttpError,M as KanonakObjectParser,di as KanonakObjectValidator,X as KanonakParser,ft as KanonakUri,fr as KanonakUriBuilder,mr as KanonakUrlResolver,Gt as KanonakVocabulary,Qr as LINE_STYLES,Cr as LinkTargetRule,Ut as ListStatement,Kt as LiteralKanonak,bt as LocalFirstRepository,_t as LockAwareRepository,ri as LookBandPathRule,ni as LookRenderer,Br as LookSemanticSvgPathRule,Wr as MarkdownLinkRule,$t as MarkdownStatement,Vr as NamespaceImportCycleRule,br as NamespacePrefixRule,er as NodeType,At as NumberStatement,Ei as OAuthDiscovery,qe as OWL_HAS_KEY,ir as OWL_RL_CLASSIFICATION_RULES,Hr as ObjectPropertyValueValidationRule,kr as OntologyValidationError,Sr as OntologyValidationResult,si as OwlOneOfRule,pn as PACKAGE_URL_TEMPLATE_ENV,ne as PackageBuilder,vr as PackageHeaderRule,wi as ProducerRepository,jr as PropertyDomainRule,Or as PropertyHierarchyCycleRule,Dr as PropertyKindRangeConsistencyRule,sr as PropertyMetadata,$r as PropertyRangeReferenceRule,Nr as PropertyRangeRequiredRule,Pr as PropertyTypeSpecificityRule,kt as PublisherConfigResolver,yt as PublisherIndex,rr as RDFS_RULES,z as Reasoner,ar as ReasoningResult,K as ReferenceKanonak,Vt as ReferenceStatement,ot as RepositoryFactory,Tr as ReservedNameShadowRule,_r as ResourceNamingRule,Ht as ResourceResolver,zt as ResourceTypeClassifier,pe as SHACL_PACKAGE,le as SHACL_PUBLISHER,ge as SH_COMP_CLASS,Z as SH_COMP_CLOSED,Se as SH_COMP_DATATYPE,q as SH_COMP_HAS_KEY,W as SH_COMP_HAS_VALUE,ke as SH_COMP_IN,he as SH_COMP_MAX_COUNT,_e as SH_COMP_MAX_INCLUSIVE,Ce as SH_COMP_MAX_LENGTH,me as SH_COMP_MIN_COUNT,be as SH_COMP_MIN_INCLUSIVE,Ee as SH_COMP_MIN_LENGTH,Pe as SH_COMP_NODE_KIND,ye as SH_COMP_PATTERN,j as SH_COMP_QUALIFIED_MAX_COUNT,H as SH_COMP_QUALIFIED_MIN_COUNT,J as SH_NODE_SHAPE,fe as SH_PROPERTY_SHAPE,Kn as SH_SHAPE,Ot as ScalarStatement,ti as SequenceNarrativeRule,ai as ShaclShapeRule,It as Statement,Nt as StringStatement,Ar as SubClassOfReferenceRule,Lr as SubPropertyOfReferenceRule,g as SubjectKanonak,Rr as SubjectKanonakTypeRequiredRule,ve as TOKEN_ENV,on as TokenCredentialProvider,tr as TripleStore,Gr as TxExpressionCompilesRule,ii as TxExpressionPathRule,jt as TypeResolver,zr as URI_DISPLAY_LABEL,Xr as URI_DISPLAY_SUMMARY,Mr as UnresolvedPredicateRule,Kr as UnresolvedReferenceRule,bn as VERSION_INDEX_FILE,Er as ValidationCache,yr as ValidationContext,gr as ValidationSeverity,fc as VersionOperator,Ne as ViewMaterializer,xi as allowAllPolicy,ut as assertHttpsUrl,Cn as assertIntegrityAsync,Et as assertPackageIdentity,xe as buildKeysModel,vt as buildLocalFirstRepository,ei as buildOntologyModel,Vo as buildReportPackageAsync,we as buildShapesModel,qt as builtinHomePackages,Bt as builtinUri,ui as canonicalForm,li as canonicalHash,Ye as carrierOf,Ci as checkCredentialAnswer,en as checkHelperAnswer,nn as checkHelperEraseAnswer,Ue as checkPackageUrlTemplate,Me as checkPackageUrlTemplates,Rt as collectKanonakFiles,ce as compareVersions,po as computeIntegrity,En as computeIntegrityAsync,fi as contentAddressedName,G as contextTypesOf,Pi as createCredentialedFetch,Bo as createVersion,pa as credentialProviderFromConfig,it as describeResponse,Ko as evaluateConformance,Zt as extractMarkdownLinks,gt as fillPackageUrlTemplate,vi as findDerivation,Jt as findMalformedReferences,ur as findMarkdownLinkAt,an as foldFlagsIntoPattern,ht as formatKanonakAddress,$ as formatVersion,nt as getGlobalCachePath,dt as getKanonakUserAgent,rt as httpError,Rn as indexedVersion,zo as isCompatibleVersion,Xo as isMajorCompatible,ze as isPropertySubject,lt as kanonakFetch,uo as loadLockFile,fo as loadVersionIndex,Sn as lockedVersion,Ie as lowerConstraint,Tt as makeUriKey,ki as narrowestScope,Ki as noopMeter,hi as normalizeHost,St as packageUrlTemplateFor,ma as packageUrlTemplatesFromConfig,mt as parseKanonakAddress,kn as parseLockFile,Si as parseScope,_n as parseVersionIndex,Go as parseVersionString,dr as parseWithPositions,bi as parseWwwAuthenticate,Qo as pickHighestDocument,vn as planVersionIndex,Yt as propertiesInScope,Xt as propertyClassOf,Jr as readSequenceConnectors,ae as readUserConfig,hr as referenceSpelling,T as referenceUris,Yr as resolveDisplayValue,Qt as resolvePropertyStep,at as retryAfterSecondsOf,Je as sanitizeName,Yo as satisfiesVersionOperator,lo as saveLockFile,mo as saveVersionIndex,gi as scopeContains,go as scopeFromCatalog,So as scopeFromClosureAsync,ko as scopeFromDocumentAsync,ho as scopeFromRepositoryAsync,yn as serializeLockFile,Pn as serializeVersionIndex,pt as setKanonakFetchRetries,ct as setKanonakUserAgent,wn as setYanked,pr as sourceSymbolAt,lr as sourceSymbols,$o as splitCommandLine,B as subjectAddress,E as subjectUri,Ge as superClassChain,oi as supportedBandKeys,Ri as tokenEnvKeyFor,Ft as tripleKey,Dt as typeReferenceUris,Q as uriKey,Wt as uriTriple,ie as userConfigPath,ee as valuesOf,Fo as versionOperatorFromChar,Wo as versionOperatorToChar,qo as versionsEqual,Xe as walkDefinedKanonaks,Zr as walkSequence};
@@ -0,0 +1,97 @@
1
+ import type { Version } from '@kanonak-protocol/types/document/models/types';
2
+ /**
3
+ * The publisher's index: every version of every package it has published,
4
+ * each with the sha256 of its bytes and whether it is yanked. A publisher
5
+ * keeps it at the root of its workspace and serves it at
6
+ * `https://{publisher}/kanonak.index`.
7
+ *
8
+ * A version's entry is written once, when the version is published, and only
9
+ * its yank ever changes: published bytes never change, and a published
10
+ * version is never removed. A yanked version is still served and still read
11
+ * wherever a text or a lock names it; it is only never taken as the newest.
12
+ *
13
+ * NORMATIVE: consumers MUST parse `kanonak.index` as YAML, and producers
14
+ * SHOULD emit it through {@link serializeVersionIndex}.
15
+ */
16
+ export declare const VERSION_INDEX_FILE = "kanonak.index";
17
+ declare const VERSION_INDEX_FORMAT = "1";
18
+ export interface IndexedVersion {
19
+ /** `sha256:` of the version's source bytes, as a lock's `integrity`. */
20
+ integrity: string;
21
+ /** Present only when the version is yanked. */
22
+ yanked?: true;
23
+ }
24
+ export interface VersionIndex {
25
+ version: typeof VERSION_INDEX_FORMAT;
26
+ publisher: string;
27
+ /** package name → version (`MAJOR.MINOR.PATCH`) → its entry. */
28
+ packages: Record<string, Record<string, IndexedVersion>>;
29
+ }
30
+ /** One version a publisher's workspace holds: what its index must agree with. */
31
+ export interface PublishedSource {
32
+ package_: string;
33
+ version: Version;
34
+ source: string;
35
+ }
36
+ /** A change {@link planVersionIndex} makes to the workspace's index. */
37
+ export interface VersionIndexChange {
38
+ kind: 'added' | 'rehashed' | 'removed';
39
+ package_: string;
40
+ version: string;
41
+ message: string;
42
+ }
43
+ /** Something the publisher's served index forbids: a published version's bytes changed, or its source is gone. */
44
+ export interface VersionIndexRefusal {
45
+ kind: 'changed' | 'removed';
46
+ package_: string;
47
+ version: string;
48
+ message: string;
49
+ }
50
+ export interface VersionIndexPlan {
51
+ index: VersionIndex;
52
+ changes: VersionIndexChange[];
53
+ refusals: VersionIndexRefusal[];
54
+ }
55
+ /**
56
+ * Parse a `kanonak.index`, and throw, naming `from` and what is wrong, on
57
+ * anything that is not one: a different format version, a version that is not
58
+ * `MAJOR.MINOR.PATCH`, an integrity that is not `sha256:` and 64 hex digits, a
59
+ * yank that is not `true`, or a field the format doesn't have.
60
+ */
61
+ export declare function parseVersionIndex(raw: string, from: string): VersionIndex;
62
+ /**
63
+ * The canonical `kanonak.index` text: generated-file header, packages sorted
64
+ * by name, and each package's versions in version order. Pure and
65
+ * deterministic, so the same index always gives the same bytes.
66
+ */
67
+ export declare function serializeVersionIndex(index: VersionIndex): string;
68
+ /** The entry an index holds for one version of one package, or undefined when it has none. */
69
+ export declare function indexedVersion(index: VersionIndex, packageName: string, version: Version): IndexedVersion | undefined;
70
+ /**
71
+ * The index a publisher's workspace should hold, with its changes and
72
+ * refusals in package and version order, given its `current` index
73
+ * (null when it has none), the versions it holds (`sources`), and the index
74
+ * its origin serves (`served`, null when it serves none, as before its first
75
+ * publication).
76
+ *
77
+ * Each source gets an entry with the sha256 of its bytes. A version the origin
78
+ * serves is published, so its bytes must still hash to the served entry and
79
+ * its source must still be there: anything else is a refusal, since a
80
+ * published version's bytes never change and it is never removed. A version
81
+ * the origin doesn't serve yet is still being written, so its entry follows
82
+ * its bytes, and goes when its source does. Yanks are carried over from
83
+ * `current`, or from `served` for an entry `current` has lost, and only
84
+ * {@link setYanked} changes one.
85
+ */
86
+ export declare function planVersionIndex(params: {
87
+ publisher: string;
88
+ current: VersionIndex | null;
89
+ sources: readonly PublishedSource[];
90
+ served: VersionIndex | null;
91
+ }): Promise<VersionIndexPlan>;
92
+ /**
93
+ * The index with one version's yank set or cleared. Throws when the index has
94
+ * no entry for it: only a version the index holds can be yanked.
95
+ */
96
+ export declare function setYanked(index: VersionIndex, packageName: string, version: Version, yanked: boolean): VersionIndex;
97
+ export {};
@@ -0,0 +1,4 @@
1
+ import { type VersionIndex } from './VersionIndex.js';
2
+ /** The `kanonak.index` at `path`, or null when there is no file there. A file that isn't one throws. */
3
+ export declare function loadVersionIndex(path: string): VersionIndex | null;
4
+ export declare function saveVersionIndex(index: VersionIndex, path: string): void;
@@ -1,3 +1,6 @@
1
1
  export { loadLockFile, saveLockFile, computeIntegrity, } from './LockFileIO.js';
2
2
  export { parseLockFile, serializeLockFile, computeIntegrityAsync, assertIntegrityAsync, lockedVersion, INTEGRITY_PREFIX, } from './LockFile.js';
3
3
  export type { LockFile, LockEntry } from './LockFile.js';
4
+ export { VERSION_INDEX_FILE, parseVersionIndex, serializeVersionIndex, indexedVersion, planVersionIndex, setYanked, } from './VersionIndex.js';
5
+ export type { VersionIndex, IndexedVersion, PublishedSource, VersionIndexChange, VersionIndexRefusal, VersionIndexPlan, } from './VersionIndex.js';
6
+ export { loadVersionIndex, saveVersionIndex } from './VersionIndexIO.js';
@@ -1,18 +1,17 @@
1
1
  import { PublisherConfigResolver, type PublisherConfig } from './PublisherConfig.js';
2
2
  import type { AuthenticatedFetchFn } from '../auth/index.js';
3
3
  import { type LockFile, type LockEntry } from '../lock/LockFile.js';
4
+ import { type VersionIndex } from '../lock/VersionIndex.js';
4
5
  import { type PackageUrlTemplates } from './PackageUrlTemplates.js';
5
6
  /**
6
7
  * The client for a publisher's SERVED metadata: its `.well-known/kanonak.json`
7
8
  * discovery config, its `kanonak.lock` (the resolution + integrity source for
8
- * RANGE imports), and the URLs of its raw package sources.
9
+ * RANGE imports), its `kanonak.index` (every version it has published, each
10
+ * with its sha256 and its yank), and the URLs of its raw package sources.
9
11
  *
10
- * There is deliberately NO version enumeration here. A publisher states its
11
- * current line in the lock; it does not publish a catalog of everything it has
12
- * ever released. Range imports therefore resolve against the lock's pin, while
13
- * an exact pin resolves directly against the archived
14
- * `{package}/{version}.kan.yml` URL — published versions are immutable, so the
15
- * URL space IS the archive (see `HttpKanonakDocumentRepository`).
12
+ * Range imports resolve against the lock's pin, while an exact pin resolves
13
+ * directly against the archived `{package}/{version}.kan.yml` URL (see
14
+ * `HttpKanonakDocumentRepository`).
16
15
  *
17
16
  * It is also THE place a package's source URL is chosen (#130). The
18
17
  * consumer's {@link PackageUrlTemplates}, when given, win over everything a
@@ -26,9 +25,6 @@ import { type PackageUrlTemplates } from './PackageUrlTemplates.js';
26
25
  * Discovery (`.well-known/kanonak.json`, the locks) is always read from the
27
26
  * publisher, so the sha256 a pinned version is checked against is the
28
27
  * publisher's, wherever the bytes come from.
29
- *
30
- * (The class name is historical; it indexes nothing. `PublisherSource` is the
31
- * accurate name whenever a breaking rename is acceptable.)
32
28
  */
33
29
  export declare class PublisherIndex {
34
30
  private readonly configResolver;
@@ -36,6 +32,7 @@ export declare class PublisherIndex {
36
32
  private readonly packageUrlTemplates;
37
33
  private readonly lockCache;
38
34
  private readonly packageLockCache;
35
+ private readonly versionIndexCache;
39
36
  constructor(options?: {
40
37
  configResolver?: PublisherConfigResolver;
41
38
  fetchFn?: AuthenticatedFetchFn;
@@ -84,5 +81,15 @@ export declare class PublisherIndex {
84
81
  * and memoized like the root lock.
85
82
  */
86
83
  getPackageLockEntry(publisher: string, packageName: string): Promise<LockEntry | null>;
84
+ /**
85
+ * The publisher's served `kanonak.index`: every version of every package it
86
+ * has published, each with its sha256 and its yank. Fetched once and
87
+ * memoized. Null when the publisher serves none (404), as before its first
88
+ * publication with an index. Anything else that stops it being read throws:
89
+ * a failed fetch, an index that doesn't parse, or one that is another
90
+ * publisher's.
91
+ */
92
+ getVersionIndex(publisher: string): Promise<VersionIndex | null>;
93
+ private fetchVersionIndex;
87
94
  private fetchLock;
88
95
  }
@@ -1 +1 @@
1
- import{m as e,t as r,u as n}from"../chunk-DAWT3ZAM.js";import"../chunk-SC5M74NM.js";import"../chunk-5FVUBF7N.js";import{a as o}from"../chunk-YEUSFSC7.js";import"../chunk-VAZY57HJ.js";import"../chunk-F67UH4FD.js";import"../chunk-7IMLHHSA.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
1
+ import{A as n,m as e,z as r}from"../chunk-AEH3NZLH.js";import"../chunk-SC5M74NM.js";import"../chunk-5FVUBF7N.js";import{a as o}from"../chunk-YEUSFSC7.js";import"../chunk-VAZY57HJ.js";import"../chunk-F67UH4FD.js";import"../chunk-7IMLHHSA.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 p,g as q,h as r,i as s}from"../chunk-DFXL2C6U.js";import{g,h,i,j,k,l,m,t as n,u as o}from"../chunk-DAWT3ZAM.js";import"../chunk-SC5M74NM.js";import"../chunk-5FVUBF7N.js";import{a}from"../chunk-YEUSFSC7.js";import"../chunk-VAZY57HJ.js";import"../chunk-F67UH4FD.js";import"../chunk-7IMLHHSA.js";import"../chunk-PC3DHZGV.js";export{g as ANY_PUBLISHER,d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,o as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,p as LocalFirstRepository,q as LockAwareRepository,m as PublisherConfigResolver,n as PublisherIndex,f as RepositoryFactory,s as buildLocalFirstRepository,i as checkPackageUrlTemplate,h as checkPackageUrlTemplates,r as collectKanonakFiles,l as defaultPublisherConfig,k as fillPackageUrlTemplate,e as getGlobalCachePath,j as packageUrlTemplateFor};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as p,g as q,h as r,i as s}from"../chunk-7PTZF5LK.js";import{A as o,g,h,i,j,k,l,m,z as n}from"../chunk-AEH3NZLH.js";import"../chunk-SC5M74NM.js";import"../chunk-5FVUBF7N.js";import{a}from"../chunk-YEUSFSC7.js";import"../chunk-VAZY57HJ.js";import"../chunk-F67UH4FD.js";import"../chunk-7IMLHHSA.js";import"../chunk-PC3DHZGV.js";export{g as ANY_PUBLISHER,d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,o as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,p as LocalFirstRepository,q as LockAwareRepository,m as PublisherConfigResolver,n as PublisherIndex,f as RepositoryFactory,s as buildLocalFirstRepository,i as checkPackageUrlTemplate,h as checkPackageUrlTemplates,r as collectKanonakFiles,l as defaultPublisherConfig,k as fillPackageUrlTemplate,e as getGlobalCachePath,j as packageUrlTemplateFor};
@@ -23,5 +23,6 @@ export declare function assembleServerModel(params: {
23
23
  renderStack: RenderStackReport;
24
24
  producers?: readonly IPackageProducer[];
25
25
  lockSource?: string;
26
+ indexSource?: string;
26
27
  configSource?: string;
27
28
  }): ServerModel;
@@ -1,4 +1,8 @@
1
1
  export { loadServerModel } from './loadServerModel.js';
2
+ export { readWorkspacePackages, chooseServedPublisher } from './workspacePackages.js';
3
+ export type { WorkspacePackage } from './workspacePackages.js';
4
+ export { planWorkspaceVersionIndex } from './workspaceVersionIndex.js';
5
+ export type { WorkspaceVersionIndex } from './workspaceVersionIndex.js';
2
6
  export { loadResourceModel } from './loadResourceModel.js';
3
7
  export type { LoadResourceModelOptions } from './loadResourceModel.js';
4
8
  export { route } from './route.js';
@@ -1,14 +1,14 @@
1
- import{c as xe}from"../chunk-6PIWCHH6.js";import{a as ye,d as J,f as Se,h as Z}from"../chunk-DFXL2C6U.js";import{l as $e,t as X,u as Q}from"../chunk-DAWT3ZAM.js";import"../chunk-TR7PC72M.js";import"../chunk-SC5M74NM.js";import{a as O,b as W}from"../chunk-QRF7AT2M.js";import{u as te}from"../chunk-A4OVTNMT.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import{a as fe}from"../chunk-YEUSFSC7.js";import{k as re}from"../chunk-A5EAI5ZU.js";import{a as B}from"../chunk-VAZY57HJ.js";import{a as Re}from"../chunk-PEJALHXK.js";import"../chunk-TVMOJ2QS.js";import{c as we,z as ee}from"../chunk-6USORWEP.js";import"../chunk-F67UH4FD.js";import{c as V,e as j,f as L,g as Y,l as be,m as ve}from"../chunk-7IMLHHSA.js";import"../chunk-PC3DHZGV.js";import{readFileSync as le,writeFileSync as Ie,mkdirSync as Fe}from"fs";import{join as ne}from"path";import Me from"js-yaml";var Pe=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function q(r){return Pe}function C(r){return`${r.publisher}/${r.package_}`}function H(r,e=[]){let i={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},t=[];for(let o of r)if(o.origin==="missing"){let a=C(o),u=i[a]??"whatever this package contributes to rendering is lost";t.push(`Render-stack package ${a} is MISSING (${o.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${a} (as the user running the render), or restore network access to ${o.publisher}.`)}else o.resolvedButNotInCatalog&&t.push(`Render-stack package ${C(o)} resolved (${o.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let o of e)t.push(`Import edge ${o.fromNamespace} \u2192 ${o.publisher}/${o.packageName} ${o.constraint} did NOT resolve (${o.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${o.fromNamespace} authors against ${o.publisher}/${o.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${o.constraint}-compatible version of ${o.publisher}/${o.packageName} to the workspace or cache (kanonak install ${o.publisher}/${o.packageName}), or bump the import in ${o.fromNamespace}.`);return t}function oe(r){let{publisher:e,availablePublishers:i,catalog:t,lookRenderer:o,localNamespaces:a,rawByNsKey:u,renderStack:p,producers:f,lockSource:y,configSource:s}=r,d=new Map,k=new Map,l=new Map,h=new Set;for(let S of t){if(!(S instanceof we))continue;let w=S.namespace||"";if(!a.has(w))continue;d.set(`${w}/${S.name}`,S);let P=w.split("/")[1]??"",[_,M]=P.split("@");if(!_||!M)continue;let E=Y(M);E&&(h.has(P)||(h.add(P),k.has(_)||k.set(_,[]),k.get(_).push({verStr:M,version:E})),S.name===_&&l.set(P,S))}for(let S of k.values())S.sort((w,P)=>V(P.version,w.version));return{publisher:e,availablePublishers:i,catalog:t,lookRenderer:o,localNamespaces:a,rawByNsKey:u,bySubject:d,pkgVersions:k,pkgSelfByVer:l,renderStack:p,...f?{producers:f}:{},...y?{lockSource:y}:{},...s?{configSource:s}:{}}}async function de(r,e={}){let i=new B,t=new fe(i),o=[],a=[];for(let c of Z(r)){let m;try{m=le(c,"utf-8")}catch{continue}let n;try{n=i.parse(m).metadata?.namespace_}catch{continue}if(!n?.version)continue;let g=n.version;a.push({publisher:n.publisher,package_:n.package_,verStr:j(g),version:g,source:m})}a.sort((c,m)=>V(m.version,c.version));for(let c of a)await t.saveDocumentAsync(i.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),o.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let u=[...new Set(o.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!u.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${u.join(", ")||"(none)"}`)}else if(u.length===1)p=u[0];else throw u.length===0?new Error(`No Kanonak packages found under ${r}`):new Error(`Workspace has multiple publishers (${u.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,y=new Map;for(let c of o)c.publisher===p&&(f.add(`${c.publisher}/${c.package_}@${c.verStr}`),y.set(`${c.package_}@${c.verStr}`,c.source));let s=J(),d=new ye(s,!0,i),k={};e.httpCache&&(k.getFromCache=e.httpCache.getFromCache,k.onFetch=e.httpCache.onFetch),e.fetchFn&&(k.fetchFn=e.fetchFn),e.packageUrlTemplates&&(k.packageUrlTemplates=e.packageUrlTemplates);let l=e.repository??new Se(t,d,new Q(k)),h=e.log??(()=>{}),S=q(void 0),w=[],P=c=>c.map(m=>m.metadata.namespace_?.version).filter(m=>m!==void 0).sort((m,n)=>V(n,m)).map(j);if(!e.repository){h(`[render-stack] resolving ${S.length} ambient look-stack package(s); cache: ${s}`);let c=new X({...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}});for(let m of S){let n=C(m),g=await t.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(g.length>0){let v=P(g);w.push({...m,origin:"workspace",versions:v}),h(`[render-stack] ${n} \u2014 workspace (${v.join(", ")})`);continue}let b=await d.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(b.length>0){let v=P(b);w.push({...m,origin:"cache",versions:v}),h(`[render-stack] ${n} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await c.getLock(m.publisher))?.packages[`${m.publisher}/${m.package_}`];if(!$){let K=`publisher ${m.publisher} reachable but its lock does not pin ${m.package_}`;w.push({...m,origin:"missing",reason:K}),h(`[render-stack] ${n} \u2014 MISSING: ${K}`);continue}let I=$.version,{url:he,content:ke}=await c.fetchLockedSource(m.publisher,m.package_,$);await t.saveDocumentAsync(i.parse(ke),`${m.publisher}/${m.package_}@${I}`);try{let K=ne(s,m.publisher);Fe(K,{recursive:!0}),Ie(ne(K,`${m.package_}@${I}.kan.yml`),ke,"utf-8"),w.push({...m,origin:"fetched",versions:[I]}),h(`[render-stack] ${n}@${I} \u2014 fetched from ${he}, installed to cache`)}catch(K){w.push({...m,origin:"fetched",versions:[I]}),h(`[render-stack] ${n}@${I} \u2014 fetched from ${he}, but cache ${s} is NOT WRITABLE (${K.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;w.push({...m,origin:"missing",reason:$}),h(`[render-stack] ${n} \u2014 MISSING: ${$}`)}}}let _=(await t.getAllDocumentsAsync()).filter(c=>c.metadata.namespace_?.publisher===p);for(let c of S)_.push(...await l.getDocumentsByNamespaceAsync(c.publisher,c.package_));let M=[],E=await O(_,l,{onUnresolvedEdge:c=>M.push(c)}),A=l;if(!e.repository){for(let c of S)E.add(C(c));A=new W(l,E)}let T=await new re(i).parseKanonaks(A),ie=new te(T),ce=(c,m)=>ee(T,{publisher:c,package_:m,name:m}).length>0,N;if(e.repository){N=[];for(let c of S){let m=await l.getDocumentsByNamespaceAsync(c.publisher,c.package_);N.push(m.length>0?{...c,origin:"repository",versions:P(m)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else N=w.map(c=>c.origin==="missing"||ce(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let G=H(N,M);for(let c of G)h(`[render-stack] WARNING: ${c}`);let z={contractSource:"universal-default",cachePath:s,packages:N,warnings:G},D;try{D=le(ne(r,"kanonak.lock"),"utf-8")}catch{D=Ee(p,o,i)}let U;try{U=le(ne(r,".well-known","kanonak.json"),"utf-8")}catch{U=void 0}return oe({publisher:p,availablePublishers:u,catalog:T,lookRenderer:ie,localNamespaces:f,rawByNsKey:y,renderStack:z,...D?{lockSource:D}:{},...U?{configSource:U}:{}})}function Ee(r,e,i){let t=new Map;for(let a of e)a.publisher===r&&(t.has(a.package_)||t.set(a.package_,{verStr:a.verStr,source:a.source}));if(t.size===0)return;let o={};for(let a of[...t.keys()].sort()){let{verStr:u,source:p}=t.get(a),f={},y;try{y=i.parse(p).metadata?.imports}catch{y=void 0}for(let d of y?.[r]??[]){let k=t.get(d.packageName);k&&(f[`${r}/${d.packageName}`]=k.verStr)}let s={};for(let d of Object.keys(f).sort())s[d]=f[d];o[`${r}/${a}`]={version:u,resolved:`https://${r}/${a}/${u}.kan.yml`,integrity:xe(p),dependencies:s}}return Me.dump({version:"1",lastUpdated:"",packages:o},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as De,readFileSync as Ke,writeFileSync as Ve,mkdirSync as Ae}from"fs";import{join as _e}from"path";async function pe(r,e={}){let i=new B,t=ve(r),o=t.kind==="resource"?t.uri.publisher:t.publisher,a=e.log??(()=>{}),u=e.cacheRoot??J(),p=(n,g,b)=>_e(u,n,`${g}@${b}.kan.yml`),f=new Set,y=new Set,s=new Map,d=new Q({getFromCache:(n,g,b)=>{let v=p(n,g,b),$=De(v)?Ke(v,"utf-8"):null;return $!==null&&f.add(`${n}/${g}`),$},onFetch:(n,g,b,v)=>{y.add(`${n}/${g}`);try{let $=_e(u,n);Ae($,{recursive:!0}),Ve(p(n,g,b),v,"utf-8")}catch($){s.set(`${n}/${g}`,$.message),a(`[render] fetched ${n}/${g}@${b} but cache ${u} is NOT WRITABLE (${$.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}}),k=new X(e.fetchFn?{fetchFn:e.fetchFn}:void 0),l;if(t.kind==="resource"){let n=t.uri.version;l=[n?{package_:t.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:t.uri.package_}]}else if(t.kind==="package"){let n=t.version;l=[n?{package_:t.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:t.package_}]}else l=((await k.getConfig(o)).featured_packages??[]).map(g=>({package_:g}));let h=async(n,g,b)=>{try{let v=b?i.buildImport(g,"=",b,n):i.buildImport(g,"*","0.0.0",n),$=await d.getHighestCompatibleVersionAsync(n,v);return $?{doc:$}:{doc:null,error:`${n} did not resolve ${g}${b?`@${b}`:""} (not in its index, or unreachable)`}}catch(v){return{doc:null,error:v.message}}},S=[],w=[];for(let n of l){let{doc:g,error:b}=await h(o,n.package_,n.version);g?S.push(g):b&&w.push(b)}if(S.length===0)throw new Error(`Could not fetch any package for address "${r}" from publisher "${o}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let P=q(),_="universal-default",M=n=>n.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,b)=>V(b,g)).map(j);a(`[render-stack] resolving ${P.length} ambient look-stack package(s) (contract: ${_}); cache: ${u}`);let E=[],A=[];for(let n of P){let g=C(n),{doc:b,error:v}=await h(n.publisher,n.package_,void 0);if(b){E.push(b);let $=M([b]),I=y.has(g)?"fetched":f.has(g)?"cache":"fetched";A.push({...n,origin:I,versions:$}),a(`[render-stack] ${g} \u2014 ${I} (${$.join(", ")})`+(s.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:v??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${v??"unresolved"}`)}let T=[],ie=await O([...S,...E],d,{onUnresolvedEdge:n=>T.push(n)}),ce=new W(d,ie),N=await new re(i).parseKanonaks(ce),G=new te(N),z=A.map(n=>n.origin==="missing"||ee(N,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),D=H(z,T);for(let n of D)a(`[render-stack] WARNING: ${n}`);let U={contractSource:_,cachePath:u,packages:z,warnings:D},c=new Set,m=new Map;for(let n of await d.getAllDocumentsAsync()){let g=n.metadata.namespace_;if(!g?.version||g.publisher!==o)continue;let b=j(g.version),v=`${g.publisher}/${g.package_}@${b}`;c.add(v);let $=await d.getDocumentContentAsync(v);$!==null&&m.set(`${g.package_}@${b}`,$)}return oe({publisher:o,availablePublishers:[o],catalog:N,lookRenderer:G,localNamespaces:c,rawByNsKey:m,renderStack:U})}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";function se(r){let{lookRenderer:e,publisher:i,renderStack:t,catalog:o}=r,a=e.explainStylesheet(e.publisherSubject(i)),u=[...a.tokens.entries()].map(([l,h])=>({name:l,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,f={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},y=new Map;for(let l of o){let h=l.namespace;h&&y.set(h,(y.get(h)??0)+1)}let s=[...y.entries()].map(([l,h])=>({namespace:l,resources:h})).sort((l,h)=>l.namespace.localeCompare(h.namespace)),d=e.expressionFailures().map(l=>({carrier:l.carrier,stage:l.stage,reason:l.reason})),k=d.map(l=>l.stage==="compile"?`Expression carrier "${l.carrier}" did not compile: ${l.reason} Consequence: that value renders as nothing (and a parent operation consuming it may drop its whole tier). Fix: use a tx.Expression node class the runner implements, or remove the carrier.`:`Expression carrier "${l.carrier}" failed to evaluate: ${l.reason} Consequence: that value renders as nothing. Fix: correct the expression, or make a value that may be absent explicitly optional.`);return{publisher:i,renderStack:{contractSource:t.contractSource,cachePath:t.cachePath,packages:t.packages.map(l=>({package_:C(l),origin:l.origin,...l.versions!==void 0?{versions:l.versions}:{},...l.reason!==void 0?{reason:l.reason}:{},...l.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:l.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},expressionCarriers:d,catalog:s,warnings:[...t.warnings,...a.warnings.filter(l=>!t.warnings.includes(l)),...k]}}function Te(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ue(r){let e=Te,i=r.warnings.length===0,t=r.expressionCarriers.map(s=>`<tr><td><code>${e(s.carrier)}</code></td><td>${e(s.reason)}</td></tr>`).join(`
2
- `),o=r.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':r.warnings.map(s=>`<div class="warn">\u26A0 ${e(s)}</div>`).join(`
3
- `),a=r.renderStack.packages.map(s=>{let d=s.origin!=="missing"&&!s.resolvedButNotInCatalog,k=s.origin==="missing"?'<span class="bad">MISSING</span>':s.resolvedButNotInCatalog?`<span class="bad">${e(s.origin)} (not in catalog)</span>`:`<span class="good">${e(s.origin)}</span>`,l=s.reason?e(s.reason):e((s.versions??[]).join(", "));return`<tr class="${d?"":"row-bad"}"><td><code>${e(s.package_)}</code></td><td>${k}</td><td>${l}</td></tr>`}).join(`
4
- `),u=r.stylesheet.baseStylesheet,p=u.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(u.source??"")}</code> (${u.bytes} bytes, ${e(u.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${u.problem?` \u2014 ${e(u.problem)}`:""}${u.candidates.length>0?`<br>candidates considered: ${u.candidates.map(s=>`<code>${e(s)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,f=r.stylesheet.tokens.map(s=>`<tr><td><code>--kan-${e(s.name)}</code></td><td><code>${e(s.value)}</code></td><td><code>${e(s.source)}</code></td><td>${e(s.level)}</td></tr>`).join(`
5
- `),y=r.catalog.map(s=>`<tr><td><code>${e(s.namespace)}</code></td><td>${s.resources}</td></tr>`).join(`
1
+ import{c as je,d as Ne}from"../chunk-RXIKK3KZ.js";import{a as $e,d as ee,f as Pe,h as ne}from"../chunk-7PTZF5LK.js";import{A as oe,l as Re,t as K,x as xe,z as re}from"../chunk-AEH3NZLH.js";import"../chunk-TR7PC72M.js";import"../chunk-SC5M74NM.js";import{a as H,b as q}from"../chunk-QRF7AT2M.js";import{u as ae}from"../chunk-A4OVTNMT.js";import"../chunk-QHABFCRC.js";import"../chunk-5FVUBF7N.js";import{a as ve}from"../chunk-YEUSFSC7.js";import{k as se}from"../chunk-A5EAI5ZU.js";import{a as C}from"../chunk-VAZY57HJ.js";import{a as _e}from"../chunk-PEJALHXK.js";import"../chunk-TVMOJ2QS.js";import{c as Ie,z as te}from"../chunk-6USORWEP.js";import"../chunk-F67UH4FD.js";import{c as D,e as I,f as B,g as Z,l as Se,m as we}from"../chunk-7IMLHHSA.js";import"../chunk-PC3DHZGV.js";import{readFileSync as ue,writeFileSync as Ke,mkdirSync as Ae}from"fs";import{join as J}from"path";import Te from"js-yaml";import{readFileSync as De}from"fs";function G(o,e=new C){let s=[];for(let r of ne(o)){let n;try{n=De(r,"utf-8")}catch{continue}let t;try{t=e.parse(n).metadata?.namespace_}catch{continue}t?.version&&s.push({publisher:t.publisher,package_:t.package_,verStr:I(t.version),version:t.version,source:n})}return s.sort((r,n)=>D(n.version,r.version))}function z(o,e,s){let r=[...new Set(o.map(n=>n.publisher))].sort();if(s){if(!r.includes(s))throw new Error(`Publisher "${s}" not found in workspace. Available: ${r.join(", ")||"(none)"}`);return{publisher:s,availablePublishers:r}}if(r.length===1)return{publisher:r[0],availablePublishers:r};throw r.length===0?new Error(`No Kanonak packages found under ${e}`):new Error(`Workspace has multiple publishers (${r.join(", ")}). Pass --publisher <domain> to choose which one to serve.`)}var Ce=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function X(o){return Ce}function E(o){return`${o.publisher}/${o.package_}`}function Y(o,e=[]){let s={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},r=[];for(let n of o)if(n.origin==="missing"){let t=E(n),u=s[t]??"whatever this package contributes to rendering is lost";r.push(`Render-stack package ${t} is MISSING (${n.reason??"unknown reason"}) \u2014 ${u}. Fix: kanonak install ${t} (as the user running the render), or restore network access to ${n.publisher}.`)}else n.resolvedButNotInCatalog&&r.push(`Render-stack package ${E(n)} resolved (${n.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let n of e)r.push(`Import edge ${n.fromNamespace} \u2192 ${n.publisher}/${n.packageName} ${n.constraint} did NOT resolve (${n.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${n.fromNamespace} authors against ${n.publisher}/${n.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${n.constraint}-compatible version of ${n.publisher}/${n.packageName} to the workspace or cache (kanonak install ${n.publisher}/${n.packageName}), or bump the import in ${n.fromNamespace}.`);return r}function ie(o){let{publisher:e,availablePublishers:s,catalog:r,lookRenderer:n,localNamespaces:t,rawByNsKey:u,renderStack:p,producers:f,lockSource:h,indexSource:a,configSource:l}=o,y=new Map,c=new Map,k=new Map,R=new Set;for(let x of r){if(!(x instanceof Ie))continue;let _=x.namespace||"";if(!t.has(_))continue;y.set(`${_}/${x.name}`,x);let P=_.split("/")[1]??"",[j,F]=P.split("@");if(!j||!F)continue;let N=Z(F);N&&(R.has(P)||(R.add(P),c.has(j)||c.set(j,[]),c.get(j).push({verStr:F,version:N})),x.name===j&&k.set(P,x))}for(let x of c.values())x.sort((_,P)=>D(P.version,_.version));return{publisher:e,availablePublishers:s,catalog:r,lookRenderer:n,localNamespaces:t,rawByNsKey:u,bySubject:y,pkgVersions:c,pkgSelfByVer:k,renderStack:p,...f?{producers:f}:{},...h?{lockSource:h}:{},...a?{indexSource:a}:{},...l?{configSource:l}:{}}}async function ge(o,e={}){let s=new C,r=new ve(s),n=G(o,s);for(let d of n)await r.saveDocumentAsync(s.parse(d.source),`${d.publisher}/${d.package_}@${d.verStr}`);let{publisher:t,availablePublishers:u}=z(n,o,e.publisher),p=new Set,f=new Map;for(let d of n)d.publisher===t&&(p.add(`${d.publisher}/${d.package_}@${d.verStr}`),f.set(`${d.package_}@${d.verStr}`,d.source));let h=ee(),a=new $e(h,!0,s),l={};e.httpCache&&(l.getFromCache=e.httpCache.getFromCache,l.onFetch=e.httpCache.onFetch),e.fetchFn&&(l.fetchFn=e.fetchFn),e.packageUrlTemplates&&(l.packageUrlTemplates=e.packageUrlTemplates);let y=e.repository??new Pe(r,a,new oe(l)),c=e.log??(()=>{}),k=X(void 0),R=[],x=d=>d.map(m=>m.metadata.namespace_?.version).filter(m=>m!==void 0).sort((m,i)=>D(i,m)).map(I);if(!e.repository){c(`[render-stack] resolving ${k.length} ambient look-stack package(s); cache: ${h}`);let d=new re({...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}});for(let m of k){let i=E(m),g=await r.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(g.length>0){let v=x(g);R.push({...m,origin:"workspace",versions:v}),c(`[render-stack] ${i} \u2014 workspace (${v.join(", ")})`);continue}let b=await a.getDocumentsByNamespaceAsync(m.publisher,m.package_);if(b.length>0){let v=x(b);R.push({...m,origin:"cache",versions:v}),c(`[render-stack] ${i} \u2014 cache (${v.join(", ")})`);continue}try{let $=(await d.getLock(m.publisher))?.packages[`${m.publisher}/${m.package_}`];if(!$){let L=`publisher ${m.publisher} reachable but its lock does not pin ${m.package_}`;R.push({...m,origin:"missing",reason:L}),c(`[render-stack] ${i} \u2014 MISSING: ${L}`);continue}let M=$.version,{url:ye,content:be}=await d.fetchLockedSource(m.publisher,m.package_,$);await r.saveDocumentAsync(s.parse(be),`${m.publisher}/${m.package_}@${M}`);try{let L=J(h,m.publisher);Ae(L,{recursive:!0}),Ke(J(L,`${m.package_}@${M}.kan.yml`),be,"utf-8"),R.push({...m,origin:"fetched",versions:[M]}),c(`[render-stack] ${i}@${M} \u2014 fetched from ${ye}, installed to cache`)}catch(L){R.push({...m,origin:"fetched",versions:[M]}),c(`[render-stack] ${i}@${M} \u2014 fetched from ${ye}, but cache ${h} is NOT WRITABLE (${L.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(v){let $=`fetch failed: ${v.message}`;R.push({...m,origin:"missing",reason:$}),c(`[render-stack] ${i} \u2014 MISSING: ${$}`)}}}let _=(await r.getAllDocumentsAsync()).filter(d=>d.metadata.namespace_?.publisher===t);for(let d of k)_.push(...await y.getDocumentsByNamespaceAsync(d.publisher,d.package_));let P=[],j=await H(_,y,{onUnresolvedEdge:d=>P.push(d)}),F=y;if(!e.repository){for(let d of k)j.add(E(d));F=new q(y,j)}let N=await new se(s).parseKanonaks(F),Q=new ae(N),de=(d,m)=>te(N,{publisher:d,package_:m,name:m}).length>0,A;if(e.repository){A=[];for(let d of k){let m=await y.getDocumentsByNamespaceAsync(d.publisher,d.package_);A.push(m.length>0?{...d,origin:"repository",versions:x(m)}:{...d,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=R.map(d=>d.origin==="missing"||de(d.publisher,d.package_)?d:{...d,resolvedButNotInCatalog:!0});let O=Y(A,P);for(let d of O)c(`[render-stack] WARNING: ${d}`);let pe={contractSource:"universal-default",cachePath:h,packages:A,warnings:O},T;try{T=ue(J(o,"kanonak.lock"),"utf-8")}catch{T=Ue(t,n,s)}let U;try{U=ue(J(o,K),"utf-8")}catch{U=void 0}let W;try{W=ue(J(o,".well-known","kanonak.json"),"utf-8")}catch{W=void 0}return ie({publisher:t,availablePublishers:u,catalog:N,lookRenderer:Q,localNamespaces:p,rawByNsKey:f,renderStack:pe,...T?{lockSource:T}:{},...U?{indexSource:U}:{},...W?{configSource:W}:{}})}function Ue(o,e,s){let r=new Map;for(let t of e)t.publisher===o&&(r.has(t.package_)||r.set(t.package_,{verStr:t.verStr,source:t.source}));if(r.size===0)return;let n={};for(let t of[...r.keys()].sort()){let{verStr:u,source:p}=r.get(t),f={},h;try{h=s.parse(p).metadata?.imports}catch{h=void 0}for(let l of h?.[o]??[]){let y=r.get(l.packageName);y&&(f[`${o}/${l.packageName}`]=y.verStr)}let a={};for(let l of Object.keys(f).sort())a[l]=f[l];n[`${o}/${t}`]={version:u,resolved:`https://${o}/${t}/${u}.kan.yml`,integrity:je(p),dependencies:a}}return Te.dump({version:"1",lastUpdated:"",packages:n},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{join as Le}from"path";async function Oe(o,e){let s=G(o,new C),{publisher:r}=z(s,o,e.publisher),n=Le(o,K),t=Ne(n),u=await e.publisherIndex.getVersionIndex(r),p=s.filter(h=>h.publisher===r).map(h=>({package_:h.package_,version:h.version,source:h.source})),f=await xe({publisher:r,current:t,sources:p,served:u});return{publisher:r,path:n,current:t,served:u,plan:f}}import{existsSync as We,readFileSync as Be,writeFileSync as He,mkdirSync as qe}from"fs";import{join as Ee}from"path";async function me(o,e={}){let s=new C,r=we(o),n=r.kind==="resource"?r.uri.publisher:r.publisher,t=e.log??(()=>{}),u=e.cacheRoot??ee(),p=(i,g,b)=>Ee(u,i,`${g}@${b}.kan.yml`),f=new Set,h=new Set,a=new Map,l=new oe({getFromCache:(i,g,b)=>{let v=p(i,g,b),$=We(v)?Be(v,"utf-8"):null;return $!==null&&f.add(`${i}/${g}`),$},onFetch:(i,g,b,v)=>{h.add(`${i}/${g}`);try{let $=Ee(u,i);qe($,{recursive:!0}),He(p(i,g,b),v,"utf-8")}catch($){a.set(`${i}/${g}`,$.message),t(`[render] fetched ${i}/${g}@${b} but cache ${u} is NOT WRITABLE (${$.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{},...e.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}}),y=new re(e.fetchFn?{fetchFn:e.fetchFn}:void 0),c;if(r.kind==="resource"){let i=r.uri.version;c=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;c=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else c=((await y.getConfig(n)).featured_packages??[]).map(g=>({package_:g}));let k=async(i,g,b)=>{try{let v=b?s.buildImport(g,"=",b,i):s.buildImport(g,"*","0.0.0",i),$=await l.getHighestCompatibleVersionAsync(i,v);return $?{doc:$}:{doc:null,error:`${i} did not resolve ${g}${b?`@${b}`:""} (not in its index, or unreachable)`}}catch(v){return{doc:null,error:v.message}}},R=[],x=[];for(let i of c){let{doc:g,error:b}=await k(n,i.package_,i.version);g?R.push(g):b&&x.push(b)}if(R.length===0)throw new Error(`Could not fetch any package for address "${o}" from publisher "${n}".`+(x.length>0?` Reasons: ${x.join("; ")}`:""));let _=X(),P="universal-default",j=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,b)=>D(b,g)).map(I);t(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${P}); cache: ${u}`);let F=[],N=[];for(let i of _){let g=E(i),{doc:b,error:v}=await k(i.publisher,i.package_,void 0);if(b){F.push(b);let $=j([b]),M=h.has(g)?"fetched":f.has(g)?"cache":"fetched";N.push({...i,origin:M,versions:$}),t(`[render-stack] ${g} \u2014 ${M} (${$.join(", ")})`+(a.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else N.push({...i,origin:"missing",reason:v??"unresolved"}),t(`[render-stack] ${g} \u2014 MISSING: ${v??"unresolved"}`)}let Q=[],de=await H([...R,...F],l,{onUnresolvedEdge:i=>Q.push(i)}),A=new q(l,de),O=await new se(s).parseKanonaks(A),pe=new ae(O),T=N.map(i=>i.origin==="missing"||te(O,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),U=Y(T,Q);for(let i of U)t(`[render-stack] WARNING: ${i}`);let W={contractSource:P,cachePath:u,packages:T,warnings:U},d=new Set,m=new Map;for(let i of await l.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==n)continue;let b=I(g.version),v=`${g.publisher}/${g.package_}@${b}`;d.add(v);let $=await l.getDocumentContentAsync(v);$!==null&&m.set(`${g.package_}@${b}`,$)}return ie({publisher:n,availablePublishers:[n],catalog:O,lookRenderer:pe,localNamespaces:d,rawByNsKey:m,renderStack:W})}import{VersionOperator as le}from"@kanonak-protocol/types/document/models/enums";function ce(o){let{lookRenderer:e,publisher:s,renderStack:r,catalog:n}=o,t=e.explainStylesheet(e.publisherSubject(s)),u=[...t.tokens.entries()].map(([c,k])=>({name:c,value:k.value,source:`${k.sourceNamespace}/${k.sourceName}`,level:k.level})),p=t.baseStylesheet,f={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},h=new Map;for(let c of n){let k=c.namespace;k&&h.set(k,(h.get(k)??0)+1)}let a=[...h.entries()].map(([c,k])=>({namespace:c,resources:k})).sort((c,k)=>c.namespace.localeCompare(k.namespace)),l=e.expressionFailures().map(c=>({carrier:c.carrier,stage:c.stage,reason:c.reason})),y=l.map(c=>c.stage==="compile"?`Expression carrier "${c.carrier}" did not compile: ${c.reason} Consequence: that value renders as nothing (and a parent operation consuming it may drop its whole tier). Fix: use a tx.Expression node class the runner implements, or remove the carrier.`:`Expression carrier "${c.carrier}" failed to evaluate: ${c.reason} Consequence: that value renders as nothing. Fix: correct the expression, or make a value that may be absent explicitly optional.`);return{publisher:s,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(c=>({package_:E(c),origin:c.origin,...c.versions!==void 0?{versions:c.versions}:{},...c.reason!==void 0?{reason:c.reason}:{},...c.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:c.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:u,baseStylesheet:f,...t.look?{look:{sourceClass:`${t.look.sourceClass.publisher}/${t.look.sourceClass.package_}/${t.look.sourceClass.name}`}}:{}},expressionCarriers:l,catalog:a,warnings:[...r.warnings,...t.warnings.filter(c=>!r.warnings.includes(c)),...y]}}function Ge(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function he(o){let e=Ge,s=o.warnings.length===0,r=o.expressionCarriers.map(a=>`<tr><td><code>${e(a.carrier)}</code></td><td>${e(a.reason)}</td></tr>`).join(`
2
+ `),n=o.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':o.warnings.map(a=>`<div class="warn">\u26A0 ${e(a)}</div>`).join(`
3
+ `),t=o.renderStack.packages.map(a=>{let l=a.origin!=="missing"&&!a.resolvedButNotInCatalog,y=a.origin==="missing"?'<span class="bad">MISSING</span>':a.resolvedButNotInCatalog?`<span class="bad">${e(a.origin)} (not in catalog)</span>`:`<span class="good">${e(a.origin)}</span>`,c=a.reason?e(a.reason):e((a.versions??[]).join(", "));return`<tr class="${l?"":"row-bad"}"><td><code>${e(a.package_)}</code></td><td>${y}</td><td>${c}</td></tr>`}).join(`
4
+ `),u=o.stylesheet.baseStylesheet,p=u.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(u.source??"")}</code> (${u.bytes} bytes, ${e(u.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${u.problem?` \u2014 ${e(u.problem)}`:""}${u.candidates.length>0?`<br>candidates considered: ${u.candidates.map(a=>`<code>${e(a)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,f=o.stylesheet.tokens.map(a=>`<tr><td><code>--kan-${e(a.name)}</code></td><td><code>${e(a.value)}</code></td><td><code>${e(a.source)}</code></td><td>${e(a.level)}</td></tr>`).join(`
5
+ `),h=o.catalog.map(a=>`<tr><td><code>${e(a.namespace)}</code></td><td>${a.resources}</td></tr>`).join(`
6
6
  `);return`<!doctype html>
7
7
  <html lang="en">
8
8
  <head>
9
9
  <meta charset="utf-8">
10
10
  <meta name="viewport" content="width=device-width,initial-scale=1">
11
- <title>Render diagnostics \u2014 ${e(r.publisher)}</title>
11
+ <title>Render diagnostics \u2014 ${e(o.publisher)}</title>
12
12
  <style>
13
13
  body { font-family: system-ui, sans-serif; max-width: 64rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; color: #1a1a1a; background: #fff; }
14
14
  h1 { font-size: 1.5rem; } h2 { font-size: 1.15rem; margin-top: 2rem; border-bottom: 1px solid #ddd; padding-bottom: .25rem; }
@@ -22,23 +22,23 @@ import{c as xe}from"../chunk-6PIWCHH6.js";import{a as ye,d as J,f as Se,h as Z}f
22
22
  .row-bad td { background: #fff5f5; }
23
23
  .meta { color: #666; font-size: .85rem; }
24
24
  .status-banner { font-size: 1.1rem; padding: .5rem 1rem; border-radius: 6px; display: inline-block; margin-bottom: 1rem;
25
- background: ${i?"#ecfdf3":"#fef2f2"}; border: 1px solid ${i?"#0a7d33":"#b91c1c"}; }
25
+ background: ${s?"#ecfdf3":"#fef2f2"}; border: 1px solid ${s?"#0a7d33":"#b91c1c"}; }
26
26
  </style>
27
27
  </head>
28
28
  <body>
29
- <h1>Render diagnostics \u2014 ${e(r.publisher)}</h1>
30
- <p class="status-banner">${i?"\u2713 Healthy":`\u2717 ${r.warnings.length} problem(s) found`}</p>
29
+ <h1>Render diagnostics \u2014 ${e(o.publisher)}</h1>
30
+ <p class="status-banner">${s?"\u2713 Healthy":`\u2717 ${o.warnings.length} problem(s) found`}</p>
31
31
  <p class="meta">Machine-readable version: <a href="/.well-known/kanonak-render.json"><code>/.well-known/kanonak-render.json</code></a></p>
32
32
 
33
33
  <h2>Problems</h2>
34
- ${o}
34
+ ${n}
35
35
 
36
36
  <h2>Ambient render stack</h2>
37
37
  <p class="meta">The look stack is discovered, not imported \u2014 these packages must be resolvable for any publisher's pages to render styled.
38
- Contract: <code>${e(r.renderStack.contractSource)}</code> \xB7 Package cache: <code>${e(r.renderStack.cachePath)}</code></p>
38
+ Contract: <code>${e(o.renderStack.contractSource)}</code> \xB7 Package cache: <code>${e(o.renderStack.cachePath)}</code></p>
39
39
  <table>
40
40
  <tr><th>Package</th><th>Origin</th><th>Versions / reason</th></tr>
41
- ${a}
41
+ ${t}
42
42
  </table>
43
43
 
44
44
  <h2>Base stylesheet</h2>
@@ -47,26 +47,26 @@ ${p}
47
47
 
48
48
  <h2>Design tokens (:root)</h2>
49
49
  <p class="meta">Resolved for the publisher landing page. Each token shows which resource in the cascade supplied it.</p>
50
- ${r.stylesheet.tokens.length===0?'<p><span class="bad">\u2717 No tokens resolved</span></p>':`<table>
50
+ ${o.stylesheet.tokens.length===0?'<p><span class="bad">\u2717 No tokens resolved</span></p>':`<table>
51
51
  <tr><th>Token</th><th>Value</th><th>Declared by</th><th>Cascade level</th></tr>
52
52
  ${f}
53
53
  </table>`}
54
54
 
55
55
  <h2>Look (page body)</h2>
56
- ${r.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <code>${e(r.stylesheet.look.sourceClass)}</code></p>`:'<p><span class="bad">\u2717 No look resolved</span> \u2014 the page body renders as an empty comment.</p>'}
56
+ ${o.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <code>${e(o.stylesheet.look.sourceClass)}</code></p>`:'<p><span class="bad">\u2717 No look resolved</span> \u2014 the page body renders as an empty comment.</p>'}
57
57
 
58
58
  <h2>Expression carriers</h2>
59
59
  <p class="meta">Authored <code>tx.Expression</code> carriers (band paths, <code>semanticSvg</code> tiers) that failed to compile while rendering this page. A carrier that does not compile contributes nothing to the output.</p>
60
- ${r.expressionCarriers.length===0?'<p><span class="good">\u2713</span> Every expression carrier on this page compiled.</p>':`<table>
60
+ ${o.expressionCarriers.length===0?'<p><span class="good">\u2713</span> Every expression carrier on this page compiled.</p>':`<table>
61
61
  <tr><th>Carrier</th><th>Reason</th></tr>
62
- ${t}
62
+ ${r}
63
63
  </table>`}
64
64
 
65
- <h2>Render catalog (${r.catalog.length} package version(s))</h2>
65
+ <h2>Render catalog (${o.catalog.length} package version(s))</h2>
66
66
  <p class="meta">Everything the renderer can see for this publisher \u2014 the served packages, their import closure, and the ambient render stack.</p>
67
67
  <table>
68
68
  <tr><th>Package version</th><th>Resources</th></tr>
69
- ${y}
69
+ ${h}
70
70
  </table>
71
71
  </body>
72
- </html>`}var R={".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"},x=(r,e,i,t)=>({status:r,headers:{"Content-Type":e,...t||{}},body:i}),F=r=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${r}</p>`),Ue=r=>({status:301,headers:{Location:r},body:""}),Be=r=>({status:302,headers:{Location:r},body:""});function Le(r){switch(r.kind){case"exact":return{operator:ae.Exact,version:L(r.major,r.minor,r.patch)};case"minor-pin":return{operator:ae.Compatible,version:L(r.major,r.minor,0)};case"major-pin":return{operator:ae.Major,version:L(r.major,0,0)};default:return{operator:ae.Any,version:L(0,0,0)}}}async function Oe(r,e,i,t){if(!t)return null;let o=r.producers?.find(f=>f.canProduce(r.publisher,e));if(!o)return null;let a=await o.resolveVersion(r.publisher,e,Le(i));if(!a)return null;let u=j(a);if(i.kind!=="exact")return Be(`/${e}/${u}.kan.yml`);let{source:p}=await o.produce(r.publisher,e,a);return x(200,R[".kan.yml"],p)}function je(r,e,i){let t=r.pkgVersions.get(e);if(!t||t.length===0)return null;switch(i.kind){case"any":return t[0].verStr;case"major-pin":return t.find(o=>o.version.major===i.major)?.verStr??null;case"minor-pin":return t.find(o=>o.version.major===i.major&&o.version.minor===i.minor)?.verStr??null;case"exact":return t.find(o=>o.version.major===i.major&&o.version.minor===i.minor&&o.version.patch===i.patch)?.verStr??null;default:return null}}async function ge(r,e,i=""){let{lookRenderer:t,publisher:o}=r;if(e==="/.well-known/kanonak.json")return r.configSource?x(200,R[".json"],r.configSource):x(200,R[".json"],JSON.stringify($e(),null,2));if(e==="/kanonak.lock")return r.lockSource?x(200,R[".kan.yml"],r.lockSource):F(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(se(r),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],ue(se(r)));if(e==="/"||e==="/index.html"||e==="/index.css"){let d=t.publisherSubject(o);return e==="/index.css"?x(200,R[".css"],t.renderStylesheet(d)):x(200,R[".html"],await t.renderDocument(d,{rootIndex:!0}))}let a=".html",u=!1,p=e;for(let d of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(d)){a=d,u=!0,p=e.slice(0,-d.length);break}let f=!u&&/application\/yaml|text\/yaml/i.test(i),y=p.endsWith("/");y&&p!=="/"&&(p=p.slice(0,-1));let s=Re.parse(p,o);if(!s)return F(e);if(s.kind==="package"){let d=je(r,s.package_,s.versionSpec);if(!d)return await Oe(r,s.package_,s.versionSpec,a===".kan.yml"||f)??F(e);if(a===".kan.yml"||f){let h=r.rawByNsKey.get(`${s.package_}@${d}`);return h!==void 0?x(200,R[".kan.yml"],h):F(e)}let k=r.pkgSelfByVer.get(`${s.package_}@${d}`);if(!k)return F(e);if(a===".css")return x(200,R[".css"],t.renderStylesheet(k));if(!y)return Ue(p+"/");let l=s.versionSpec.kind==="any";if(l&&!t.hasDeclaredView(k)){let h=(r.pkgVersions.get(s.package_)||[]).map(S=>S.verStr);return x(200,R[".html"],t.renderPackageVersionList(s.package_,h,k))}return x(200,R[".html"],await t.renderDocument(k,l?{bareOverview:!0}:void 0))}if(s.kind==="resource"){let d=je(r,s.package_,s.versionSpec);if(!d)return F(e);let k=r.bySubject.get(`${o}/${s.package_}@${d}/${s.name}`);if(!k)return F(e);switch(a){case".css":return x(200,R[".css"],t.renderStylesheet(k));case".svg":return x(200,R[".svg"],await t.renderSvg(k));case".md":{let l=t.renderRawMarkdown(k);return l===void 0?F(e):x(200,R[".md"],l)}default:return x(200,R[".html"],await t.renderDocument(k))}}return F(e)}import{readFileSync as We}from"fs";var Ce=/^\d+\.\d+\.\d+$/,me=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,i=new Set;if(this.options.root!==void 0){let t=new B;for(let o of Z(this.options.root))try{let a=t.parse(We(o,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let u=a.version;e.add(`${a.publisher}/${a.package_}@${u.major}.${u.minor}.${u.patch}`),i.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:i},this.workspaceIndex}async modelFor(e,i,t){let o=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.packageUrlTemplates?{packageUrlTemplates:this.options.packageUrlTemplates}:{},...this.options.log?{log:this.options.log}:{}},u=i?t?o.exact.has(`${e}/${i}@${t}`):o.pkgs.has(`${e}/${i}`):[...o.pkgs].some(d=>d.startsWith(`${e}/`)),p,f;if(u&&this.options.root!==void 0){let d=this.options.root;p=`ws:${e}`,f=()=>de(d,{publisher:e,...a})}else{let d=i?t?`${e}/${i}@${t}`:`${e}/${i}`:e;p=`rm:${d}`,f=()=>pe(d,a)}let y=this.models.get(p);if(y)return y;let s=await f();return s.lookRenderer.setLinkMode("open-world"),this.models.set(p,s),s}async handle(e,i=""){let t=e.split("/").filter(Boolean);if(t.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Ne()};let o=t[0];if(!o.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let a=t.length>=2&&(t[1]==="index.html"||t[1]==="index.css"||t[1]==="kanonak.lock"||t[1]===".well-known"),u=!a&&t.length>=2?t[1]:void 0,p=!a&&t.length>=3&&Ce.test(t[2])?t[2]:void 0,f=await this.modelFor(o,u,p),y=e.endsWith("/")&&t.length>1?"/":"",s="/"+t.slice(1).join("/")+y,d=await ge(f,s,i);return d.headers.Location?{...d,headers:{...d.headers,Location:`/${o}${d.headers.Location}`}}:d}};function qe(r){switch(r.kind){case"publisher":return`/${r.publisher}/`;case"package":return r.version?`/${r.publisher}/${r.package_}/${j(r.version)}/`:`/${r.publisher}/${r.package_}/`;case"resource":{let e=r.uri;return e.version?`/${e.publisher}/${e.package_}/${j(e.version)}/${e.name}`:`/${e.publisher}/${e.package_}/${e.name}`}}}function He(r){let e=r.split("/").filter(Boolean),i=e[0];if(!i||!i.includes("."))return;let t=e[1];if(!t)return{kind:"publisher",publisher:i};let o=e[2]&&Ce.test(e[2])?Y(e[2])??void 0:void 0,a=o?e[3]:e[2];return a?{kind:"resource",uri:new be(i,t,a,o)}:o?{kind:"package",publisher:i,package_:t,version:o}:{kind:"package",publisher:i,package_:t}}function Ne(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{W as ClosureScopedRepository,me as RequestRouter,Pe as UNIVERSAL_RENDER_BASE,He as addressForRequestPath,se as buildRenderDiagnostics,H as buildRenderStackWarnings,O as deriveImportClosure,Ne as landingPage,pe as loadResourceModel,de as loadServerModel,ue as renderDiagnosticsHtml,C as renderRefKey,qe as requestPathFor,q as resolveRenderContract,ge as route};
72
+ </html>`}var S={".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"},w=(o,e,s,r)=>({status:o,headers:{"Content-Type":e,...r||{}},body:s}),V=o=>w(404,S[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${o}</p>`),ze=o=>({status:301,headers:{Location:o},body:""}),Xe=o=>({status:302,headers:{Location:o},body:""});function Ye(o){switch(o.kind){case"exact":return{operator:le.Exact,version:B(o.major,o.minor,o.patch)};case"minor-pin":return{operator:le.Compatible,version:B(o.major,o.minor,0)};case"major-pin":return{operator:le.Major,version:B(o.major,0,0)};default:return{operator:le.Any,version:B(0,0,0)}}}async function Je(o,e,s,r){if(!r)return null;let n=o.producers?.find(f=>f.canProduce(o.publisher,e));if(!n)return null;let t=await n.resolveVersion(o.publisher,e,Ye(s));if(!t)return null;let u=I(t);if(s.kind!=="exact")return Xe(`/${e}/${u}.kan.yml`);let{source:p}=await n.produce(o.publisher,e,t);return w(200,S[".kan.yml"],p)}function Ve(o,e,s){let r=o.pkgVersions.get(e);if(!r||r.length===0)return null;switch(s.kind){case"any":return r[0].verStr;case"major-pin":return r.find(n=>n.version.major===s.major)?.verStr??null;case"minor-pin":return r.find(n=>n.version.major===s.major&&n.version.minor===s.minor)?.verStr??null;case"exact":return r.find(n=>n.version.major===s.major&&n.version.minor===s.minor&&n.version.patch===s.patch)?.verStr??null;default:return null}}async function ke(o,e,s=""){let{lookRenderer:r,publisher:n}=o;if(e==="/.well-known/kanonak.json")return o.configSource?w(200,S[".json"],o.configSource):w(200,S[".json"],JSON.stringify(Re(),null,2));if(e==="/kanonak.lock")return o.lockSource?w(200,S[".kan.yml"],o.lockSource):V(e);if(e===`/${K}`)return o.indexSource?w(200,S[".kan.yml"],o.indexSource):V(e);if(e==="/.well-known/kanonak-render.json")return w(200,S[".json"],JSON.stringify(ce(o),null,2));if(e==="/.well-known/kanonak-render")return w(200,S[".html"],he(ce(o)));if(e==="/"||e==="/index.html"||e==="/index.css"){let l=r.publisherSubject(n);return e==="/index.css"?w(200,S[".css"],r.renderStylesheet(l)):w(200,S[".html"],await r.renderDocument(l,{rootIndex:!0}))}let t=".html",u=!1,p=e;for(let l of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(l)){t=l,u=!0,p=e.slice(0,-l.length);break}let f=!u&&/application\/yaml|text\/yaml/i.test(s),h=p.endsWith("/");h&&p!=="/"&&(p=p.slice(0,-1));let a=_e.parse(p,n);if(!a)return V(e);if(a.kind==="package"){let l=Ve(o,a.package_,a.versionSpec);if(!l)return await Je(o,a.package_,a.versionSpec,t===".kan.yml"||f)??V(e);if(t===".kan.yml"||f){let k=o.rawByNsKey.get(`${a.package_}@${l}`);return k!==void 0?w(200,S[".kan.yml"],k):V(e)}let y=o.pkgSelfByVer.get(`${a.package_}@${l}`);if(!y)return V(e);if(t===".css")return w(200,S[".css"],r.renderStylesheet(y));if(!h)return ze(p+"/");let c=a.versionSpec.kind==="any";if(c&&!r.hasDeclaredView(y)){let k=(o.pkgVersions.get(a.package_)||[]).map(R=>R.verStr);return w(200,S[".html"],r.renderPackageVersionList(a.package_,k,y))}return w(200,S[".html"],await r.renderDocument(y,c?{bareOverview:!0}:void 0))}if(a.kind==="resource"){let l=Ve(o,a.package_,a.versionSpec);if(!l)return V(e);let y=o.bySubject.get(`${n}/${a.package_}@${l}/${a.name}`);if(!y)return V(e);switch(t){case".css":return w(200,S[".css"],r.renderStylesheet(y));case".svg":return w(200,S[".svg"],await r.renderSvg(y));case".md":{let c=r.renderRawMarkdown(y);return c===void 0?V(e):w(200,S[".md"],c)}default:return w(200,S[".html"],await r.renderDocument(y))}}return V(e)}import{readFileSync as Qe}from"fs";var Fe=/^\d+\.\d+\.\d+$/,fe=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,s=new Set;if(this.options.root!==void 0){let r=new C;for(let n of ne(this.options.root))try{let t=r.parse(Qe(n,"utf-8")).metadata?.namespace_;if(!t?.version)continue;let u=t.version;e.add(`${t.publisher}/${t.package_}@${u.major}.${u.minor}.${u.patch}`),s.add(`${t.publisher}/${t.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:s},this.workspaceIndex}async modelFor(e,s,r){let n=this.getWorkspaceIndex(),t={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.packageUrlTemplates?{packageUrlTemplates:this.options.packageUrlTemplates}:{},...this.options.log?{log:this.options.log}:{}},u=s?r?n.exact.has(`${e}/${s}@${r}`):n.pkgs.has(`${e}/${s}`):[...n.pkgs].some(l=>l.startsWith(`${e}/`)),p,f;if(u&&this.options.root!==void 0){let l=this.options.root;p=`ws:${e}`,f=()=>ge(l,{publisher:e,...t})}else{let l=s?r?`${e}/${s}@${r}`:`${e}/${s}`:e;p=`rm:${l}`,f=()=>me(l,t)}let h=this.models.get(p);if(h)return h;let a=await f();return a.lookRenderer.setLinkMode("open-world"),this.models.set(p,a),a}async handle(e,s=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Me()};let n=r[0];if(!n.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let t=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="kanonak.lock"||r[1]===K||r[1]===".well-known"),u=!t&&r.length>=2?r[1]:void 0,p=!t&&r.length>=3&&Fe.test(r[2])?r[2]:void 0,f=await this.modelFor(n,u,p),h=e.endsWith("/")&&r.length>1?"/":"",a="/"+r.slice(1).join("/")+h,l=await ke(f,a,s);return l.headers.Location?{...l,headers:{...l.headers,Location:`/${n}${l.headers.Location}`}}:l}};function Ze(o){switch(o.kind){case"publisher":return`/${o.publisher}/`;case"package":return o.version?`/${o.publisher}/${o.package_}/${I(o.version)}/`:`/${o.publisher}/${o.package_}/`;case"resource":{let e=o.uri;return e.version?`/${e.publisher}/${e.package_}/${I(e.version)}/${e.name}`:`/${e.publisher}/${e.package_}/${e.name}`}}}function er(o){let e=o.split("/").filter(Boolean),s=e[0];if(!s||!s.includes("."))return;let r=e[1];if(!r)return{kind:"publisher",publisher:s};let n=e[2]&&Fe.test(e[2])?Z(e[2])??void 0:void 0,t=n?e[3]:e[2];return t?{kind:"resource",uri:new Se(s,r,t,n)}:n?{kind:"package",publisher:s,package_:r,version:n}:{kind:"package",publisher:s,package_:r}}function Me(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{q as ClosureScopedRepository,fe as RequestRouter,Ce as UNIVERSAL_RENDER_BASE,er as addressForRequestPath,ce as buildRenderDiagnostics,Y as buildRenderStackWarnings,z as chooseServedPublisher,H as deriveImportClosure,Me as landingPage,me as loadResourceModel,ge as loadServerModel,Oe as planWorkspaceVersionIndex,G as readWorkspacePackages,he as renderDiagnosticsHtml,E as renderRefKey,Ze as requestPathFor,X as resolveRenderContract,ke as route};
@@ -3,7 +3,7 @@ import type { ServerModel, RouteResponse } from './types.js';
3
3
  * Map one request to a response, using the same `LookRenderer` calls
4
4
  * `kanonak publish` makes — so a live response is byte-equivalent to the
5
5
  * static page `publish` would write — plus the machine-facing endpoints
6
- * (`/.well-known/kanonak.json`, `/kanonak.lock`, raw `.kan.yml`), which
6
+ * (`/.well-known/kanonak.json`, `/kanonak.lock`, `/kanonak.index`, raw `.kan.yml`), which
7
7
  * `publish` freezes to disk rather than omitting.
8
8
  *
9
9
  * Pure: `pathname` in, response out. No filesystem or network I/O — raw
@@ -54,6 +54,12 @@ export interface ServerModel {
54
54
  * pins no closure (the lock endpoint 404s).
55
55
  */
56
56
  readonly lockSource?: string;
57
+ /**
58
+ * The served publisher's `kanonak.index` source (verbatim YAML), when present
59
+ * in the workspace: every version it has published, each with its sha256 and
60
+ * its yank. Served at `/kanonak.index`; absent → that endpoint 404s.
61
+ */
62
+ readonly indexSource?: string;
57
63
  /**
58
64
  * The served publisher's authored `.well-known/kanonak.json` source (verbatim),
59
65
  * when present in the workspace. This is how a publisher DECLARES its bootstrap
@@ -0,0 +1,26 @@
1
+ import { KanonakParser } from '../parsing/KanonakParser.js';
2
+ import type { Version } from '@kanonak-protocol/types/document/models/types';
3
+ /** One versioned package a workspace holds, with its raw source. */
4
+ export interface WorkspacePackage {
5
+ publisher: string;
6
+ package_: string;
7
+ verStr: string;
8
+ version: Version;
9
+ source: string;
10
+ }
11
+ /**
12
+ * Every versioned package under `workspaceRoot`, highest version first: the
13
+ * set a publisher origin serves from, and its `kanonak.index` records. A file
14
+ * that can't be read or parsed, or that states no version, is not a package
15
+ * the workspace publishes.
16
+ */
17
+ export declare function readWorkspacePackages(workspaceRoot: string, parser?: KanonakParser): WorkspacePackage[];
18
+ /**
19
+ * The one publisher a workspace origin serves: `requested` when given and
20
+ * present, else the workspace's only publisher. Throws for an empty workspace,
21
+ * a requested publisher it doesn't hold, or several publishers and no choice.
22
+ */
23
+ export declare function chooseServedPublisher(packages: readonly WorkspacePackage[], workspaceRoot: string, requested?: string): {
24
+ publisher: string;
25
+ availablePublishers: string[];
26
+ };
@@ -0,0 +1,23 @@
1
+ import { type VersionIndex, type VersionIndexPlan } from '../lock/VersionIndex.js';
2
+ import type { PublisherIndex } from '../repositories/PublisherIndex.js';
3
+ export interface WorkspaceVersionIndex {
4
+ publisher: string;
5
+ /** Where the workspace keeps its index: `{workspaceRoot}/kanonak.index`. */
6
+ path: string;
7
+ /** The index the workspace holds now, or null when it has none. */
8
+ current: VersionIndex | null;
9
+ /** The index the publisher's origin serves, or null when it serves none. */
10
+ served: VersionIndex | null;
11
+ plan: VersionIndexPlan;
12
+ }
13
+ /**
14
+ * Plan the `kanonak.index` of the publisher a workspace serves, chosen as
15
+ * `kanonak serve` chooses it: its versions are the ones the workspace holds,
16
+ * checked against what the publisher's origin already serves, read through
17
+ * `publisherIndex`. `kanonak index` writes the plan, and `kanonak publish`
18
+ * refuses to publish unless the workspace's index already is it.
19
+ */
20
+ export declare function planWorkspaceVersionIndex(workspaceRoot: string, options: {
21
+ publisher?: string;
22
+ publisherIndex: PublisherIndex;
23
+ }): Promise<WorkspaceVersionIndex>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "6.9.0",
3
+ "version": "7.0.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -135,7 +135,7 @@
135
135
  ],
136
136
  "dependencies": {
137
137
  "@kanonak-protocol/canonical": "^0.1.3",
138
- "@kanonak-protocol/types": "^6.9.0",
138
+ "@kanonak-protocol/types": "^7.0.0",
139
139
  "ignore": "^7.0.5",
140
140
  "js-yaml": "^4.1.0",
141
141
  "yaml": "^2.7.0",
@@ -1 +0,0 @@
1
- import{o as i,p as o,q as r}from"./chunk-DAWT3ZAM.js";import{readFileSync as c,writeFileSync as l,existsSync as s}from"fs";import{createHash as a}from"crypto";var n="kanonak.lock";function f(e=n){return s(e)?o(c(e,"utf-8")):null}function k(e,t=n){e.lastUpdated=new Date().toISOString(),l(t,r(e),"utf-8")}function L(e){let t=a("sha256").update(e).digest("hex");return`${i}${t}`}export{f as a,k as b,L as c};
@@ -1,2 +0,0 @@
1
- import{a as m}from"./chunk-SC5M74NM.js";import{b as l,d as A,e as p}from"./chunk-5FVUBF7N.js";import{a as E}from"./chunk-VAZY57HJ.js";import{e as f,g as R,j as C,m as x}from"./chunk-7IMLHHSA.js";var j="@kanonak-protocol/sdk (+https://kanonak.org)",F=j;function ee(o){F=o}function te(){return F}function g(o){let e;try{e=typeof o=="string"?new URL(o):o}catch{throw new Error(`Kanonak requires an absolute https:// URL \u2014 got an unparseable or relative URL: ${String(o)}`)}if(e.protocol!=="https:")throw new Error(`Kanonak requires HTTPS \u2014 refusing to fetch ${e.href} (only https:// is supported).`)}var M=new Set([429,502,503,504]),B=4,q=500,_=2e4;function h(o,e){g(o);let t=new Headers(e?.headers);return t.has("User-Agent")||t.set("User-Agent",F),W(o,{...e,headers:t})}var d=B;function ne(o){d=Math.max(0,o)}async function W(o,e){let t;for(let r=0;r<=d;r++){let n;try{n=await fetch(o,e)}catch(a){if(t=a,r>=d)throw a;await b(T(r,void 0));continue}if(!M.has(n.status)||r>=d)return n;let s=A(n.headers.get("retry-after"));if(s!==void 0&&s*1e3>_)return n;await b(T(r,s))}throw t??new Error("kanonakFetch: exhausted retries")}function T(o,e){if(e!==void 0)return e*1e3;let t=Math.min(_,q*2**o);return Math.floor(t/2+Math.random()*(t/2))}function b(o){return new Promise(e=>setTimeout(e,o))}var k="*",P=["publisher","package","version"];function D(o,e,t){let r=t?` in ${t}`:"";if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`${e}${r} must be an object mapping a publisher, or "${k}", to a package URL template`);let n={};for(let[s,a]of Object.entries(o)){let i=s===k;if(!i&&!V(s))throw new Error(`${e}${r} names "${s}", which is not a publisher (a publisher is a bare domain, e.g. example.org)`);n[s]=N(a,`${e}["${s}"]${r}`,i)}return Object.freeze(n)}function N(o,e,t){if(typeof o!="string"||o.trim()==="")throw new Error(`${e} must be a package URL template string`);if(!o.startsWith("https://"))throw new Error(`${e} must be an absolute https:// URL template (got "${o}")`);let r=(o.match(/\{[^{}]*\}/g)??[]).filter(a=>!P.includes(a.slice(1,-1)));if(r.length>0)throw new Error(`${e} has the unknown placeholder ${r[0]}; a package URL template takes {publisher}, {package} and {version}`);let s=(t?P:P.filter(a=>a!=="publisher")).filter(a=>!o.includes(`{${a}}`)).map(a=>`{${a}}`);if(s.length>0)throw new Error(`${e} must contain ${s.join(", ")}`+(t?", so that one template addresses every publisher's packages":"")+` (got "${o}")`);return o}function U(o,e){if(o)return Object.hasOwn(o,e)?o[e]:Object.hasOwn(o,k)?o[k]:void 0}function u(o,e,t,r){let n={publisher:e,package:t,version:r},s=o;for(let[i,c]of Object.entries(n))s=s.replaceAll(`{${i}}`,c);let a=s.match(/\{[a-z]+\}/);if(a)throw new Error(`Unresolved variable ${a[0]} in URL template: ${o}`);return g(s),s}function V(o){if(o.trim()!==o)return!1;try{let e=x(o);return e.kind==="publisher"&&e.publisher===o}catch{return!1}}var G="https://{publisher}/{package}/{version}.kan.yml",I={version:1};function he(){return{version:1}}var y=class{constructor(e){this.fetchFn=e}fetchFn;cache=new Map;getConfig(e){let t=this.cache.get(e);return t||(t=this.fetchConfig(e),this.cache.set(e,t),t.catch(()=>{this.cache.get(e)===t&&this.cache.delete(e)})),t}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await(this.fetchFn?this.fetchFn(t,e):h(t))}catch(a){if(a instanceof p)throw a;return I}if(r.status===404)return I;if(!r.ok)throw await l("publisher config",t,r);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:n.version};return typeof n.package_url_template=="string"&&(z(t,"package_url_template",n.package_url_template),s.package_url_template=n.package_url_template),Array.isArray(n.featured_packages)&&n.featured_packages.every(a=>typeof a=="string")&&(s.featured_packages=n.featured_packages),s}resolvePackageUrl(e,t,r,n){let s=n.package_url_template??G;return u(s,e,t,r)}};function z(o,e,t){if(!t.startsWith("https://"))throw new Error(`Invalid publisher config at ${o}: ${e} must be an absolute https:// URL template (got "${t}").`)}import K from"js-yaml";function pe(o,e,t){return o.packages[`${e}/${t}`]?.version}var Y=`# This file is generated by Kanonak CLI. Do not edit manually.
2
- `,X="sha256:";function O(o){let e=K.load(o);return!e||typeof e!="object"||e.version!=="1"?null:{version:"1",lastUpdated:e.lastUpdated??"",packages:e.packages??{}}}function me(o){let e={};for(let r of Object.keys(o.packages).sort())e[r]=o.packages[r];let t=K.dump({...o,packages:e},{lineWidth:-1,sortKeys:!1,quotingType:'"'});return Y+t}async function J(o){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)),t=Array.from(new Uint8Array(e),r=>r.toString(16).padStart(2,"0")).join("");return`${X}${t}`}async function S(o,e,t,r){let n=await J(e);if(n!==t)throw new Error(`Integrity mismatch for ${o}: the lock declares ${t||"(no integrity)"} but the bytes from ${r} hash to ${n}.`)}var w=class{configResolver;fetchFn;packageUrlTemplates;lockCache=new Map;packageLockCache=new Map;constructor(e){this.configResolver=e?.configResolver??new y(e?.fetchFn),this.fetchFn=e?.fetchFn,this.packageUrlTemplates=e?.packageUrlTemplates?D(e.packageUrlTemplates,"packageUrlTemplates"):void 0}getConfig(e){return this.configResolver.getConfig(e)}async getPackageUrl(e,t,r){let n=U(this.packageUrlTemplates,e);if(n)return u(n,e,t,r);let s=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,s)}lockedSourceUrl(e,t,r){let n=U(this.packageUrlTemplates,e);return n?u(n,e,t,r.version):r.resolved}async fetchLockedSource(e,t,r){let n=`${e}/${t}@${r.version}`,s=this.lockedSourceUrl(e,t,r);g(s);let a=this.fetchFn?await this.fetchFn(s,e):await h(s);if(!a.ok)throw await l(n,s,a);let i=await a.text();return await S(n,i,r.integrity,s),{url:s,content:i}}getLock(e){let t=this.lockCache.get(e);return t||(t=this.fetchLock(e),this.lockCache.set(e,t),t.catch(()=>{this.lockCache.get(e)===t&&this.lockCache.delete(e)})),t}async getPackageLockEntry(e,t){let r=`${e}/${t}`,n=this.packageLockCache.get(r);return n||(n=this.fetchLock(e,t),this.packageLockCache.set(r,n),n.catch(()=>{this.packageLockCache.get(r)===n&&this.packageLockCache.delete(r)})),(await n)?.packages[r]??null}async fetchLock(e,t){let r=t?`https://${e}/${t}/kanonak.lock`:`https://${e}/kanonak.lock`,n;try{n=this.fetchFn?await this.fetchFn(r,e):await h(r)}catch(s){if(s instanceof p)throw s;return null}if(n.status===404)return null;if(!n.ok)throw await l("publisher lock",r,n);return O(await n.text())}};import{VersionOperator as $}from"@kanonak-protocol/types/document/models/enums";function Q(o,e){let t=R(o);return t?C(t,e):!1}var H=class{parser=new E;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=new w({...e?.fetchFn?{fetchFn:e.fetchFn}:{},...e?.packageUrlTemplates?{packageUrlTemplates:e.packageUrlTemplates}:{}})}async getHighestCompatibleVersionAsync(e,t){if(t.versionOperator===$.Exact){let s=await this.fromMemoOrCache(e,t.packageName,f(t.version));if(s)return s}let n=(await this.publisherIndex.getLock(e))?.packages[`${e}/${t.packageName}`]??await this.publisherIndex.getPackageLockEntry(e,t.packageName)??void 0;return n&&Q(n.version,t)?this.fetchPinned(e,t.packageName,n):n&&t.versionOperator!==$.Exact?null:this.resolveByDirectFetch(e,t)}async fetchPinned(e,t,r){let n=r.version,s=`${e}/${t}@${n}`,a=await this.fromMemoOrCache(e,t,n);if(a)return a;let{content:i}=await this.publisherIndex.fetchLockedSource(e,t,r),c=this.parser.parse(i);return m(c,e,t,n),this.onFetch&&await this.onFetch(e,t,n,i),this.documents.set(s,c),this.contentCache.set(s,i),c}async fromMemoOrCache(e,t,r){let n=`${e}/${t}@${r}`,s=this.documents.get(n);if(s)return s;if(!this.getFromCache)return null;let a=await this.getFromCache(e,t,r);if(a==null)return null;let i;try{i=this.parser.parse(a),m(i,e,t,r)}catch(c){throw new Error(`Cached content for ${n} is not a usable copy of that package \u2014 refusing to fall through to a fetch that would hide it. ${c.message}`,{cause:c})}return this.documents.set(n,i),this.contentCache.set(n,a),i}async resolveByDirectFetch(e,t){let r=t.packageName,s=t.versionOperator===$.Exact?await this.publisherIndex.getPackageUrl(e,r,f(t.version)):`https://${e}/${r}.kan.yml`,a=await this.fetchFollowing(s,e);if(!a)return null;let i=this.parser.parse(a.content),c=i.metadata.namespace_;if(!c||!c.version)throw new Error(`Producer origin returned a package with no namespace/version for ${e}/${r}`);let v=f(c.version);m(i,e,r,v);let L=`${e}/${r}@${v}`;return this.onFetch&&await this.onFetch(e,r,v,a.content),this.documents.set(L,i),this.contentCache.set(L,a.content),i}async fetchFollowing(e,t,r=4){let n=e;for(let s=0;s<r;s++){g(n);let a=this.fetchFn?await this.fetchFn(n,t):await h(n,{redirect:"manual"});if(a.status===301||a.status===302){let i=a.headers.get("location");if(!i)throw new Error(`Redirect with no Location header from ${n}`);n=new URL(i,n).toString();continue}if(a.status===404)return null;if(!a.ok)throw await l("Kanonak package",n,a);return{url:n,content:await a.text()}}throw new Error(`Too many redirects resolving ${e}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(r=>{let n=r.metadata.namespace_;return n&&n.publisher===e&&n.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,r,n,s]=t;return this.publisherIndex.getPackageUrl(r,n,s)}};export{j as a,ee as b,te as c,g as d,h as e,ne as f,k as g,D as h,N as i,U as j,u as k,he as l,y as m,pe as n,X as o,O as p,me as q,J as r,S as s,w as t,H as u};
@@ -1 +0,0 @@
1
- import{n as R,u as A}from"./chunk-DAWT3ZAM.js";import{a as P}from"./chunk-YEUSFSC7.js";import{a as f}from"./chunk-VAZY57HJ.js";import{c as C,g as K,j as I}from"./chunk-7IMLHHSA.js";import{a as F}from"./chunk-PC3DHZGV.js";import*as m from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";var h=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;return I(r,t)});return s.length===0?null:(s.sort((a,r)=>{let l=a.metadata.namespace_.version,u=r.metadata.namespace_.version;return C(u,l)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let l=o.split("/"),u=l[0],y=l[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,u,y)}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 m.mkdir(s,{recursive:!0});let a=this.parser.save(e);await m.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 m.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 m.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await m.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=b(n).toString(),s;for(let[l,u]of this.documentCache.entries())if(this.filePathsByIdentifier.get(l)===n&&u.metadata.namespace_){s=u.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 m.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await m.access(n),t=n}catch{return null}}try{return await m.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await m.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await m.access(n),t=n}catch{return null}}return b(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 m.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await m.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 l=s.metadata.namespace_.toString();this.documentCache.set(l,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(l,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 m.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 g from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),D=class{cache;workspace;constructor(e,t,n){let o=n??new f;g.existsSync(e)||g.mkdirSync(e,{recursive:!0}),g.existsSync(t)||g.mkdirSync(t,{recursive:!0}),this.cache=new h(e,!0,o),this.workspace=new h(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 U}from"os";import{join as V}from"path";function d(){let i=process.env.KANONAK_PACKAGE_CACHE;return i||V(U(),".kanonak","packages")}var w=class i{static createComposite(e,t,n){let o=e??d(),s=t??".";return new D(o,s,n)}static createFromEnvironment(e){let t=d(),n=process.env.KANONAK_WORKSPACE_PATH??".";return i.createComposite(t,n,e)}};var k=class{repos;constructor(...e){this.repos=e}async firstAnswer(e,t,n){let o=[];for(let s of this.repos)try{let a=await e(s);if(t(a))return a}catch(a){o.push(a)}return x(o),n}async getHighestCompatibleVersionAsync(e,t){return this.firstAnswer(n=>n.getHighestCompatibleVersionAsync(e,t),n=>n!==null,null)}async getAllDocumentsAsync(){let e=[],t=new Set,n=[];for(let o of this.repos)try{for(let s of await o.getAllDocumentsAsync()){let a=s.metadata?.namespace_,r=a?a.version?`${a.publisher}/${a.package_}@${a.version.major}.${a.version.minor}.${a.version.patch}`:`${a.publisher}/${a.package_}`:void 0;if(r!==void 0){if(t.has(r))continue;t.add(r)}e.push(s)}}catch(s){n.push(s)}return x(n),e}async getDocumentAsync(e){return this.firstAnswer(t=>t.getDocumentAsync(e),t=>t!==null,null)}async getDocumentsByNamespaceAsync(e,t){return this.firstAnswer(n=>n.getDocumentsByNamespaceAsync(e,t),n=>n.length>0,[])}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){return this.firstAnswer(t=>t.getDocumentContentAsync(e),t=>!!t,null)}async getDocumentUriAsync(e){return this.firstAnswer(t=>t.getDocumentUriAsync(e),t=>!!t,null)}};function x(i){if(i.length===1)throw i[0];if(i.length>1)throw new Error(i.map(e=>e instanceof Error?e.message:String(e)).join("; "))}import{VersionOperator as j}from"@kanonak-protocol/types/document/models/enums";var v=class{constructor(e,t){this.base=e;this.lock=t}base;lock;pinnedVersion(e,t){return R(this.lock,e,t)}async getHighestCompatibleVersionAsync(e,t){let n=this.pinnedVersion(e,t.packageName);if(n){let o=K(n);if(o){let s={...t,versionOperator:j.Exact,version:o};return this.base.getHighestCompatibleVersionAsync(e,s)}}return this.base.getHighestCompatibleVersionAsync(e,t)}async getDocumentsByNamespaceAsync(e,t){let n=await this.base.getDocumentsByNamespaceAsync(e,t),o=this.pinnedVersion(e,t);return o?n.filter(s=>{let a=s.metadata.namespace_?.version;return a?`${a.major}.${a.minor}.${a.patch}`===o:!1}):n}getAllDocumentsAsync(){return this.base.getAllDocumentsAsync()}getDocumentAsync(e){return this.base.getDocumentAsync(e)}saveDocumentAsync(e,t){return this.base.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.base.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.base.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.base.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.base.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.base.getDocumentUriAsync(e)}};import{readFileSync as E,readdirSync as _}from"fs";import{join as H}from"path";var T=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function N(i,e=[],t={}){let n=t.ignore??new F(i),o=s=>{for(let a of _(s,{withFileTypes:!0})){let r=H(s,a.name);if(a.isDirectory()){if(T.has(a.name))continue;if(!n.shouldIgnoreDirectory(r))o(r);else if(t.ignored){let l=B(r);l>0&&t.ignored.push({path:r,isDirectory:!0,kanonakFiles:l})}}else a.name.endsWith(".kan.yml")&&(n.shouldIgnore(r)?t.ignored?.push({path:r,isDirectory:!1,kanonakFiles:1}):e.push(r))}};return o(i),e}function B(i){let e=0;for(let t of _(i,{withFileTypes:!0}))t.isDirectory()?T.has(t.name)||(e+=B(H(i,t.name))):t.name.endsWith(".kan.yml")&&e++;return e}async function W(i,e=new f,t={}){let n=new P(e);for(let l of N(i))try{let u=E(l,"utf-8"),p=e.parse(u),y=p.metadata?.namespace_;y?.version&&await n.saveDocumentAsync(p,y.toString(),u)}catch{}let o=new h(d(),!0,e);if(t.offline)return new k(n,o);let s=new Map,a=t.httpCache??{getFromCache:(l,u,p)=>s.get(`${l}|${u}|${p}`)??null,onFetch:(l,u,p,y)=>{s.set(`${l}|${u}|${p}`,y)}},r=new A({getFromCache:a.getFromCache,onFetch:a.onFetch,...t.fetchFn?{fetchFn:t.fetchFn}:{},...t.packageUrlTemplates?{packageUrlTemplates:t.packageUrlTemplates}:{}});return new k(n,o,r)}export{h as a,S as b,D as c,d,w as e,k as f,v as g,N as h,W as i};