@kanonak-protocol/sdk 5.1.0 → 5.3.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.
@@ -1,3 +1,4 @@
1
+ import { type OAuthServerMetadata } from './OAuthDiscovery.js';
1
2
  import type { SessionRecord } from './SessionStore.js';
2
3
  /**
3
4
  * The durable host→credential primitive (issue #72): given any registry/repo
@@ -10,8 +11,16 @@ import type { SessionRecord } from './SessionStore.js';
10
11
  * host --RFC 9728 protected-resource metadata--> authorization server(s)
11
12
  * authority --device session (refreshed from the cert)--> a fresh token
12
13
  * The session is keyed by the AUTHORITY and reused across every resource host
13
- * that points at it. Returns null when the host advertises no authority (not a
14
- * Kanonak resource) or its authority isn't enrolled on this device.
14
+ * that points at it. When the advertised authority itself isn't enrolled, an
15
+ * enrollment in the same trust plane still serves it (issue #75): per-account
16
+ * authority hosts (`oauth--{account}.{tenant}`) are consent surfaces over one
17
+ * tenant-level trust plane, and that identity is proven by the servers' own
18
+ * RFC 8414 documents — an advertised authority whose `session_endpoint` equals
19
+ * an enrolled authority's `session_endpoint` mints at the same place with the
20
+ * same CA-signed cert, so the enrollment applies. No host-string heuristics:
21
+ * a different tenant advertises a different `session_endpoint`, so enrolling
22
+ * per tenant remains the trust boundary. Returns null when the host advertises
23
+ * no authority (not a Kanonak resource) or no enrollment serves its authority.
15
24
  */
16
25
  /** A resolved registry credential. `token` is the credential (presented as a
17
26
  * Bearer token, or as the HTTP Basic password); there is no identity here. */
@@ -28,15 +37,23 @@ export interface ResolvedCredential {
28
37
  export interface CredentialResolverDeps {
29
38
  discovery?: {
30
39
  discoverProtectedResource(host: string): Promise<string[] | null>;
40
+ /** RFC 8414 metadata — the `session_endpoint` proves trust-plane identity (#75). */
41
+ discover(host: string): Promise<OAuthServerMetadata | null>;
31
42
  };
32
43
  sessionManager?: {
33
44
  getValidSession(host: string): Promise<SessionRecord | null>;
34
45
  };
46
+ /** The enrolled-authority hosts on this device — the trust-plane candidates (#75). */
47
+ deviceStore?: {
48
+ list(): Promise<string[]>;
49
+ };
35
50
  }
36
51
  export declare class CredentialResolver {
37
52
  private readonly discovery;
38
53
  private readonly sessions;
54
+ private readonly devices;
39
55
  constructor(deps?: CredentialResolverDeps);
40
56
  /** Resolve a fresh credential for `host`, or null to decline. */
41
57
  resolve(host: string): Promise<ResolvedCredential | null>;
58
+ private sessionFor;
42
59
  }
package/dist/browser.js CHANGED
@@ -1 +1 @@
1
- import{a as U,b as B,c as A,d as ke,e as xe,f as Pe,g as Ke}from"./chunk-EBH5WSSY.js";import{a as ge}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c as d,d as c,f as y,g as R,h as f}from"./chunk-JYBKSBB5.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as G,b as H,c as L}from"./chunk-S6VSAKXB.js";import{a as w,b as q}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as ye,B as Re,K as fe,a as W,b as _,c as z,d as F,f as J,g as Q,h as X,i as Y,k as Z,l as $,m as ee,n as oe,o as te,p as re,q as ne,r as ae,s as ie,t as se,u as pe,v as le,w as me,x as ue,y as de,z as ce}from"./chunk-FPUQEPYK.js";import{a as g,c as E,l as N}from"./chunk-MX3DEXMV.js";import{a as l}from"./chunk-NJ3AZYQD.js";import{a as M}from"./chunk-ZP6P7HNU.js";import"./chunk-6U26UASC.js";import{a as v,b as T}from"./chunk-GZPLWII7.js";import{a as k,b as x,c as P,d as S,e as b,f as D,g as h,h as C,i as V,j,k as I,l as O}from"./chunk-7BHDZHJY.js";import{a as K}from"./chunk-FUUTGGJS.js";import{c as e,d as o,e as t,f as r,g as n,h as a,i,j as s}from"./chunk-2ACBWC7K.js";export{pe as AmbiguousReferenceRule,V as BooleanStatement,ye as ClassDefinitionRule,oe as ClassHierarchyCycleRule,x as DefinedKanonak,B as EdgeType,g as EmbeddedKanonak,Z as EmbeddedKanonakTypeRule,I as EmbeddedStatement,A as GraphBuilder,f as HttpKanonakDocumentRepository,$ as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,k as Kanonak,H as KanonakDocumentPositions,N as KanonakObjectParser,fe as KanonakObjectValidator,l as KanonakParser,K as KanonakUri,w as KanonakUriBuilder,O as ListStatement,Re as MarkdownLinkRule,E as MarkdownStatement,ie as NamespaceImportCycleRule,J as NamespacePrefixRule,U as NodeType,C as NumberStatement,me as ObjectPropertyValueValidationRule,z as OntologyValidationError,W as OntologyValidationResult,ue as PropertyDomainRule,te as PropertyHierarchyCycleRule,de as PropertyKindRangeConsistencyRule,G as PropertyMetadata,le as PropertyRangeReferenceRule,re as PropertyRangeRequiredRule,X as PropertyTypeSpecificityRule,y as PublisherConfigResolver,R as PublisherIndex,S as ReferenceKanonak,j as ReferenceStatement,ce as ReservedNameShadowRule,Q as ResourceNamingRule,v as ResourceResolver,M as ResourceTypeClassifier,D as ScalarStatement,b as Statement,h as StringStatement,ne as SubClassOfReferenceRule,ae as SubPropertyOfReferenceRule,P as SubjectKanonak,Y as SubjectKanonakTypeRequiredRule,T as TypeResolver,se as UnresolvedPredicateRule,ee as UnresolvedReferenceRule,F as ValidationContext,_ as ValidationSeverity,Ke as buildOntologyModel,e as compareVersions,r as createVersion,ge as findDerivation,q as findInstancesByType,t as formatVersion,d as getKanonakUserAgent,xe as hasValidToken,a as isCompatibleVersion,ke as isExpired,i as isMajorCompatible,c as kanonakFetch,Pe as normalizeHost,n as parseVersionString,L as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
1
+ import{a as U,b as B,c as A,d as ke,e as xe,f as Pe,g as Ke}from"./chunk-S5URV3V7.js";import{a as ge}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as m,b as u,c as d,d as c,f as y,g as R,h as f}from"./chunk-JYBKSBB5.js";import{a as p}from"./chunk-4NO7MHS7.js";import{a as G,b as H,c as L}from"./chunk-S6VSAKXB.js";import{a as w,b as q}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as ye,B as Re,K as fe,a as W,b as _,c as z,d as F,f as J,g as Q,h as X,i as Y,k as Z,l as $,m as ee,n as oe,o as te,p as re,q as ne,r as ae,s as ie,t as se,u as pe,v as le,w as me,x as ue,y as de,z as ce}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as g,c as E,l as N}from"./chunk-MX3DEXMV.js";import{a as l}from"./chunk-NJ3AZYQD.js";import{a as M}from"./chunk-ZP6P7HNU.js";import"./chunk-6U26UASC.js";import{a as v,b as T}from"./chunk-GZPLWII7.js";import{a as k,b as x,c as P,d as S,e as b,f as D,g as h,h as C,i as V,j,k as I,l as O}from"./chunk-7BHDZHJY.js";import{a as K}from"./chunk-FUUTGGJS.js";import{c as e,d as o,e as t,f as r,g as n,h as a,i,j as s}from"./chunk-2ACBWC7K.js";export{pe as AmbiguousReferenceRule,V as BooleanStatement,ye as ClassDefinitionRule,oe as ClassHierarchyCycleRule,x as DefinedKanonak,B as EdgeType,g as EmbeddedKanonak,Z as EmbeddedKanonakTypeRule,I as EmbeddedStatement,A as GraphBuilder,f as HttpKanonakDocumentRepository,$ as ImportExistenceRule,p as InMemoryKanonakDocumentRepository,m as KANONAK_USER_AGENT,k as Kanonak,H as KanonakDocumentPositions,N as KanonakObjectParser,fe as KanonakObjectValidator,l as KanonakParser,K as KanonakUri,w as KanonakUriBuilder,O as ListStatement,Re as MarkdownLinkRule,E as MarkdownStatement,ie as NamespaceImportCycleRule,J as NamespacePrefixRule,U as NodeType,C as NumberStatement,me as ObjectPropertyValueValidationRule,z as OntologyValidationError,W as OntologyValidationResult,ue as PropertyDomainRule,te as PropertyHierarchyCycleRule,de as PropertyKindRangeConsistencyRule,G as PropertyMetadata,le as PropertyRangeReferenceRule,re as PropertyRangeRequiredRule,X as PropertyTypeSpecificityRule,y as PublisherConfigResolver,R as PublisherIndex,S as ReferenceKanonak,j as ReferenceStatement,ce as ReservedNameShadowRule,Q as ResourceNamingRule,v as ResourceResolver,M as ResourceTypeClassifier,D as ScalarStatement,b as Statement,h as StringStatement,ne as SubClassOfReferenceRule,ae as SubPropertyOfReferenceRule,P as SubjectKanonak,Y as SubjectKanonakTypeRequiredRule,T as TypeResolver,se as UnresolvedPredicateRule,ee as UnresolvedReferenceRule,F as ValidationContext,_ as ValidationSeverity,Ke as buildOntologyModel,e as compareVersions,r as createVersion,ge as findDerivation,q as findInstancesByType,t as formatVersion,d as getKanonakUserAgent,xe as hasValidToken,a as isCompatibleVersion,ke as isExpired,i as isMajorCompatible,c as kanonakFetch,Pe as normalizeHost,n as parseVersionString,L as parseWithPositions,s as pickHighestDocument,u as setKanonakUserAgent,o as versionsEqual};
@@ -1,11 +1,11 @@
1
- import{a as v,b as Me,c as it,g as M,j as ct,l as S}from"./chunk-MX3DEXMV.js";import{a as rt}from"./chunk-NJ3AZYQD.js";import{a as y,d as A,e as Y,f as pt,g as L,h as lt}from"./chunk-ZP6P7HNU.js";import{a as G}from"./chunk-6U26UASC.js";import{h as Fe,i as st}from"./chunk-GZPLWII7.js";import{c as d,d as I,j as Be,k as H,l as F,m as K,n as z,p as P,r as h,t as J,u as x,v as W,w as g,x as O,y as V}from"./chunk-7BHDZHJY.js";import{a as at}from"./chunk-FUUTGGJS.js";import{e as U}from"./chunk-2ACBWC7K.js";var Q=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var k=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(k||{});var u=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var ze=class c{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new c;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ee=class{constructor(e){this.underlying=e;this.repository=new Xe(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e={};return{merged:await new S().parseKanonaks(this.underlying,e),authored:e.authored??[]}})()),this.parsePromise}},Xe=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};async function D(c,e,t){return t?t.getKanonaks():new S().parseKanonaks(new te(c,e))}async function C(c,e,t){let o=await D(c,e,t),n=We(c);return n?o.filter(r=>r instanceof d&&r.namespace===n):[]}async function oe(c,e,t){let o=We(c);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new S().parseKanonaks(new te(c,e),r),n=r.authored??[]}return n.filter(r=>r instanceof d&&r.sourceDoc===o)}function q(c,e){for(let t of c)t instanceof d&&Ze(t,t.name,e)}function Ze(c,e,t){t({kanonak:c,path:e});for(let o of c.statement)if(o instanceof H)Ze(o.object,mt(e,o.object),t);else if(o instanceof F)for(let n of o.object)n instanceof v&&Ze(n,mt(e,n),t)}function mt(c,e){let t=e instanceof v&&e.name?e.name:"<embedded>";return`${c}/${t}`}function We(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var te=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var ne=class c{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&c.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),s=e.split(".")[0],p=new u;p.ruleType=this.ruleName,p.severity="Error",p.entityName=s,p.propertyName=e,p.actualValue=n,p.expectedValue=i,p.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(p)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var re=class c{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=c.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&c.RESERVED_WORDS.has(n.toLowerCase())){let i=new u;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!c.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new u;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Invalid entity name '${n}'. ${i}`,s.suggestion=i,t.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!c.VALID_PROPERTIES.has(n)&&!c.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new u;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var ae=class c{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let s=[];if(Array.isArray(i))for(let p of i){let l=p?.toString();l&&l==="Property"&&!o&&s.push(l)}else{let p=i?.toString();p&&p==="Property"&&!o&&s.push(p)}for(let p of s){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),f=new u;f.ruleType=this.ruleName,f.severity="Error",f.entityName=n,f.propertyName="type",f.actualValue=p,f.expectedValue=m,f.message=`Invalid property type '${p}'. Use '${m}' instead.`,f.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(f)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":c.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ie=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let s=new u;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.propertyName="type",s.message=`Subject Kanonak '${o}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
1
+ import{a as mt}from"./chunk-ITKOKDBG.js";import{a as v,b as Me,c as it,g as M,j as ct,l as S}from"./chunk-MX3DEXMV.js";import{a as rt}from"./chunk-NJ3AZYQD.js";import{a as y,d as A,e as Y,f as pt,g as L,h as lt}from"./chunk-ZP6P7HNU.js";import{a as G}from"./chunk-6U26UASC.js";import{h as Fe,i as st}from"./chunk-GZPLWII7.js";import{c as d,d as I,j as Be,k as H,l as F,m as K,n as z,p as P,r as h,t as J,u as x,v as W,w as g,x as O,y as V}from"./chunk-7BHDZHJY.js";import{a as at}from"./chunk-FUUTGGJS.js";import{e as U}from"./chunk-2ACBWC7K.js";var Q=class{isValid=!1;errors=[];warnings=[];infos=[];get totalIssues(){return this.errors.length+this.warnings.length+this.infos.length}get allDiagnostics(){return[...this.errors,...this.warnings,...this.infos]}};var k=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(k||{});var u=class{ruleType="";severity="Error";lineNumber;column;entityName;propertyName;propertyPath;message="";suggestion;actualValue;expectedValue;toString(){let e="";return this.lineNumber!==void 0&&(e+=`Line ${this.lineNumber}: `),this.entityName&&(e+=`[${this.entityName}] `),e+=this.message,e}};var ze=class c{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new c;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var ee=class{constructor(e){this.underlying=e;this.repository=new Xe(e)}underlying;repository;parsePromise=null;getKanonaks(){return this.parseOnce().then(e=>e.merged)}getAuthoredKanonaks(){return this.parseOnce().then(e=>e.authored)}parseOnce(){return this.parsePromise||(this.parsePromise=(async()=>{let e=await this.underlying.getAllDocumentsAsync();await mt(e,this.repository);let t={};return{merged:await new S().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},Xe=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let o=`${e}/${t}`,n=this.byNamespaceCache.get(o);return n||(n=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(o,n),n)}getHighestCompatibleVersionAsync(e,t){let o=t.version,n=o?`${o.major}.${o.minor}.${o.patch}`:"",r=`${e}/${t.packageName}@${t.versionOperator}:${n}`,a=this.highestVersionCache.get(r);return a||(a=this.inner.getHighestCompatibleVersionAsync(e,t),this.highestVersionCache.set(r,a),a)}saveDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}deleteDocumentAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}clearNamespaceAsync(){throw new Error("CachingRepository is read-only during a validation pass.")}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};async function D(c,e,t){return t?t.getKanonaks():new S().parseKanonaks(new te(c,e))}async function C(c,e,t){let o=await D(c,e,t),n=We(c);return n?o.filter(r=>r instanceof d&&r.namespace===n):[]}async function oe(c,e,t){let o=We(c);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new S().parseKanonaks(new te(c,e),r),n=r.authored??[]}return n.filter(r=>r instanceof d&&r.sourceDoc===o)}function q(c,e){for(let t of c)t instanceof d&&Ze(t,t.name,e)}function Ze(c,e,t){t({kanonak:c,path:e});for(let o of c.statement)if(o instanceof H)Ze(o.object,ut(e,o.object),t);else if(o instanceof F)for(let n of o.object)n instanceof v&&Ze(n,ut(e,n),t)}function ut(c,e){let t=e instanceof v&&e.name?e.name:"<embedded>";return`${c}/${t}`}function We(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var te=class{constructor(e,t){this.document=e;this.broader=t}document;broader;async getAllDocumentsAsync(){let e=this.document.metadata.namespace_?.toString(),t=(await this.broader.getAllDocumentsAsync()).filter(o=>o.metadata.namespace_?.toString()!==e);return[this.document,...t]}getDocumentAsync(e){return this.broader.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}getAllDocumentReferencesAsync(){return this.broader.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}saveDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}deleteDocumentAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}clearNamespaceAsync(){throw new Error("DocumentWithRepositoryCatalog is read-only")}};var ne=class c{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[o,n]of Object.entries(e.body))n&&typeof n=="object"&&!Array.isArray(n)&&this.validateEntity(o,n,t);return t}validateEntity(e,t,o){for(let[n,r]of Object.entries(t)){let a=r?.toString()??"";if(a&&c.NAMESPACE_PREFIX_PATTERN.test(a)){let i=this.getSuggestionForPrefixedValue(a),s=e.split(".")[0],p=new u;p.ruleType=this.ruleName,p.severity="Error",p.entityName=s,p.propertyName=e,p.actualValue=n,p.expectedValue=i,p.message=`Invalid namespace prefix '${a}'. Use '${i}' without prefix.`,p.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",o.push(p)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validateEntity(`${e}.${n}`,r,o)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let o=e.indexOf(":");return o>=0?e.substring(o+1):e}};var re=class c{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],o=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[n,r]of Object.entries(e.body)){let a=c.VALID_AUGMENTATION_PATTERN.test(n);if(!a&&!o&&c.RESERVED_WORDS.has(n.toLowerCase())){let i=new u;i.ruleType=this.ruleName,i.severity="Error",i.entityName=n,i.message=`Entity name '${n}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",t.push(i);continue}if(!a&&!c.VALID_NAME_PATTERN.test(n)){let i;/^\d/.test(n)?i="Entity names must start with a letter, not a number.":n.includes(" ")?i="Entity names cannot contain spaces. Use camelCase or underscores instead.":i="Entity names must start with a letter and contain only letters, numbers, and underscores.";let s=new u;s.ruleType=this.ruleName,s.severity="Error",s.entityName=n,s.message=`Invalid entity name '${n}'. ${i}`,s.suggestion=i,t.push(s)}r&&typeof r=="object"&&!Array.isArray(r)&&this.validatePropertyNames(n,r,t)}return t}validatePropertyNames(e,t,o){for(let n of Object.keys(t))if(!c.VALID_PROPERTIES.has(n)&&!c.VALID_PROPERTY_NAME_PATTERN.test(n)){let r=new u;r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=n,r.message=`Property name '${n}' in entity '${e}' doesn't follow naming conventions.`,r.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",o.push(r)}}};var ae=class c{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let o=this.isPropertyDefinedAsClass(e);for(let[n,r]of Object.entries(e.body))if(r&&typeof r=="object"&&!Array.isArray(r)){let a=r,i=a.type;if(i){let s=[];if(Array.isArray(i))for(let p of i){let l=p?.toString();l&&l==="Property"&&!o&&s.push(l)}else{let p=i?.toString();p&&p==="Property"&&!o&&s.push(p)}for(let p of s){let l=this.getPropertyValue(a,"range"),m=this.determinePropertyType(l),f=new u;f.ruleType=this.ruleName,f.severity="Error",f.entityName=n,f.propertyName="type",f.actualValue=p,f.expectedValue=m,f.message=`Invalid property type '${p}'. Use '${m}' instead.`,f.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(f)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":c.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let o=e[t];return o?o.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t.type;if(n){let r=n.toString();return r==="Class"||r.endsWith(".Class")}}return!1}};var ie=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let t=[];for(let[o,n]of Object.entries(e.body)){if(typeof n!="object"||n===null||Array.isArray(n)||o.includes("."))continue;let r=n,a="type"in r,i=r.type?.toString().trim();if(!a||!i){let s=new u;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.propertyName="type",s.message=`Subject Kanonak '${o}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
2
2
  type: Scene
3
3
 
4
- Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,s.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(s)}}return t}};var Ut=new Set(["EphemeralPackage"]),se=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let o=[],n=this.packageKey(e,t.type_);return t.namespace_?(!Ut.has(t.type_)&&!t.namespace_.version&&o.push(this.error(n,"version",`Package resource '${n}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
4
+ Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,s.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(s)}}return t}};var At=new Set(["EphemeralPackage"]),se=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let o=[],n=this.packageKey(e,t.type_);return t.namespace_?(!At.has(t.type_)&&!t.namespace_.version&&o.push(this.error(n,"version",`Package resource '${n}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
5
5
  version: 1.0.0`)),o):(o.push(this.error(n,"publisher",`Package resource '${n}' requires a 'publisher' property.`,`Add a publisher, e.g.:
6
- publisher: example.org`)),o)}packageKey(e,t){for(let[o,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type===t)return o;return t}error(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.message=o,r.suggestion=n,r}};var At={publisher:"kanonak.org",package_:"core-rdf",name:"type"},wt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},xt={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Tt={publisher:"kanonak.org",package_:"core-rdf",name:"Class"},ce=class{ruleName="EmbeddedKanonakType";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof H){let a=r.predicate?.subject,i=`${o}.${a?.name??"<embedded>"}`;this.check(e,a,r.object,o,i,n),this.walk(e,r.object,i,n)}else if(r instanceof F){let a=r.predicate?.subject,i=0;for(let s of r.object){if(s instanceof v){let p=`${o}.${a?.name??"<embedded>"}[${i}]`;this.check(e,a,s,o,p,n),this.walk(e,s,p,n)}i++}}}check(e,t,o,n,r,a){if(!t)return;let i=g(o,At);if(!i)return;let s=h(e,t);if(!s)return;let p=g(s,wt);if(p&&!(z(p,xt)||z(p,Tt))){if(K(i)===K(p)){a.push(this.redundant(n,r,i,p));return}Y(e,i).some(l=>K(l)===K(p))||a.push(this.notSubclass(n,r,i,p))}}redundant(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' declares 'type: ${o.name}', which equals the parent property's range '${n.name}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,r.suggestion=`Remove the 'type: ${o.name}' line, or keep it if explicitness is preferred over concision.`,r}notSubclass(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' has 'type: ${o.name}', which is not a subclass of the parent property's range '${n.name}'.`,r.suggestion=`Either remove the 'type: ${o.name}' line (so the type is inferred from the property's range '${n.name}'), or add 'subClassOf: ${n.name}' to the '${o.name}' class definition so the relationship holds.`,r}};import{VersionOperator as He}from"@kanonak-protocol/types/document/models/enums";var pe=class{ruleName="ImportExistence";async validateAsync(e,t){let o=[];if(!e.metadata?.imports)return o;let n=await t.getAllDocumentsAsync();for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a)if(!await t.getHighestCompatibleVersionAsync(r,i)){let p=await this.determineImportErrorAsync(t,r,i,n),l=new u;l.ruleType=this.ruleName,l.severity="Error",l.message=p.message,l.suggestion=p.suggestion,l.entityName=`Import: ${r}/${i.packageName}`,l.actualValue=i.toString(),l.expectedValue=p.expectedValue,o.push(l)}return o}async determineImportErrorAsync(e,t,o,n){let r=await e.getDocumentsByNamespaceAsync(t,o.packageName);if(r.length===0){let p=n.filter(R=>R.metadata.namespace_?.publisher===t).map(R=>R.metadata.namespace_.package_).filter((R,E,N)=>N.indexOf(R)===E),l=this.findSimilarPackages(o.packageName,p),m=`Import '${t}/${o.package_}' not found - package does not exist`,f=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:p.length>0?`Available packages in ${t}: ${p.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:m,suggestion:f,expectedValue:"Existing package"}}let i=r.filter(p=>p.metadata.namespace_?.version).map(p=>p.metadata.namespace_.version.toString()).sort().join(", "),s=this.getAcceptableVersionRange(o);return{message:`Import '${t}/${o.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${i}. Required: ${s}`,expectedValue:s}}getAcceptableVersionRange(e){switch(e.versionOperator){case He.Exact:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case He.Compatible:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case He.Major:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case He.Any:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let o=t.filter(a=>a.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(a.toLowerCase()));if(o.length>0)return o.sort((a,i)=>a.length-i.length);let n=t.map(a=>({package:a,distance:this.levenshteinDistance(e.toLowerCase(),a.toLowerCase())})).sort((a,i)=>a.distance-i.distance),r=Math.max(3,Math.floor(e.length*.4));return n.filter(a=>a.distance<=r).map(a=>a.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let o=e.length,n=t.length,r=Array(o+1).fill(null).map(()=>Array(n+1).fill(0));for(let a=0;a<=o;a++)r[a][0]=a;for(let a=0;a<=n;a++)r[0][a]=a;for(let a=1;a<=o;a++)for(let i=1;i<=n;i++){let s=e[a-1]===t[i-1]?0:1;r[a][i]=Math.min(Math.min(r[a-1][i]+1,r[a][i-1]+1),r[a-1][i-1]+s)}return r[o][n]}};var Nt="kanonak.org",_t="core-rdf",Lt=new Set(["type","subClassOf","subPropertyOf","domain","range"].map(c=>K({publisher:Nt,package_:_t,name:c}))),le=class{ruleName="UnresolvedReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of i.statement){let l=Mt(p);if(!(!l||Lt.has(K(l)))){if(p instanceof Be)this.check(r,s,l,p.object,n);else if(p instanceof F)for(let m of p.object)m instanceof I&&this.check(r,s,l,m,n)}}}),n}check(e,t,o,n,r){h(e,n.subject)||r.push(this.unresolvedError(t,o.name,n.subject))}unresolvedError(e,t,o){let n=`${o.publisher}/${o.package_}/${o.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=n,r.expectedValue="A reference that resolves to a defined or imported resource",r.message=`Reference to '${o.name}' in '${t}' could not be resolved`,r.suggestion=`The entity '${n}' is not defined in this namespace or any imported namespace.
6
+ publisher: example.org`)),o)}packageKey(e,t){for(let[o,n]of Object.entries(e.body))if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type===t)return o;return t}error(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.message=o,r.suggestion=n,r}};var wt={publisher:"kanonak.org",package_:"core-rdf",name:"type"},xt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Tt={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Nt={publisher:"kanonak.org",package_:"core-rdf",name:"Class"},ce=class{ruleName="EmbeddedKanonakType";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof H){let a=r.predicate?.subject,i=`${o}.${a?.name??"<embedded>"}`;this.check(e,a,r.object,o,i,n),this.walk(e,r.object,i,n)}else if(r instanceof F){let a=r.predicate?.subject,i=0;for(let s of r.object){if(s instanceof v){let p=`${o}.${a?.name??"<embedded>"}[${i}]`;this.check(e,a,s,o,p,n),this.walk(e,s,p,n)}i++}}}check(e,t,o,n,r,a){if(!t)return;let i=g(o,wt);if(!i)return;let s=h(e,t);if(!s)return;let p=g(s,xt);if(p&&!(z(p,Tt)||z(p,Nt))){if(K(i)===K(p)){a.push(this.redundant(n,r,i,p));return}Y(e,i).some(l=>K(l)===K(p))||a.push(this.notSubclass(n,r,i,p))}}redundant(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' declares 'type: ${o.name}', which equals the parent property's range '${n.name}'. The declaration is redundant \u2014 the type is already inferred from the property's range.`,r.suggestion=`Remove the 'type: ${o.name}' line, or keep it if explicitness is preferred over concision.`,r}notSubclass(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=o.name,r.expectedValue=n.name,r.message=`Embedded object at '${t}' has 'type: ${o.name}', which is not a subclass of the parent property's range '${n.name}'.`,r.suggestion=`Either remove the 'type: ${o.name}' line (so the type is inferred from the property's range '${n.name}'), or add 'subClassOf: ${n.name}' to the '${o.name}' class definition so the relationship holds.`,r}};import{VersionOperator as He}from"@kanonak-protocol/types/document/models/enums";var pe=class{ruleName="ImportExistence";async validateAsync(e,t){let o=[];if(!e.metadata?.imports)return o;let n=await t.getAllDocumentsAsync();for(let[r,a]of Object.entries(e.metadata.imports))for(let i of a)if(!await t.getHighestCompatibleVersionAsync(r,i)){let p=await this.determineImportErrorAsync(t,r,i,n),l=new u;l.ruleType=this.ruleName,l.severity="Error",l.message=p.message,l.suggestion=p.suggestion,l.entityName=`Import: ${r}/${i.packageName}`,l.actualValue=i.toString(),l.expectedValue=p.expectedValue,o.push(l)}return o}async determineImportErrorAsync(e,t,o,n){let r=await e.getDocumentsByNamespaceAsync(t,o.packageName);if(r.length===0){let p=n.filter(R=>R.metadata.namespace_?.publisher===t).map(R=>R.metadata.namespace_.package_).filter((R,E,N)=>N.indexOf(R)===E),l=this.findSimilarPackages(o.packageName,p),m=`Import '${t}/${o.package_}' not found - package does not exist`,f=l.length>0?`Did you mean: ${l.slice(0,3).join(", ")}?`:p.length>0?`Available packages in ${t}: ${p.slice(0,5).join(", ")}`:`No packages found for publisher '${t}'. Verify the publisher name is correct.`;return{message:m,suggestion:f,expectedValue:"Existing package"}}let i=r.filter(p=>p.metadata.namespace_?.version).map(p=>p.metadata.namespace_.version.toString()).sort().join(", "),s=this.getAcceptableVersionRange(o);return{message:`Import '${t}/${o.toString()}' version mismatch - no compatible version found`,suggestion:`Available versions: ${i}. Required: ${s}`,expectedValue:s}}getAcceptableVersionRange(e){switch(e.versionOperator){case He.Exact:return`exactly ${e.version.major}.${e.version.minor}.${e.version.patch}`;case He.Compatible:return`${e.version.major}.${e.version.minor}.${e.version.patch} to ${e.version.major}.${e.version.minor}.x`;case He.Major:return e.version.major===0?`0.${e.version.minor}.x`:`${e.version.major}.x.x`;case He.Any:return`any version >= ${e.version.major}.${e.version.minor}.${e.version.patch}`;default:return e.toString()}}findSimilarPackages(e,t){if(t.length===0)return[];let o=t.filter(a=>a.toLowerCase().includes(e.toLowerCase())||e.toLowerCase().includes(a.toLowerCase()));if(o.length>0)return o.sort((a,i)=>a.length-i.length);let n=t.map(a=>({package:a,distance:this.levenshteinDistance(e.toLowerCase(),a.toLowerCase())})).sort((a,i)=>a.distance-i.distance),r=Math.max(3,Math.floor(e.length*.4));return n.filter(a=>a.distance<=r).map(a=>a.package)}levenshteinDistance(e,t){if(!e||e.length===0)return t?.length??0;if(!t||t.length===0)return e.length;let o=e.length,n=t.length,r=Array(o+1).fill(null).map(()=>Array(n+1).fill(0));for(let a=0;a<=o;a++)r[a][0]=a;for(let a=0;a<=n;a++)r[0][a]=a;for(let a=1;a<=o;a++)for(let i=1;i<=n;i++){let s=e[a-1]===t[i-1]?0:1;r[a][i]=Math.min(Math.min(r[a-1][i]+1,r[a][i-1]+1),r[a-1][i-1]+s)}return r[o][n]}};var _t="kanonak.org",Lt="core-rdf",Mt=new Set(["type","subClassOf","subPropertyOf","domain","range"].map(c=>K({publisher:_t,package_:Lt,name:c}))),le=class{ruleName="UnresolvedReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of i.statement){let l=Bt(p);if(!(!l||Mt.has(K(l)))){if(p instanceof Be)this.check(r,s,l,p.object,n);else if(p instanceof F)for(let m of p.object)m instanceof I&&this.check(r,s,l,m,n)}}}),n}check(e,t,o,n,r){h(e,n.subject)||r.push(this.unresolvedError(t,o.name,n.subject))}unresolvedError(e,t,o){let n=`${o.publisher}/${o.package_}/${o.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName=t,r.actualValue=n,r.expectedValue="A reference that resolves to a defined or imported resource",r.message=`Reference to '${o.name}' in '${t}' could not be resolved`,r.suggestion=`The entity '${n}' is not defined in this namespace or any imported namespace.
7
7
  \u2022 Import the package that defines it, or check for a typo in '${o.name}'
8
- \u2022 If it lives in an imported namespace, alias-qualify the reference`,r}};function Mt(c){return c.predicate?.subject}var ut={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},ft={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"};function Bt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}function Ge(c,e,t){let o=[],n=new Set,r=new Set,a=i=>{let s=h(c,i),p=s?`${s.namespace}/${s.name}`:K(i);if(n.has(p)){let l=o.findIndex(f=>f.key===p),m=o.slice(l);return m.length<=1?null:[...m.map(f=>f.uri),i]}if(r.has(p))return null;if(n.add(p),o.push({key:p,uri:i}),s)for(let l of Bt(s,t)){let m=a(l);if(m)return m}return o.pop(),n.delete(p),r.add(p),null};return a(e)}var dt=c=>c,me=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!(y.isClassType(dt(i))||y.isDatatypeType(dt(i))))continue;let s=A(i);if(!s)continue;let p=Ge(r,s,ut);if(p){let l=p.map(f=>f.name).join(" \u2192 "),m=new u;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=i.name,m.propertyName="subClassOf",m.actualValue=l,n.push(m);break}}return n}};var Ft=c=>c,ue=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!y.isAnyPropertyType(Ft(i)))continue;let s=A(i);if(!s)continue;let p=Ge(r,s,ft);if(p){let l=p.map(f=>f.name).join(" \u2192 "),m=new u;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=i.name,m.propertyName="subPropertyOf",m.actualValue=l,n.push(m);break}}return n}};var Wt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},yt=c=>c,fe=class{ruleName="PropertyRangeRequired";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);for(let a of r){if(!(a instanceof d))continue;let i=y.isObjectPropertyType(yt(a));!i&&!y.isDatatypePropertyType(yt(a))||J(a,Wt)||n.push(this.error(a.name,i))}return n}error(e,t){let o=new u;return o.ruleType=this.ruleName,o.severity="Error",o.entityName=e,o.propertyName="range",o.message=`Property '${e}' must have a 'range' defined.`,o.suggestion=t?"Add a range like: range: ClassName (the class this property expects)":"Add a range like: range: string (or integer, boolean, etc.)",o.expectedValue=t?"A class name (Character, Scene, Story, etc.)":"A datatype (string, integer, boolean, decimal, etc.)",o}};var Ht={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},gt=c=>c,de=class{ruleName="SubClassOfReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!kt(gt(i)))continue;let s=Gt(i,Ht);for(let p=0;p<s.length;p++)this.resolvesToClassLike(r,s[p])||n.push(this.error(i.name,s[p],s.length>1?`[${p}]`:""))}return n}resolvesToClassLike(e,t){let o=h(e,t);return o?kt(gt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subClassOf",r.actualValue=n,r.expectedValue="Defined or imported class",r.message=`Class '${t.name}' referenced in subClassOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a Class, or import a namespace that contains it`,r}};function kt(c){return y.isClassType(c)||y.isDatatypeType(c)}function Gt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Yt={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"},ht=c=>c,ye=class{ruleName="SubPropertyOfReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!y.isAnyPropertyType(ht(i)))continue;let s=qt(i,Yt);for(let p=0;p<s.length;p++)this.resolvesToProperty(r,s[p])||n.push(this.error(i.name,s[p],s.length>1?`[${p}]`:""))}return n}resolvesToProperty(e,t){let o=h(e,t);return o?y.isAnyPropertyType(ht(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subPropertyOf",r.actualValue=n,r.expectedValue="Defined or imported property",r.message=`Property '${t.name}' referenced in subPropertyOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a property, or import a namespace that contains it`,r}};function qt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var ge=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let o=[],n=e.metadata.namespace_?.toString();if(!n)return o;let r=new Map,a=new Set;await this.buildImportGraph(e,t,r,a);let i=this.detectCycle(n,r);if(i){let s=i.join(" \u2192 "),p=new u;p.ruleType=this.ruleName,p.severity="Error",p.message=`Circular namespace import detected: ${s}`,p.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",p.entityName="imports",p.propertyName="imports",p.actualValue=s,o.push(p)}return o}async buildImportGraph(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!(!r||n.has(r))&&(n.add(r),e.metadata.imports)){let a=[];for(let[i,s]of Object.entries(e.metadata.imports))for(let p of s){let l=`${i}/${p.packageName}@${p.version}`;a.push(l);let m=await t.getHighestCompatibleVersionAsync(i,p);m&&await this.buildImportGraph(m,t,o,n)}a.length>0&&o.set(r,a)}}detectCycle(e,t){let o=[],n=new Set;return this.detectCycleRecursive(e,t,o,n)}detectCycleRecursive(e,t,o,n){let r=o.indexOf(e);if(r>=0){let i=o.slice(r);return i.push(e),i}if(n.has(e))return null;o.push(e),n.add(e);let a=t.get(e);if(a)for(let i of a){let s=this.detectCycleRecursive(i,t,o,n);if(s)return s}return o.pop(),null}};var ke=class{ruleName="UnresolvedPredicate";async validateAsync(e,t,o){let n=[],r=We(e);if(!r)return n;let a=await D(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of i.unresolvedPredicates)p.sourceDoc===r&&n.push(this.unresolvedPredicateError(s,p.key))}),n}unresolvedPredicateError(e,t){let o=t.lastIndexOf("."),n=o>0?t.slice(0,o):null,r=o>0?t.slice(o+1):t,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=t,a.expectedValue="A defined or imported property",a.message=`Property '${t}' is not defined or imported`,a.suggestion=n?`The property '${r}' was not found in the namespace imported as '${n}'.
8
+ \u2022 If it lives in an imported namespace, alias-qualify the reference`,r}};function Bt(c){return c.predicate?.subject}var ft={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},dt={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"};function Ft(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}function Ge(c,e,t){let o=[],n=new Set,r=new Set,a=i=>{let s=h(c,i),p=s?`${s.namespace}/${s.name}`:K(i);if(n.has(p)){let l=o.findIndex(f=>f.key===p),m=o.slice(l);return m.length<=1?null:[...m.map(f=>f.uri),i]}if(r.has(p))return null;if(n.add(p),o.push({key:p,uri:i}),s)for(let l of Ft(s,t)){let m=a(l);if(m)return m}return o.pop(),n.delete(p),r.add(p),null};return a(e)}var yt=c=>c,me=class{ruleName="ClassHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!(y.isClassType(yt(i))||y.isDatatypeType(yt(i))))continue;let s=A(i);if(!s)continue;let p=Ge(r,s,ft);if(p){let l=p.map(f=>f.name).join(" \u2192 "),m=new u;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular class hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subClassOf relationships",m.entityName=i.name,m.propertyName="subClassOf",m.actualValue=l,n.push(m);break}}return n}};var Wt=c=>c,ue=class{ruleName="PropertyHierarchyCycle";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!y.isAnyPropertyType(Wt(i)))continue;let s=A(i);if(!s)continue;let p=Ge(r,s,dt);if(p){let l=p.map(f=>f.name).join(" \u2192 "),m=new u;m.ruleType=this.ruleName,m.severity="Error",m.message=`Circular property hierarchy detected: ${l}`,m.suggestion="Remove the circular dependency by breaking one of the subPropertyOf relationships",m.entityName=i.name,m.propertyName="subPropertyOf",m.actualValue=l,n.push(m);break}}return n}};var Ht={publisher:"kanonak.org",package_:"core-rdf",name:"range"},gt=c=>c,fe=class{ruleName="PropertyRangeRequired";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);for(let a of r){if(!(a instanceof d))continue;let i=y.isObjectPropertyType(gt(a));!i&&!y.isDatatypePropertyType(gt(a))||J(a,Ht)||n.push(this.error(a.name,i))}return n}error(e,t){let o=new u;return o.ruleType=this.ruleName,o.severity="Error",o.entityName=e,o.propertyName="range",o.message=`Property '${e}' must have a 'range' defined.`,o.suggestion=t?"Add a range like: range: ClassName (the class this property expects)":"Add a range like: range: string (or integer, boolean, etc.)",o.expectedValue=t?"A class name (Character, Scene, Story, etc.)":"A datatype (string, integer, boolean, decimal, etc.)",o}};var Gt={publisher:"kanonak.org",package_:"core-rdf",name:"subClassOf"},kt=c=>c,de=class{ruleName="SubClassOfReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!ht(kt(i)))continue;let s=Yt(i,Gt);for(let p=0;p<s.length;p++)this.resolvesToClassLike(r,s[p])||n.push(this.error(i.name,s[p],s.length>1?`[${p}]`:""))}return n}resolvesToClassLike(e,t){let o=h(e,t);return o?ht(kt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subClassOf",r.actualValue=n,r.expectedValue="Defined or imported class",r.message=`Class '${t.name}' referenced in subClassOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a Class, or import a namespace that contains it`,r}};function ht(c){return y.isClassType(c)||y.isDatatypeType(c)}function Yt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var qt={publisher:"kanonak.org",package_:"core-rdf",name:"subPropertyOf"},Rt=c=>c,ye=class{ruleName="SubPropertyOfReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d)||!y.isAnyPropertyType(Rt(i)))continue;let s=zt(i,qt);for(let p=0;p<s.length;p++)this.resolvesToProperty(r,s[p])||n.push(this.error(i.name,s[p],s.length>1?`[${p}]`:""))}return n}resolvesToProperty(e,t){let o=h(e,t);return o?y.isAnyPropertyType(Rt(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="subPropertyOf",r.actualValue=n,r.expectedValue="Defined or imported property",r.message=`Property '${t.name}' referenced in subPropertyOf${o} is not defined or imported`,r.suggestion=`Define '${t.name}' as a property, or import a namespace that contains it`,r}};function zt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var ge=class{get ruleName(){return"NamespaceImportCycle"}async validateAsync(e,t){let o=[],n=e.metadata.namespace_?.toString();if(!n)return o;let r=new Map,a=new Set;await this.buildImportGraph(e,t,r,a);let i=this.detectCycle(n,r);if(i){let s=i.join(" \u2192 "),p=new u;p.ruleType=this.ruleName,p.severity="Error",p.message=`Circular namespace import detected: ${s}`,p.suggestion="Remove one of the imports to break the circular dependency. Circular dependencies prevent proper package resolution.",p.entityName="imports",p.propertyName="imports",p.actualValue=s,o.push(p)}return o}async buildImportGraph(e,t,o,n){let r=e.metadata.namespace_?.toString()??"";if(!(!r||n.has(r))&&(n.add(r),e.metadata.imports)){let a=[];for(let[i,s]of Object.entries(e.metadata.imports))for(let p of s){let l=`${i}/${p.packageName}@${p.version}`;a.push(l);let m=await t.getHighestCompatibleVersionAsync(i,p);m&&await this.buildImportGraph(m,t,o,n)}a.length>0&&o.set(r,a)}}detectCycle(e,t){let o=[],n=new Set;return this.detectCycleRecursive(e,t,o,n)}detectCycleRecursive(e,t,o,n){let r=o.indexOf(e);if(r>=0){let i=o.slice(r);return i.push(e),i}if(n.has(e))return null;o.push(e),n.add(e);let a=t.get(e);if(a)for(let i of a){let s=this.detectCycleRecursive(i,t,o,n);if(s)return s}return o.pop(),null}};var ke=class{ruleName="UnresolvedPredicate";async validateAsync(e,t,o){let n=[],r=We(e);if(!r)return n;let a=await D(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of i.unresolvedPredicates)p.sourceDoc===r&&n.push(this.unresolvedPredicateError(s,p.key))}),n}unresolvedPredicateError(e,t){let o=t.lastIndexOf("."),n=o>0?t.slice(0,o):null,r=o>0?t.slice(o+1):t,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=t,a.expectedValue="A defined or imported property",a.message=`Property '${t}' is not defined or imported`,a.suggestion=n?`The property '${r}' was not found in the namespace imported as '${n}'.
9
9
  1. Check '${r}' is spelled correctly
10
10
  2. Verify '${n}' is imported with the right alias and version
11
11
  3. Ensure that namespace version actually defines '${r}'`:`The property '${t}' is not defined in this namespace or any imported namespace.
@@ -16,10 +16,10 @@ Only embedded objects can infer type from their parent property's range. Subject
16
16
  `),f=e.split(".")[0],R=e.includes(".")?e:t,E=new u;E.ruleType=this.ruleName,E.severity="Error",E.entityName=f,R&&(E.propertyName=R);let N=s??t;return N&&(E.actualValue=N),E.message=`${o} is ambiguous - defined in multiple imported namespaces`,E.suggestion=`${l}
17
17
 
18
18
  Defined in:
19
- ${m}`,E.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",E}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(`${o}/${r.packageName}@${r.version}`===t&&r.alias)return r.alias;return null}};var zt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ye=c=>c,Re=class{ruleName="PropertyRangeReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d))continue;let s=y.isObjectPropertyType(Ye(i));if(!(!s&&!y.isDatatypePropertyType(Ye(i))))for(let p of Xt(i,zt))this.resolvesToClassLike(r,p)||n.push(this.error(i.name,p,s))}return n}resolvesToClassLike(e,t){let o=h(e,t);return o?y.isClassType(Ye(o))||y.isDatatypeType(Ye(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="range",r.actualValue=n,r.expectedValue=o?"A defined or imported class":"A datatype or defined class",r.message=`Property '${e}' has range '${t.name}' which is not defined or imported`,r.suggestion=o?`Define '${t.name}' as a Class here, or import the namespace that contains it (alias-qualify it if imported under an alias).`:`Use a datatype (xsd type, rdfs.Literal, or a datatype-derived type), or \u2014 if '${t.name}' is a class \u2014 make this an ObjectProperty.`,r}};function Xt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Zt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ke="kanonak.org",Je="core-rdf",Qe="core-owl",Jt=c=>c,Qt=[{uri:{publisher:Ke,package_:Je,name:"Class"},ok:c=>y.isClassType(c)||y.isDatatypeType(c)},{uri:{publisher:Ke,package_:Je,name:"Datatype"},ok:c=>y.isDatatypeType(c)},{uri:{publisher:Ke,package_:Je,name:"Property"},ok:c=>y.isAnyPropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"ObjectProperty"},ok:c=>y.isObjectPropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"DatatypeProperty"},ok:c=>y.isDatatypePropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"AnnotationProperty"},ok:c=>y.isAnnotationPropertyType(c)}],be=class{ruleName="ObjectPropertyValue";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof Be)this.check(e,r.predicate?.subject,r.object.subject,o,n);else if(r instanceof H)this.walk(e,r.object,Rt(o,r.predicate?.subject),n);else if(r instanceof F){let a=r.predicate?.subject;for(let i of r.object)i instanceof I?this.check(e,a,i.subject,o,n):i instanceof v&&this.walk(e,i,Rt(o,a),n)}}check(e,t,o,n,r){if(!t)return;let a=h(e,t);if(!a)return;let i=g(a,Zt);if(!i)return;let s=Qt.find(l=>z(i,l.uri));if(!s)return;let p=h(e,o);p&&(s.ok(Jt(p))||r.push(this.warn(n,t,i,o)))}warn(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e.split(".")[0],r.propertyName=e,r.actualValue=n.name,r.expectedValue=o.name,r.message=`Property '${t.name}' expects a ${o.name}, but '${n.name}' is not a ${o.name}`,r.suggestion=`Reference a resource that is a ${o.name}, or correct the type of '${n.name}'.`,r}};function Rt(c,e){return`${c}.${e?.name??"<embedded>"}`}var eo={publisher:"kanonak.org",package_:"core-rdf",name:"type"},to={publisher:"kanonak.org",package_:"core-rdf",name:"domain"},oo={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Ve=class{ruleName="PropertyDomain";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){this.checkNode(e,t,o,n);for(let r of t.statement)if(r instanceof H)this.walk(e,r.object,bt(o,r.predicate?.subject),n);else if(r instanceof F)for(let a of r.object)a instanceof v&&this.walk(e,a,bt(o,r.predicate?.subject),n)}checkNode(e,t,o,n){let r=Kt(t,eo);if(r.length===0)return;let a,i=()=>{if(!a){a=new Set([K(oo)]);for(let p of r)for(let l of Y(e,p))a.add(K(l))}return a},s=new Set;for(let p of t.statement){let l=no(p);if(!l||Fe(l.name)||s.has(K(l)))continue;s.add(K(l));let m=h(e,l);if(!m)continue;let f=Kt(m,to);f.length!==0&&(f.some(R=>i().has(K(R)))||n.push(this.error(o,l,f,r[0])))}}error(e,t,o,n){let r=o.map(i=>i.name).join(" | "),a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e.split(".")[0],a.propertyName=e,a.actualValue=t.name,a.expectedValue=`Property used on ${r} or its subclasses`,a.message=`Property '${t.name}' has domain '${r}' but is used on '${n.name}' at '${e}'`,a.suggestion=`Either:
19
+ ${m}`,E.expectedValue="Unambiguous reference (use namespace alias to disambiguate)",E}findAliasForNamespace(e,t){if(!e.metadata.imports)return null;for(let[o,n]of Object.entries(e.metadata.imports))for(let r of n)if(`${o}/${r.packageName}@${r.version}`===t&&r.alias)return r.alias;return null}};var Xt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ye=c=>c,Re=class{ruleName="PropertyRangeReference";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d))continue;let s=y.isObjectPropertyType(Ye(i));if(!(!s&&!y.isDatatypePropertyType(Ye(i))))for(let p of Zt(i,Xt))this.resolvesToClassLike(r,p)||n.push(this.error(i.name,p,s))}return n}resolvesToClassLike(e,t){let o=h(e,t);return o?y.isClassType(Ye(o))||y.isDatatypeType(Ye(o)):!1}error(e,t,o){let n=`${t.publisher}/${t.package_}/${t.name}`,r=new u;return r.ruleType=this.ruleName,r.severity="Error",r.entityName=e,r.propertyName="range",r.actualValue=n,r.expectedValue=o?"A defined or imported class":"A datatype or defined class",r.message=`Property '${e}' has range '${t.name}' which is not defined or imported`,r.suggestion=o?`Define '${t.name}' as a Class here, or import the namespace that contains it (alias-qualify it if imported under an alias).`:`Use a datatype (xsd type, rdfs.Literal, or a datatype-derived type), or \u2014 if '${t.name}' is a class \u2014 make this an ObjectProperty.`,r}};function Zt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Jt={publisher:"kanonak.org",package_:"core-rdf",name:"range"},Ke="kanonak.org",Je="core-rdf",Qe="core-owl",Qt=c=>c,eo=[{uri:{publisher:Ke,package_:Je,name:"Class"},ok:c=>y.isClassType(c)||y.isDatatypeType(c)},{uri:{publisher:Ke,package_:Je,name:"Datatype"},ok:c=>y.isDatatypeType(c)},{uri:{publisher:Ke,package_:Je,name:"Property"},ok:c=>y.isAnyPropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"ObjectProperty"},ok:c=>y.isObjectPropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"DatatypeProperty"},ok:c=>y.isDatatypePropertyType(c)},{uri:{publisher:Ke,package_:Qe,name:"AnnotationProperty"},ok:c=>y.isAnnotationPropertyType(c)}],be=class{ruleName="ObjectPropertyValue";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){for(let r of t.statement)if(r instanceof Be)this.check(e,r.predicate?.subject,r.object.subject,o,n);else if(r instanceof H)this.walk(e,r.object,Kt(o,r.predicate?.subject),n);else if(r instanceof F){let a=r.predicate?.subject;for(let i of r.object)i instanceof I?this.check(e,a,i.subject,o,n):i instanceof v&&this.walk(e,i,Kt(o,a),n)}}check(e,t,o,n,r){if(!t)return;let a=h(e,t);if(!a)return;let i=g(a,Jt);if(!i)return;let s=eo.find(l=>z(i,l.uri));if(!s)return;let p=h(e,o);p&&(s.ok(Qt(p))||r.push(this.warn(n,t,i,o)))}warn(e,t,o,n){let r=new u;return r.ruleType=this.ruleName,r.severity="Warning",r.entityName=e.split(".")[0],r.propertyName=e,r.actualValue=n.name,r.expectedValue=o.name,r.message=`Property '${t.name}' expects a ${o.name}, but '${n.name}' is not a ${o.name}`,r.suggestion=`Reference a resource that is a ${o.name}, or correct the type of '${n.name}'.`,r}};function Kt(c,e){return`${c}.${e?.name??"<embedded>"}`}var to={publisher:"kanonak.org",package_:"core-rdf",name:"type"},oo={publisher:"kanonak.org",package_:"core-rdf",name:"domain"},no={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"},Ve=class{ruleName="PropertyDomain";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await oe(e,t,o);for(let i of a)i instanceof d&&this.walk(r,i,i.name,n);return n}walk(e,t,o,n){this.checkNode(e,t,o,n);for(let r of t.statement)if(r instanceof H)this.walk(e,r.object,Vt(o,r.predicate?.subject),n);else if(r instanceof F)for(let a of r.object)a instanceof v&&this.walk(e,a,Vt(o,r.predicate?.subject),n)}checkNode(e,t,o,n){let r=bt(t,to);if(r.length===0)return;let a,i=()=>{if(!a){a=new Set([K(no)]);for(let p of r)for(let l of Y(e,p))a.add(K(l))}return a},s=new Set;for(let p of t.statement){let l=ro(p);if(!l||Fe(l.name)||s.has(K(l)))continue;s.add(K(l));let m=h(e,l);if(!m)continue;let f=bt(m,oo);f.length!==0&&(f.some(R=>i().has(K(R)))||n.push(this.error(o,l,f,r[0])))}}error(e,t,o,n){let r=o.map(i=>i.name).join(" | "),a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e.split(".")[0],a.propertyName=e,a.actualValue=t.name,a.expectedValue=`Property used on ${r} or its subclasses`,a.message=`Property '${t.name}' has domain '${r}' but is used on '${n.name}' at '${e}'`,a.suggestion=`Either:
20
20
  1. Use '${t.name}' only on '${r}' (or a subclass) instances
21
21
  2. Widen the property's domain to include '${n.name}'
22
- 3. Use a different property for '${n.name}'`,a}};function no(c){return c.predicate?.subject}function Kt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}function bt(c,e){return`${c}.${e?.name??"<embedded>"}`}var ro={publisher:"kanonak.org",package_:"core-rdf",name:"range"},ao={publisher:"kanonak.org",package_:"core-rdf",name:"Literal"},et=c=>c,Ee=class{ruleName="PropertyKindRangeConsistency";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d))continue;let s=y.isObjectPropertyType(et(i)),p=y.isDatatypePropertyType(et(i));if(!s&&!p)continue;let l=g(i,ro);if(!l||!h(r,l))continue;let m=io(r,l);p&&!m?n.push(this.error(i.name,l,"datatype")):s&&m&&n.push(this.error(i.name,l,"object"))}return n}error(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="range",n.actualValue=t.name,o==="datatype"?(n.expectedValue="A datatype (xsd type, rdfs.Literal, or a datatype-derived class)",n.message=`DatatypeProperty '${e}' has range '${t.name}', which is a class, not a datatype. A datatype property's values are literals.`,n.suggestion=`Use a datatype range (e.g. xsd.string, rdfs.Literal, or a datatype-derived class), or \u2014 if '${t.name}' is the intended target \u2014 declare '${e}' an ObjectProperty.`):(n.expectedValue="A plain class (not datatype-derived)",n.message=`ObjectProperty '${e}' has range '${t.name}', which is a datatype, not a class. An object property's values are references to resources.`,n.suggestion=`Declare '${e}' a DatatypeProperty (its values are literals of '${t.name}'), or change the range to a plain class.`),n}};function io(c,e){for(let t of Y(c,e)){if(z(t,ao))return!0;let o=h(c,t);if(o&&y.isDatatypeType(et(o)))return!0}return!1}var ve=class{ruleName="ReservedNameShadow";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);for(let a of r){if(!(a instanceof d))continue;let i=st(a.name);if(!i)continue;let s=A(a);s&&(i.publisher===s.publisher&&i.package_===s.package_||n.push(this.info(a.name,s,i)))}return n}info(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Info",n.entityName=e,n.propertyName=e,n.actualValue=`${t.publisher}/${t.package_}/${e}`,n.expectedValue=`${o.publisher}/${o.package_}/${e}`,n.message=`'${e}' is also the reserved built-in '${o.publisher}/${o.package_}/${e}'. This local definition shadows it \u2014 a bare '${e}' reference in this package resolves to the local entity, not the built-in.`,n.suggestion=`If this is intentional, qualify bare references to '${e}' explicitly (this local one vs. the built-in '${o.publisher}/${o.package_}/${e}') so the choice is unambiguous to readers and tools \u2014 e.g. a self-referential 'subClassOf: ${e}' silently resolves to this local entity.`,n}};var so={publisher:"kanonak.org",package_:"core-rdf",name:"type"},Vt=c=>c,De=class{ruleName="ClassDefinition";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of co(i,so))this.resolvesToClassLike(r,p)||n.push(this.error(s,p))}),n}resolvesToClassLike(e,t){if(Fe(t.name))return!0;let o=h(e,t);return o?y.isClassType(Vt(o))||y.isDatatypeType(Vt(o)):!1}error(e,t){let o=`${t.publisher}/${t.package_}/${t.name}`,n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="type",n.actualValue=o,n.expectedValue="Defined or imported class",n.message=`Class '${t.name}' is not defined or imported`,n.suggestion=`Define '${t.name}' as a Class in this document, or import a namespace that contains it`,n}};function co(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Ie=class{ruleName="MarkdownLink";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);return q(r,({kanonak:a,path:i})=>{this.checkNode(a,i,n)}),n}checkNode(e,t,o){for(let n of e.statement){if(!(n instanceof it))continue;let r=n.predicate.subject?.name??"(unknown)";for(let a of n.links)a.target||o.push(this.unresolvedLinkError(t,r,a.reference));for(let a of ct(n.object))o.push(this.malformedLinkError(t,r,a.snippet))}}unresolvedLinkError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Embedded link [[${o}]] in '${t}' could not be resolved`,n.expectedValue="A reference resolvable through the document's import closure",n.suggestion=`The reference '${o}' inside a markdown value cannot be found in the current document or any imported namespace.
22
+ 3. Use a different property for '${n.name}'`,a}};function ro(c){return c.predicate?.subject}function bt(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}function Vt(c,e){return`${c}.${e?.name??"<embedded>"}`}var ao={publisher:"kanonak.org",package_:"core-rdf",name:"range"},io={publisher:"kanonak.org",package_:"core-rdf",name:"Literal"},et=c=>c,Ee=class{ruleName="PropertyKindRangeConsistency";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);for(let i of a){if(!(i instanceof d))continue;let s=y.isObjectPropertyType(et(i)),p=y.isDatatypePropertyType(et(i));if(!s&&!p)continue;let l=g(i,ao);if(!l||!h(r,l))continue;let m=so(r,l);p&&!m?n.push(this.error(i.name,l,"datatype")):s&&m&&n.push(this.error(i.name,l,"object"))}return n}error(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="range",n.actualValue=t.name,o==="datatype"?(n.expectedValue="A datatype (xsd type, rdfs.Literal, or a datatype-derived class)",n.message=`DatatypeProperty '${e}' has range '${t.name}', which is a class, not a datatype. A datatype property's values are literals.`,n.suggestion=`Use a datatype range (e.g. xsd.string, rdfs.Literal, or a datatype-derived class), or \u2014 if '${t.name}' is the intended target \u2014 declare '${e}' an ObjectProperty.`):(n.expectedValue="A plain class (not datatype-derived)",n.message=`ObjectProperty '${e}' has range '${t.name}', which is a datatype, not a class. An object property's values are references to resources.`,n.suggestion=`Declare '${e}' a DatatypeProperty (its values are literals of '${t.name}'), or change the range to a plain class.`),n}};function so(c,e){for(let t of Y(c,e)){if(z(t,io))return!0;let o=h(c,t);if(o&&y.isDatatypeType(et(o)))return!0}return!1}var ve=class{ruleName="ReservedNameShadow";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);for(let a of r){if(!(a instanceof d))continue;let i=st(a.name);if(!i)continue;let s=A(a);s&&(i.publisher===s.publisher&&i.package_===s.package_||n.push(this.info(a.name,s,i)))}return n}info(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Info",n.entityName=e,n.propertyName=e,n.actualValue=`${t.publisher}/${t.package_}/${e}`,n.expectedValue=`${o.publisher}/${o.package_}/${e}`,n.message=`'${e}' is also the reserved built-in '${o.publisher}/${o.package_}/${e}'. This local definition shadows it \u2014 a bare '${e}' reference in this package resolves to the local entity, not the built-in.`,n.suggestion=`If this is intentional, qualify bare references to '${e}' explicitly (this local one vs. the built-in '${o.publisher}/${o.package_}/${e}') so the choice is unambiguous to readers and tools \u2014 e.g. a self-referential 'subClassOf: ${e}' silently resolves to this local entity.`,n}};var co={publisher:"kanonak.org",package_:"core-rdf",name:"type"},Et=c=>c,De=class{ruleName="ClassDefinition";async validateAsync(e,t,o){let n=[],r=await D(e,t,o),a=await C(e,t,o);return q(a,({kanonak:i,path:s})=>{for(let p of po(i,co))this.resolvesToClassLike(r,p)||n.push(this.error(s,p))}),n}resolvesToClassLike(e,t){if(Fe(t.name))return!0;let o=h(e,t);return o?y.isClassType(Et(o))||y.isDatatypeType(Et(o)):!1}error(e,t){let o=`${t.publisher}/${t.package_}/${t.name}`,n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName="type",n.actualValue=o,n.expectedValue="Defined or imported class",n.message=`Class '${t.name}' is not defined or imported`,n.suggestion=`Define '${t.name}' as a Class in this document, or import a namespace that contains it`,n}};function po(c,e){let t=g(c,e);if(t)return[t];let o=[];for(let n of V(c,e))n instanceof I&&o.push(n.subject);return o}var Ie=class{ruleName="MarkdownLink";async validateAsync(e,t,o){let n=[],r=await C(e,t,o);return q(r,({kanonak:a,path:i})=>{this.checkNode(a,i,n)}),n}checkNode(e,t,o){for(let n of e.statement){if(!(n instanceof it))continue;let r=n.predicate.subject?.name??"(unknown)";for(let a of n.links)a.target||o.push(this.unresolvedLinkError(t,r,a.reference));for(let a of ct(n.object))o.push(this.malformedLinkError(t,r,a.snippet))}}unresolvedLinkError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`Embedded link [[${o}]] in '${t}' could not be resolved`,n.expectedValue="A reference resolvable through the document's import closure",n.suggestion=`The reference '${o}' inside a markdown value cannot be found in the current document or any imported namespace.
23
23
 
24
24
  Possible solutions:
25
25
  \u2022 Import the package that defines '${o}' so the link can resolve
@@ -31,22 +31,22 @@ long reference across two lines in a block scalar, e.g.:
31
31
  ... read for [[persistent-energy-
32
32
  shock]] held ...
33
33
  which is parsed as literal text, not a link. Keep each [[reference]] on one
34
- line (let the line run long), or check for an unterminated [[.`,n}};var Et="kanonak.org",vt="look",po={publisher:Et,package_:vt,name:"displayLabel"},lo={publisher:Et,package_:vt,name:"displaySummary"},Ce=class{ruleName="DisplayLensScope";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=mo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&(this.checkLens(r,i,po,"displayLabel",n),this.checkLens(r,i,lo,"displaySummary",n));return n}checkLens(e,t,o,n,r){let a=g(t,o);if(!a)return;let i=[],s=A(t);if(s&&i.push(s),i.push(...lt(t)),i.length===0)return;i.some(l=>L(e,l,a).ok)||r.push(this.scopeError(t.name,n,a.name))}scopeError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`${t} points at '${o}', which is not a property in scope for '${e}'`,n.expectedValue="A property whose domain is this resource's class, an ancestor, or rdfs.Resource",n.suggestion=`'${o}' resolves, but its domain does not cover '${e}', so the lens would silently fall back to the resource's name at render time.
34
+ line (let the line run long), or check for an unterminated [[.`,n}};var vt="kanonak.org",Dt="look",lo={publisher:vt,package_:Dt,name:"displayLabel"},mo={publisher:vt,package_:Dt,name:"displaySummary"},Ce=class{ruleName="DisplayLensScope";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=uo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&(this.checkLens(r,i,lo,"displayLabel",n),this.checkLens(r,i,mo,"displaySummary",n));return n}checkLens(e,t,o,n,r){let a=g(t,o);if(!a)return;let i=[],s=A(t);if(s&&i.push(s),i.push(...lt(t)),i.length===0)return;i.some(l=>L(e,l,a).ok)||r.push(this.scopeError(t.name,n,a.name))}scopeError(e,t,o){let n=new u;return n.ruleType=this.ruleName,n.severity="Error",n.entityName=e,n.propertyName=t,n.actualValue=o,n.message=`${t} points at '${o}', which is not a property in scope for '${e}'`,n.expectedValue="A property whose domain is this resource's class, an ancestor, or rdfs.Resource",n.suggestion=`'${o}' resolves, but its domain does not cover '${e}', so the lens would silently fall back to the resource's name at render time.
35
35
 
36
36
  Possible solutions:
37
37
  \u2022 Point ${t} at a property declared on this class (or an ancestor / rdfs.Resource)
38
38
  \u2022 Set the property's domain to this class if it should apply here
39
- \u2022 Use rdfs.label / rdfs.comment for the universal default`,n}};function mo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function X(c,e,t){let o=[];return Te(c,t,{input:e},o),o}function Te(c,e,t,o){if(P(e,M.VarRef)){let a=W(e,M.varName);return a?t[a]:void 0}if(P(e,M.PropertyRead)){let a=O(e,M.readSource),i=a?Te(c,a,t,o):void 0,s=g(e,M.readProp);if(!i||!s)return;let p=L(c,i,s);if(!p.ok){o.push({contextClass:i,propertyUri:s,via:"PropertyRead"});return}return p.descriptor?.range}if(P(e,M.Traverse)){let a=O(e,M.traverseSource),i=a?Te(c,a,t,o):void 0,s=g(e,M.through),p;if(i&&s){let m=L(c,i,s);m.ok?p=m.descriptor?.range:o.push({contextClass:i,propertyUri:s,via:"Traverse"})}let l=O(e,M.step);return l?Te(c,l,{...t,input:p},o):void 0}let n=W(e,M.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of uo(e))Te(c,a,r,o)}function uo(c){let e=[];for(let t of c.statement){let o=t.object;if(o instanceof v)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof v&&e.push(n)}return e}var Ne="kanonak.org",_e="look",fo={publisher:Ne,package_:_e,name:"semanticSvg"},yo={publisher:Ne,package_:_e,name:"tierChip"},go={publisher:Ne,package_:_e,name:"tierIcon"},ko={publisher:Ne,package_:_e,name:"tierCard"},ho={publisher:Ne,package_:_e,name:"tierFull"},Ro=[yo,go,ko,ho],Se=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=Ko(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=O(t,fo);if(!n)return;let r=A(t);if(r)for(let a of Ro){let i=O(n,a);if(i)for(let s of X(e,r,i))o.push(this.toError(t.name,a.name,s))}}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=r===e?`'${e}' (the class this SemanticSvg is declared on)`:`'${r}', reached by traversal from '${e}' (the class this SemanticSvg is declared on)`,i=new u;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=`look.semanticSvg.${t}`,i.actualValue=n,i.message=`tx.${o.via} reads property '${o.propertyUri.name}' off the rendered instance, but its domain is not in scope for ${a}. The read would silently return undefined at render time.`,i.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,i.suggestion=`Property '${n}' is not in scope for '${r}'.
39
+ \u2022 Use rdfs.label / rdfs.comment for the universal default`,n}};function uo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function X(c,e,t){let o=[];return Te(c,t,{input:e},o),o}function Te(c,e,t,o){if(P(e,M.VarRef)){let a=W(e,M.varName);return a?t[a]:void 0}if(P(e,M.PropertyRead)){let a=O(e,M.readSource),i=a?Te(c,a,t,o):void 0,s=g(e,M.readProp);if(!i||!s)return;let p=L(c,i,s);if(!p.ok){o.push({contextClass:i,propertyUri:s,via:"PropertyRead"});return}return p.descriptor?.range}if(P(e,M.Traverse)){let a=O(e,M.traverseSource),i=a?Te(c,a,t,o):void 0,s=g(e,M.through),p;if(i&&s){let m=L(c,i,s);m.ok?p=m.descriptor?.range:o.push({contextClass:i,propertyUri:s,via:"Traverse"})}let l=O(e,M.step);return l?Te(c,l,{...t,input:p},o):void 0}let n=W(e,M.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of fo(e))Te(c,a,r,o)}function fo(c){let e=[];for(let t of c.statement){let o=t.object;if(o instanceof v)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof v&&e.push(n)}return e}var Ne="kanonak.org",_e="look",yo={publisher:Ne,package_:_e,name:"semanticSvg"},go={publisher:Ne,package_:_e,name:"tierChip"},ko={publisher:Ne,package_:_e,name:"tierIcon"},ho={publisher:Ne,package_:_e,name:"tierCard"},Ro={publisher:Ne,package_:_e,name:"tierFull"},Ko=[go,ko,ho,Ro],Se=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=bo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=O(t,yo);if(!n)return;let r=A(t);if(r)for(let a of Ko){let i=O(n,a);if(i)for(let s of X(e,r,i))o.push(this.toError(t.name,a.name,s))}}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=r===e?`'${e}' (the class this SemanticSvg is declared on)`:`'${r}', reached by traversal from '${e}' (the class this SemanticSvg is declared on)`,i=new u;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=`look.semanticSvg.${t}`,i.actualValue=n,i.message=`tx.${o.via} reads property '${o.propertyUri.name}' off the rendered instance, but its domain is not in scope for ${a}. The read would silently return undefined at render time.`,i.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,i.suggestion=`Property '${n}' is not in scope for '${r}'.
40
40
 
41
41
  Possible solutions:
42
42
  \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
43
43
  \u2022 If the property should apply to '${r}', adjust its domain
44
- \u2022 If the value comes from a pre-computed env binding, use tx.VarRef instead of PropertyRead`,i}};function Ko(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var bo="kanonak.org",b=(c,e)=>({publisher:bo,package_:c,name:e}),Vo=b("derivation","look"),Eo=b("look","bands"),vo=b("look","Distribution"),Do=b("look","StatRow"),Io=b("look","VersionDelta"),Co=b("look","Timeline"),So=b("look","VersionDiff"),Po=b("look","TimePlot"),jo=b("look","ReferenceList"),$o=b("look","Diagram"),Oo=b("look","alphaPath"),Uo=b("look","betaPath"),tt=b("look","metricPath"),Dt=b("look","lowerPath"),It=b("look","upperPath"),Ct=b("look","hueBy"),Ao=b("look","statPath"),wo=b("look","laneBy"),St=b("look","labelPath"),xo=b("look","badgePath"),To=b("look","mapPath"),No=b("look","nodeNote"),_o=b("look","edgeValue"),Lo=b("look","stats"),Mo=b("look","facets"),Bo=b("look","channels"),Fo=b("look","track"),Wo=b("look","source"),Ho=b("look","relation"),Go=b("look","entries"),Le=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=qo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=O(t,Vo);if(!n)return;let r=A(t);if(!r)return;let a=V(n,Eo).filter(i=>i instanceof v);for(let i of a)for(let s of this.carriersOf(e,i,r))for(let p of X(e,s.context,s.expr))o.push(this.toError(t.name,s.slot,p))}carriersOf(e,t,o){let n=[],r=(a,i)=>{let s=O(t,a);s&&n.push({slot:`look.${a.name}`,context:i,expr:s})};if(P(t,vo))for(let a of[Oo,Uo,tt,Dt,It,Ct])r(a,o);if(P(t,Io)&&r(tt,o),P(t,Do)){let a=V(t,Lo).filter(i=>i instanceof v);for(let i of a){let s=O(i,Ao);s&&n.push({slot:"look.stats[].statPath",context:o,expr:s})}}if(P(t,Co)||P(t,So)){let a=this.rangeOf(e,o,g(t,Fo));if(a)for(let i of[tt,Dt,It,Ct])r(i,a)}if(P(t,Po)){let a=this.rangeOf(e,o,g(t,Wo));if(a)for(let i of[wo,St])r(i,a)}if(P(t,jo))for(let a of V(t,Go)){let i=a instanceof v?void 0:Yo(a),s=this.rangeOf(e,o,i);if(s)for(let p of[St,xo])r(p,s)}if(P(t,$o)){let a=V(t,Mo).filter(i=>i instanceof v);for(let i of a){let s=this.rangeOf(e,o,g(i,Ho));if(!s)continue;let p=O(i,No);p&&n.push({slot:"look.facets[].nodeNote",context:s,expr:p});let l=O(i,_o);l&&n.push({slot:"look.facets[].edgeValue",context:s,expr:l});let m=V(i,Bo).filter(f=>f instanceof v);for(let f of m){let R=O(f,To);R&&n.push({slot:"look.facets[].channels[].mapPath",context:s,expr:R})}}}return n}rangeOf(e,t,o){if(!o)return;let n=L(e,t,o);return n.ok?n.descriptor?.range:void 0}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=n,a.message=`tx.${o.via} reads property '${o.propertyUri.name}', but its domain is not in scope for '${r}' (the class this band carrier is evaluated against). The read would silently return undefined at render time and the band would render empty.`,a.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${n}' is not in scope for '${r}'.
44
+ \u2022 If the value comes from a pre-computed env binding, use tx.VarRef instead of PropertyRead`,i}};function bo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Vo="kanonak.org",b=(c,e)=>({publisher:Vo,package_:c,name:e}),Eo=b("derivation","look"),vo=b("look","bands"),Do=b("look","Distribution"),Io=b("look","StatRow"),Co=b("look","VersionDelta"),So=b("look","Timeline"),Po=b("look","VersionDiff"),jo=b("look","TimePlot"),$o=b("look","ReferenceList"),Oo=b("look","Diagram"),Uo=b("look","alphaPath"),Ao=b("look","betaPath"),tt=b("look","metricPath"),It=b("look","lowerPath"),Ct=b("look","upperPath"),St=b("look","hueBy"),wo=b("look","statPath"),xo=b("look","laneBy"),Pt=b("look","labelPath"),To=b("look","badgePath"),No=b("look","mapPath"),_o=b("look","nodeNote"),Lo=b("look","edgeValue"),Mo=b("look","stats"),Bo=b("look","facets"),Fo=b("look","channels"),Wo=b("look","track"),Ho=b("look","source"),Go=b("look","relation"),Yo=b("look","entries"),Le=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=zo(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=O(t,Eo);if(!n)return;let r=A(t);if(!r)return;let a=V(n,vo).filter(i=>i instanceof v);for(let i of a)for(let s of this.carriersOf(e,i,r))for(let p of X(e,s.context,s.expr))o.push(this.toError(t.name,s.slot,p))}carriersOf(e,t,o){let n=[],r=(a,i)=>{let s=O(t,a);s&&n.push({slot:`look.${a.name}`,context:i,expr:s})};if(P(t,Do))for(let a of[Uo,Ao,tt,It,Ct,St])r(a,o);if(P(t,Co)&&r(tt,o),P(t,Io)){let a=V(t,Mo).filter(i=>i instanceof v);for(let i of a){let s=O(i,wo);s&&n.push({slot:"look.stats[].statPath",context:o,expr:s})}}if(P(t,So)||P(t,Po)){let a=this.rangeOf(e,o,g(t,Wo));if(a)for(let i of[tt,It,Ct,St])r(i,a)}if(P(t,jo)){let a=this.rangeOf(e,o,g(t,Ho));if(a)for(let i of[xo,Pt])r(i,a)}if(P(t,$o))for(let a of V(t,Yo)){let i=a instanceof v?void 0:qo(a),s=this.rangeOf(e,o,i);if(s)for(let p of[Pt,To])r(p,s)}if(P(t,Oo)){let a=V(t,Bo).filter(i=>i instanceof v);for(let i of a){let s=this.rangeOf(e,o,g(i,Go));if(!s)continue;let p=O(i,_o);p&&n.push({slot:"look.facets[].nodeNote",context:s,expr:p});let l=O(i,Lo);l&&n.push({slot:"look.facets[].edgeValue",context:s,expr:l});let m=V(i,Fo).filter(f=>f instanceof v);for(let f of m){let R=O(f,No);R&&n.push({slot:"look.facets[].channels[].mapPath",context:s,expr:R})}}}return n}rangeOf(e,t,o){if(!o)return;let n=L(e,t,o);return n.ok?n.descriptor?.range:void 0}toError(e,t,o){let n=`${o.propertyUri.publisher}/${o.propertyUri.package_}/${o.propertyUri.name}`,r=o.contextClass.name,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=t,a.actualValue=n,a.message=`tx.${o.via} reads property '${o.propertyUri.name}', but its domain is not in scope for '${r}' (the class this band carrier is evaluated against). The read would silently return undefined at render time and the band would render empty.`,a.expectedValue=`A property whose domain is '${r}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${n}' is not in scope for '${r}'.
45
45
 
46
46
  Possible solutions:
47
47
  \u2022 Read a property declared on '${r}' (or an ancestor / rdfs.Resource)
48
48
  \u2022 If the property should apply to '${r}', adjust its domain
49
- \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,a}};function Yo(c){let e=c.subject;return e&&typeof e.name=="string"?e:void 0}function qo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var je="kanonak.org",$e="view",zo={publisher:je,package_:$e,name:"bind"},Xo={publisher:je,package_:$e,name:"produces"},Zo={publisher:je,package_:$e,name:"projections"},Jo={publisher:je,package_:$e,name:"where"},Qo={publisher:je,package_:$e,name:"value"},en={publisher:je,package_:$e,name:"as"},Pe=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=nn(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=g(t,zo);if(!n)return;let r=g(t,Xo),a=0;for(let s of on(e,V(t,Zo))){let p=O(s,Qo);if(p)for(let m of X(e,n,p))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=g(s,en);l&&r&&(L(e,r,l).ok||o.push(this.asError(t.name,a,r,l))),a+=1}let i=0;for(let s of tn(t,Jo)){for(let p of X(e,n,s))o.push(this.toError(t.name,`view.where[${i}]`,n,p));i+=1}}asError(e,t,o,n){let r=`${n.publisher}/${n.package_}/${n.name}`,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=`view.projections[${t}].as`,a.actualValue=r,a.message=`Projection stores its value under property '${n.name}', but that property's domain is not in scope for the view's produces class '${o.name}'. The materialized result instance could not carry this value.`,a.expectedValue=`A property whose domain is '${o.name}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${r}' is not in scope for produces class '${o.name}'.
49
+ \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,a}};function qo(c){let e=c.subject;return e&&typeof e.name=="string"?e:void 0}function zo(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var je="kanonak.org",$e="view",Xo={publisher:je,package_:$e,name:"bind"},Zo={publisher:je,package_:$e,name:"produces"},Jo={publisher:je,package_:$e,name:"projections"},Qo={publisher:je,package_:$e,name:"where"},en={publisher:je,package_:$e,name:"value"},tn={publisher:je,package_:$e,name:"as"},Pe=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new G(e,t));let a=rn(e);if(!a)return n;for(let i of r)i instanceof d&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=g(t,Xo);if(!n)return;let r=g(t,Zo),a=0;for(let s of nn(e,V(t,Jo))){let p=O(s,en);if(p)for(let m of X(e,n,p))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=g(s,tn);l&&r&&(L(e,r,l).ok||o.push(this.asError(t.name,a,r,l))),a+=1}let i=0;for(let s of on(t,Qo)){for(let p of X(e,n,s))o.push(this.toError(t.name,`view.where[${i}]`,n,p));i+=1}}asError(e,t,o,n){let r=`${n.publisher}/${n.package_}/${n.name}`,a=new u;return a.ruleType=this.ruleName,a.severity="Error",a.entityName=e,a.propertyName=`view.projections[${t}].as`,a.actualValue=r,a.message=`Projection stores its value under property '${n.name}', but that property's domain is not in scope for the view's produces class '${o.name}'. The materialized result instance could not carry this value.`,a.expectedValue=`A property whose domain is '${o.name}', an ancestor, or rdfs.Resource`,a.suggestion=`Property '${r}' is not in scope for produces class '${o.name}'.
50
50
 
51
51
  Possible solutions:
52
52
  \u2022 Use an output property whose domain covers '${o.name}'
@@ -56,8 +56,8 @@ Possible solutions:
56
56
  Possible solutions:
57
57
  \u2022 Read a property declared on '${a}' (or an ancestor / rdfs.Resource)
58
58
  \u2022 If the property should apply to '${a}', adjust its domain
59
- \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,s}};function tn(c,e){let t=O(c,e);return t?[t]:V(c,e).filter(o=>o instanceof v)}function on(c,e){let t=[];for(let o of e)if(o instanceof v)t.push(o);else if(o instanceof I){let n=h(c,o.subject);n&&t.push(n)}return t}function nn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var qe="kanonak.org",rn="core-shacl",w=c=>({publisher:qe,package_:rn,name:c}),an=w("NodeShape"),sn=w("PropertyShape"),cn=w("targetClass"),pn=w("property"),ln=w("path"),mn=w("minCount"),un=w("maxCount"),fn=w("datatype"),dn=w("class"),Pt=w("in"),yn=w("pattern"),gn=w("flags"),kn=w("minLength"),hn=w("maxLength"),Rn=w("minInclusive"),Kn=w("maxInclusive"),bn=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),ot=c=>c,Ue=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Vn(e);if(!a)return n;let i=new Set;for(let s of r){if(!(s instanceof d)||s.namespace!==a||!P(s,an))continue;let p=g(s,cn);p?this.resolvesToClass(r,p)||n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' sh:targetClass '${p.name}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",Z(p))):n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' has no sh:targetClass; it constrains nothing.`,"Add sh:targetClass naming the class this shape applies to."));for(let l of V(s,pn)){let m;if(l instanceof v)m=l;else if(l instanceof I){let f=h(r,l.subject);f&&(m=f,i.add(K(l.subject)))}m&&this.checkPropertyShape(r,s.name,m,p??void 0,n)}}for(let s of r){if(!(s instanceof d)||s.namespace!==a||!P(s,sn))continue;let p=A(s);p&&i.has(K(p))||this.checkPropertyShape(r,s.name,s,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=g(o,ln);if(!a){r.push(this.err(t,"property.path","Error",`A PropertyShape on '${t}' has no sh:path; a PropertyShape must name the property it constrains.`,"Add sh:path naming a property."));return}let i=h(e,a),s=i?y.isAnyPropertyType(ot(i)):!1;s?n&&(L(e,n,a).ok||r.push(this.err(t,"property.path","Warning",`sh:path '${a.name}' is not in scope for sh:targetClass '${n.name}'; the constraint would never bind a value.`,`Constrain a property whose domain is '${n.name}', an ancestor, or rdfs.Resource.`,Z(a)))):r.push(this.err(t,"property.path","Error",`sh:path '${a.name}' on '${t}' does not resolve to a property.`,"Reference a defined or imported property.",Z(a)));let p=g(o,fn),l=g(o,dn);p&&l&&r.push(this.err(t,"property","Error",`A PropertyShape on '${t}' sets both sh:datatype and sh:class; a value is a literal or a node, not both.`,"Keep sh:datatype (literal values) or sh:class (node values), not both.")),p&&!this.resolvesToDatatype(e,p)&&r.push(this.err(t,"datatype","Error",`sh:datatype '${p.name}' on '${t}' does not resolve to a datatype.`,"Reference an xsd datatype or rdfs.Datatype.",Z(p))),l&&!this.resolvesToClass(e,l)&&r.push(this.err(t,"class","Error",`sh:class '${l.name}' on '${t}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",Z(l)));let m=Oe(x(o,mn)),f=Oe(x(o,un));this.checkOrder(t,"minCount",m,"maxCount",f,r);let R=Oe(x(o,kn)),E=Oe(x(o,hn));this.checkOrder(t,"minLength",R,"maxLength",E,r);let N=Oe(x(o,Rn)),j=Oe(x(o,Kn));this.checkOrder(t,"minInclusive",N,"maxInclusive",j,r);let $=W(o,yn);if($!==void 0){let B=W(o,gn);try{new RegExp($,B)}catch{r.push(this.err(t,"pattern","Error",`sh:pattern on '${t}' is not a valid regular expression`+(B!==void 0?` (with flags '${B}')`:"")+`: ${$}`,"Provide a valid regular expression and flags.",$))}}if(J(o,Pt)&&V(o,Pt).length===0&&r.push(this.err(t,"in","Error",`sh:in on '${t}' is empty; an enumeration must list at least one permitted value.`,"List the permitted literal values, or remove sh:in.")),s&&n){let _=L(e,n,a).descriptor;_&&(($!==void 0||R!==void 0||E!==void 0)&&_.kind==="object"&&r.push(this.err(t,"pattern/minLength/maxLength","Warning",`String facets on '${t}' apply to '${a.name}', which is an object property; string facets constrain literal values.`,"Apply string facets to a datatype property, or use sh:class for node values.",Z(a))),(N!==void 0||j!==void 0)&&!this.isNumericDatatypeRange(_.range)&&r.push(this.err(t,"minInclusive/maxInclusive","Warning",`Numeric bounds on '${t}' apply to '${a.name}', whose range is not a numeric datatype.`,"Apply numeric bounds to a numeric datatype property.",Z(a))))}}checkOrder(e,t,o,n,r,a){o!==void 0&&r!==void 0&&o>r&&a.push(this.err(e,`${t}/${n}`,"Error",`${t} (${o}) exceeds ${n} (${r}) on '${e}'.`,`Set ${t} <= ${n}.`))}resolvesToClass(e,t){let o=h(e,t);return o?y.isClassType(ot(o)):!1}resolvesToDatatype(e,t){if(t.publisher===qe&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=h(e,t);return o?y.isDatatypeType(ot(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===qe&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===qe&&e.package_==="core-xsd"&&bn.has(e.name)}err(e,t,o,n,r,a){let i=new u;return i.ruleType=this.ruleName,i.severity=o,i.entityName=e,i.propertyName=t,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function Oe(c){return typeof c=="number"?c:void 0}function Z(c){return`${c.publisher}/${c.package_}/${c.name}`}function Vn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var jt={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},En=c=>c,Ae=class{ruleName="OwlOneOf";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=vn(e);if(!a)return n;for(let i of r){if(!(i instanceof d)||i.namespace!==a||!J(i,jt))continue;let s=V(i,jt);if(s.length===0){n.push(this.err(i.name,"Warning",`owl:oneOf on '${i.name}' is empty; a closed enumeration must list at least one individual.`,"List the individuals that make up the enumeration, or remove owl:oneOf."));continue}for(let p of s)if(p instanceof Me)n.push(this.err(i.name,"Error",`owl:oneOf member '${String(p.value)}' on '${i.name}' is not a named individual; a class enumeration is of individuals (a misspelled or unimported individual reads as a literal). For a closed set of literal VALUES, constrain a property with sh:in instead.`,"Reference a defined or imported individual, or move literal value sets to a property sh:in.",String(p.value)));else if(p instanceof I){let l=h(r,p.subject);l&&y.isSchemaDefinitionType(En(l))&&n.push(this.err(i.name,"Error",`owl:oneOf member '${p.subject.name}' on '${i.name}' is a class/property/datatype, not an individual.`,"List named individuals (instances), not schema definitions.",`${p.subject.publisher}/${p.subject.package_}/${p.subject.name}`))}}return n}err(e,t,o,n,r){let a=new u;return a.ruleType=this.ruleName,a.severity=t,a.entityName=e,a.propertyName="oneOf",a.message=o,a.suggestion=n,r!==void 0&&(a.actualValue=r),a}};function vn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Dn="kanonak.org",In="core-shacl",T=c=>({publisher:Dn,package_:In,name:c}),Cn=T("NodeShape"),Sn=T("targetClass"),Pn=T("property"),jn=T("path"),$n=T("minCount"),On=T("maxCount"),Un=T("in"),An=T("pattern"),wn=T("flags"),xn=T("minLength"),Tn=T("maxLength"),Nn=T("minInclusive"),_n=T("maxInclusive"),Ln=T("message");function we(c){return typeof c=="number"?c:void 0}function Mn(c){let e={},t=we(x(c,$n)),o=we(x(c,On));t!==void 0&&(e.minCount=t),o!==void 0&&(e.maxCount=o);let n=we(x(c,xn)),r=we(x(c,Tn));n!==void 0&&(e.minLength=n),r!==void 0&&(e.maxLength=r);let a=we(x(c,Nn)),i=we(x(c,_n));a!==void 0&&(e.minInclusive=a),i!==void 0&&(e.maxInclusive=i);let s=W(c,An);if(s!==void 0){let m=W(c,wn);e.pattern=m!==void 0?{regex:s,flags:m}:{regex:s}}let p=V(c,Un).filter(m=>m instanceof Me).map(m=>m.value);p.length>0&&(e.enumValues=p);let l=W(c,Ln);return l!==void 0&&(e.message=l),e}function Bn(c,e){let t=[];for(let o of V(e,Pn))if(o instanceof v)t.push(o);else if(o instanceof I){let n=h(c,o.subject);n&&t.push(n)}return t}function $t(c){let e=new Map;for(let t of c){if(!(t instanceof d)||!P(t,Cn))continue;let o=g(t,Sn);if(!o)continue;let n=K(o);for(let r of Bn(c,t)){let a=g(r,jn);if(!a)continue;let i={pathKey:K(a),constraints:Mn(r)},s=e.get(n);s?s.push(i):e.set(n,[i])}}return e}function Fn(c,e){e.minCount!==void 0&&(c.minCount=e.minCount),e.maxCount!==void 0&&(c.maxCount=e.maxCount),e.minLength!==void 0&&(c.minLength=e.minLength),e.maxLength!==void 0&&(c.maxLength=e.maxLength),e.minInclusive!==void 0&&(c.minInclusive=e.minInclusive),e.maxInclusive!==void 0&&(c.maxInclusive=e.maxInclusive),e.pattern!==void 0&&(c.pattern=e.pattern),e.enumValues!==void 0&&(c.enumValues=e.enumValues),e.message!==void 0&&(c.message=e.message)}function Ot(c,e,t){let o=K(t),n=!1,r={};for(let a=e.length-1;a>=0;a--){let i=c.get(K(e[a]));if(i)for(let s of i)s.pathKey===o&&(n=!0,Fn(r,s.constraints))}if(n)return r.cardinality=r.maxCount===1?"single":"list",r.required=(r.minCount??0)>=1,r}var Wn=c=>c,Hn=new at("kanonak.org","core-rdf","Resource"),xe=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Gn(e);if(!a)return n;let i=$t(r);for(let s of r){if(!(s instanceof d)||s.namespace!==a||!y.isClassType(Wn(s)))continue;let p=A(s);if(!p)continue;let l=Y(r,p),m=K(p),f=new Set(l.map(E=>K(E)));f.delete(m),f.delete(K(Hn));let R=new Map;for(let E of pt(r,p)){if(!E.domains.some($=>f.has(K($))))continue;let j=R.get(E.uri.name);j?j.push(E):R.set(E.uri.name,[E])}for(let[E,N]of R){if(N.length<2)continue;let j=_=>Ot(i,l,_.uri)?.cardinality,$=new Set(N.map(_=>_.range?K(_.range):void 0).filter(_=>_!==void 0)),B=new Set(N.map(j).filter(_=>_!==void 0));$.size<=1&&B.size<=1||n.push(this.toError(s.name,E,N,j))}}return n}toError(e,t,o,n){let r=s=>{let p=`${s.uri.publisher}/${s.uri.package_}/${s.uri.name}`,l=s.range?`${s.range.publisher}/${s.range.package_}/${s.range.name}`:"no range",m=n(s);return`${p} (range ${l}${m?`, ${m}`:""})`},a=o.map(r).join("; "),i=new u;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=t,i.actualValue=a,i.message=`Class '${e}' inherits ${o.length} distinct properties named '${t}' with incompatible range or cardinality: ${a}. The generated interface would multiply-inherit '${t}' with conflicting types and could not compile.`,i.suggestion=`Disambiguate the diamond name-clash on '${t}':
59
+ \u2022 If the path is wrong, correct the tx.PropertyRead/tx.Traverse chain`,s}};function on(c,e){let t=O(c,e);return t?[t]:V(c,e).filter(o=>o instanceof v)}function nn(c,e){let t=[];for(let o of e)if(o instanceof v)t.push(o);else if(o instanceof I){let n=h(c,o.subject);n&&t.push(n)}return t}function rn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var qe="kanonak.org",an="core-shacl",w=c=>({publisher:qe,package_:an,name:c}),sn=w("NodeShape"),cn=w("PropertyShape"),pn=w("targetClass"),ln=w("property"),mn=w("path"),un=w("minCount"),fn=w("maxCount"),dn=w("datatype"),yn=w("class"),jt=w("in"),gn=w("pattern"),kn=w("flags"),hn=w("minLength"),Rn=w("maxLength"),Kn=w("minInclusive"),bn=w("maxInclusive"),Vn=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),ot=c=>c,Ue=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=En(e);if(!a)return n;let i=new Set;for(let s of r){if(!(s instanceof d)||s.namespace!==a||!P(s,sn))continue;let p=g(s,pn);p?this.resolvesToClass(r,p)||n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' sh:targetClass '${p.name}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",Z(p))):n.push(this.err(s.name,"targetClass","Error",`NodeShape '${s.name}' has no sh:targetClass; it constrains nothing.`,"Add sh:targetClass naming the class this shape applies to."));for(let l of V(s,ln)){let m;if(l instanceof v)m=l;else if(l instanceof I){let f=h(r,l.subject);f&&(m=f,i.add(K(l.subject)))}m&&this.checkPropertyShape(r,s.name,m,p??void 0,n)}}for(let s of r){if(!(s instanceof d)||s.namespace!==a||!P(s,cn))continue;let p=A(s);p&&i.has(K(p))||this.checkPropertyShape(r,s.name,s,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=g(o,mn);if(!a){r.push(this.err(t,"property.path","Error",`A PropertyShape on '${t}' has no sh:path; a PropertyShape must name the property it constrains.`,"Add sh:path naming a property."));return}let i=h(e,a),s=i?y.isAnyPropertyType(ot(i)):!1;s?n&&(L(e,n,a).ok||r.push(this.err(t,"property.path","Warning",`sh:path '${a.name}' is not in scope for sh:targetClass '${n.name}'; the constraint would never bind a value.`,`Constrain a property whose domain is '${n.name}', an ancestor, or rdfs.Resource.`,Z(a)))):r.push(this.err(t,"property.path","Error",`sh:path '${a.name}' on '${t}' does not resolve to a property.`,"Reference a defined or imported property.",Z(a)));let p=g(o,dn),l=g(o,yn);p&&l&&r.push(this.err(t,"property","Error",`A PropertyShape on '${t}' sets both sh:datatype and sh:class; a value is a literal or a node, not both.`,"Keep sh:datatype (literal values) or sh:class (node values), not both.")),p&&!this.resolvesToDatatype(e,p)&&r.push(this.err(t,"datatype","Error",`sh:datatype '${p.name}' on '${t}' does not resolve to a datatype.`,"Reference an xsd datatype or rdfs.Datatype.",Z(p))),l&&!this.resolvesToClass(e,l)&&r.push(this.err(t,"class","Error",`sh:class '${l.name}' on '${t}' does not resolve to a class.`,"Reference a defined or imported rdfs.Class.",Z(l)));let m=Oe(x(o,un)),f=Oe(x(o,fn));this.checkOrder(t,"minCount",m,"maxCount",f,r);let R=Oe(x(o,hn)),E=Oe(x(o,Rn));this.checkOrder(t,"minLength",R,"maxLength",E,r);let N=Oe(x(o,Kn)),j=Oe(x(o,bn));this.checkOrder(t,"minInclusive",N,"maxInclusive",j,r);let $=W(o,gn);if($!==void 0){let B=W(o,kn);try{new RegExp($,B)}catch{r.push(this.err(t,"pattern","Error",`sh:pattern on '${t}' is not a valid regular expression`+(B!==void 0?` (with flags '${B}')`:"")+`: ${$}`,"Provide a valid regular expression and flags.",$))}}if(J(o,jt)&&V(o,jt).length===0&&r.push(this.err(t,"in","Error",`sh:in on '${t}' is empty; an enumeration must list at least one permitted value.`,"List the permitted literal values, or remove sh:in.")),s&&n){let _=L(e,n,a).descriptor;_&&(($!==void 0||R!==void 0||E!==void 0)&&_.kind==="object"&&r.push(this.err(t,"pattern/minLength/maxLength","Warning",`String facets on '${t}' apply to '${a.name}', which is an object property; string facets constrain literal values.`,"Apply string facets to a datatype property, or use sh:class for node values.",Z(a))),(N!==void 0||j!==void 0)&&!this.isNumericDatatypeRange(_.range)&&r.push(this.err(t,"minInclusive/maxInclusive","Warning",`Numeric bounds on '${t}' apply to '${a.name}', whose range is not a numeric datatype.`,"Apply numeric bounds to a numeric datatype property.",Z(a))))}}checkOrder(e,t,o,n,r,a){o!==void 0&&r!==void 0&&o>r&&a.push(this.err(e,`${t}/${n}`,"Error",`${t} (${o}) exceeds ${n} (${r}) on '${e}'.`,`Set ${t} <= ${n}.`))}resolvesToClass(e,t){let o=h(e,t);return o?y.isClassType(ot(o)):!1}resolvesToDatatype(e,t){if(t.publisher===qe&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=h(e,t);return o?y.isDatatypeType(ot(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===qe&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===qe&&e.package_==="core-xsd"&&Vn.has(e.name)}err(e,t,o,n,r,a){let i=new u;return i.ruleType=this.ruleName,i.severity=o,i.entityName=e,i.propertyName=t,i.message=n,i.suggestion=r,a!==void 0&&(i.actualValue=a),i}};function Oe(c){return typeof c=="number"?c:void 0}function Z(c){return`${c.publisher}/${c.package_}/${c.name}`}function En(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var $t={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},vn=c=>c,Ae=class{ruleName="OwlOneOf";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Dn(e);if(!a)return n;for(let i of r){if(!(i instanceof d)||i.namespace!==a||!J(i,$t))continue;let s=V(i,$t);if(s.length===0){n.push(this.err(i.name,"Warning",`owl:oneOf on '${i.name}' is empty; a closed enumeration must list at least one individual.`,"List the individuals that make up the enumeration, or remove owl:oneOf."));continue}for(let p of s)if(p instanceof Me)n.push(this.err(i.name,"Error",`owl:oneOf member '${String(p.value)}' on '${i.name}' is not a named individual; a class enumeration is of individuals (a misspelled or unimported individual reads as a literal). For a closed set of literal VALUES, constrain a property with sh:in instead.`,"Reference a defined or imported individual, or move literal value sets to a property sh:in.",String(p.value)));else if(p instanceof I){let l=h(r,p.subject);l&&y.isSchemaDefinitionType(vn(l))&&n.push(this.err(i.name,"Error",`owl:oneOf member '${p.subject.name}' on '${i.name}' is a class/property/datatype, not an individual.`,"List named individuals (instances), not schema definitions.",`${p.subject.publisher}/${p.subject.package_}/${p.subject.name}`))}}return n}err(e,t,o,n,r){let a=new u;return a.ruleType=this.ruleName,a.severity=t,a.entityName=e,a.propertyName="oneOf",a.message=o,a.suggestion=n,r!==void 0&&(a.actualValue=r),a}};function Dn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var In="kanonak.org",Cn="core-shacl",T=c=>({publisher:In,package_:Cn,name:c}),Sn=T("NodeShape"),Pn=T("targetClass"),jn=T("property"),$n=T("path"),On=T("minCount"),Un=T("maxCount"),An=T("in"),wn=T("pattern"),xn=T("flags"),Tn=T("minLength"),Nn=T("maxLength"),_n=T("minInclusive"),Ln=T("maxInclusive"),Mn=T("message");function we(c){return typeof c=="number"?c:void 0}function Bn(c){let e={},t=we(x(c,On)),o=we(x(c,Un));t!==void 0&&(e.minCount=t),o!==void 0&&(e.maxCount=o);let n=we(x(c,Tn)),r=we(x(c,Nn));n!==void 0&&(e.minLength=n),r!==void 0&&(e.maxLength=r);let a=we(x(c,_n)),i=we(x(c,Ln));a!==void 0&&(e.minInclusive=a),i!==void 0&&(e.maxInclusive=i);let s=W(c,wn);if(s!==void 0){let m=W(c,xn);e.pattern=m!==void 0?{regex:s,flags:m}:{regex:s}}let p=V(c,An).filter(m=>m instanceof Me).map(m=>m.value);p.length>0&&(e.enumValues=p);let l=W(c,Mn);return l!==void 0&&(e.message=l),e}function Fn(c,e){let t=[];for(let o of V(e,jn))if(o instanceof v)t.push(o);else if(o instanceof I){let n=h(c,o.subject);n&&t.push(n)}return t}function Ot(c){let e=new Map;for(let t of c){if(!(t instanceof d)||!P(t,Sn))continue;let o=g(t,Pn);if(!o)continue;let n=K(o);for(let r of Fn(c,t)){let a=g(r,$n);if(!a)continue;let i={pathKey:K(a),constraints:Bn(r)},s=e.get(n);s?s.push(i):e.set(n,[i])}}return e}function Wn(c,e){e.minCount!==void 0&&(c.minCount=e.minCount),e.maxCount!==void 0&&(c.maxCount=e.maxCount),e.minLength!==void 0&&(c.minLength=e.minLength),e.maxLength!==void 0&&(c.maxLength=e.maxLength),e.minInclusive!==void 0&&(c.minInclusive=e.minInclusive),e.maxInclusive!==void 0&&(c.maxInclusive=e.maxInclusive),e.pattern!==void 0&&(c.pattern=e.pattern),e.enumValues!==void 0&&(c.enumValues=e.enumValues),e.message!==void 0&&(c.message=e.message)}function Ut(c,e,t){let o=K(t),n=!1,r={};for(let a=e.length-1;a>=0;a--){let i=c.get(K(e[a]));if(i)for(let s of i)s.pathKey===o&&(n=!0,Wn(r,s.constraints))}if(n)return r.cardinality=r.maxCount===1?"single":"list",r.required=(r.minCount??0)>=1,r}var Hn=c=>c,Gn=new at("kanonak.org","core-rdf","Resource"),xe=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Yn(e);if(!a)return n;let i=Ot(r);for(let s of r){if(!(s instanceof d)||s.namespace!==a||!y.isClassType(Hn(s)))continue;let p=A(s);if(!p)continue;let l=Y(r,p),m=K(p),f=new Set(l.map(E=>K(E)));f.delete(m),f.delete(K(Gn));let R=new Map;for(let E of pt(r,p)){if(!E.domains.some($=>f.has(K($))))continue;let j=R.get(E.uri.name);j?j.push(E):R.set(E.uri.name,[E])}for(let[E,N]of R){if(N.length<2)continue;let j=_=>Ut(i,l,_.uri)?.cardinality,$=new Set(N.map(_=>_.range?K(_.range):void 0).filter(_=>_!==void 0)),B=new Set(N.map(j).filter(_=>_!==void 0));$.size<=1&&B.size<=1||n.push(this.toError(s.name,E,N,j))}}return n}toError(e,t,o,n){let r=s=>{let p=`${s.uri.publisher}/${s.uri.package_}/${s.uri.name}`,l=s.range?`${s.range.publisher}/${s.range.package_}/${s.range.name}`:"no range",m=n(s);return`${p} (range ${l}${m?`, ${m}`:""})`},a=o.map(r).join("; "),i=new u;return i.ruleType=this.ruleName,i.severity="Error",i.entityName=e,i.propertyName=t,i.actualValue=a,i.message=`Class '${e}' inherits ${o.length} distinct properties named '${t}' with incompatible range or cardinality: ${a}. The generated interface would multiply-inherit '${t}' with conflicting types and could not compile.`,i.suggestion=`Disambiguate the diamond name-clash on '${t}':
60
60
  \u2022 rename one of the properties, or
61
61
  \u2022 re-domain one so it is not inherited by '${e}', or
62
62
  \u2022 restructure the hierarchy so '${e}' inherits only one '${t}', or
63
- \u2022 make the ranges/cardinalities compatible (identical) if they are meant to be the same property.`,i}};function Gn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var nt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new rt,this.documentRules=[new ne,new re,new ae,new ie,new se],this.repositoryRules=[new ce,new pe,new le,new me,new ue,new fe,new de,new ye,new ge,new ke,new he,new Re,new be,new Ve,new Ee,new ve,new De,new Ie,new Ce,new Se,new Le,new Pe,new Ue,new Ae,new xe]}async validateAsync(e,t,o){let n=new Q;for(let r of this.documentRules)try{let a=r.validate(e);this.addErrorsToResult(n,a)}catch(a){let i=new u;i.ruleType=r.ruleName,i.severity="Error",i.message=`Validation rule '${r.ruleName}' failed: ${a instanceof Error?a.message:String(a)}`,n.errors.push(i)}if(t){let r=[],a=o??new ee(new te(e,t)),i=a.repository;for(let s of this.repositoryRules)try{let p=await s.validateAsync(e,i,a);this.addErrorsToResult(n,p)}catch(p){let l=p instanceof Error?p.message:String(p);r.push({ruleName:s.ruleName,cause:l})}if(r.length>0){let s=new Map;for(let{ruleName:p,cause:l}of r){let m=s.get(l);m?m.push(p):s.set(l,[p])}for(let[p,l]of s){let m=new u;m.ruleType=l[0],m.severity="Error",l.length===1?m.message=`Validation rule '${l[0]}' failed: ${p}`:m.message=`${p} (affects ${l.length} rules: ${l.join(", ")})`,n.errors.push(m)}}}return n.isValid=n.errors.length===0,n}async validateDocumentsAsync(e,t){let o=new ee(t),n=[];for(let r of e){let a=await this.validateAsync(r,o.repository,o);n.push({document:r,result:a})}return n}async validateYamlAsync(e,t,o){let n=this.parser.parseWithErrors(e);if(!n.isValid){let r=new Q;r.isValid=!1;for(let a of n.errors){let i=new u;i.ruleType="ParseError",i.severity="Error",i.lineNumber=a.line,i.column=a.column,i.message=a.message,a.keyName&&(i.entityName=a.keyName),a.errorType==="DuplicateKey"&&(i.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),r.errors.push(i)}return r}return await this.validateAsync(n.document,t,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(o=>o instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(o=>o instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let o of t)o.severity==="Error"?e.errors.push(o):o.severity==="Info"?this.includeWarnings&&e.infos.push(o):this.includeWarnings&&e.warnings.push(o)}};export{Q as a,k as b,u as c,ze as d,ee as e,ne as f,re as g,ae as h,ie as i,se as j,ce as k,pe as l,le as m,me as n,ue as o,fe as p,de as q,ye as r,ge as s,ke as t,he as u,Re as v,be as w,Ve as x,Ee as y,ve as z,De as A,Ie as B,Ce as C,Se as D,Pe as E,Ue as F,Ae as G,$t as H,Ot as I,xe as J,nt as K};
63
+ \u2022 make the ranges/cardinalities compatible (identical) if they are meant to be the same property.`,i}};function Yn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var nt=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new rt,this.documentRules=[new ne,new re,new ae,new ie,new se],this.repositoryRules=[new ce,new pe,new le,new me,new ue,new fe,new de,new ye,new ge,new ke,new he,new Re,new be,new Ve,new Ee,new ve,new De,new Ie,new Ce,new Se,new Le,new Pe,new Ue,new Ae,new xe]}async validateAsync(e,t,o){let n=new Q;for(let r of this.documentRules)try{let a=r.validate(e);this.addErrorsToResult(n,a)}catch(a){let i=new u;i.ruleType=r.ruleName,i.severity="Error",i.message=`Validation rule '${r.ruleName}' failed: ${a instanceof Error?a.message:String(a)}`,n.errors.push(i)}if(t){let r=[],a=o??new ee(new te(e,t)),i=a.repository;for(let s of this.repositoryRules)try{let p=await s.validateAsync(e,i,a);this.addErrorsToResult(n,p)}catch(p){let l=p instanceof Error?p.message:String(p);r.push({ruleName:s.ruleName,cause:l})}if(r.length>0){let s=new Map;for(let{ruleName:p,cause:l}of r){let m=s.get(l);m?m.push(p):s.set(l,[p])}for(let[p,l]of s){let m=new u;m.ruleType=l[0],m.severity="Error",l.length===1?m.message=`Validation rule '${l[0]}' failed: ${p}`:m.message=`${p} (affects ${l.length} rules: ${l.join(", ")})`,n.errors.push(m)}}}return n.isValid=n.errors.length===0,n}async validateDocumentsAsync(e,t){let o=new ee(t),n=[];for(let r of e){let a=await this.validateAsync(r,o.repository,o);n.push({document:r,result:a})}return n}async validateYamlAsync(e,t,o){let n=this.parser.parseWithErrors(e);if(!n.isValid){let r=new Q;r.isValid=!1;for(let a of n.errors){let i=new u;i.ruleType="ParseError",i.severity="Error",i.lineNumber=a.line,i.column=a.column,i.message=a.message,a.keyName&&(i.entityName=a.keyName),a.errorType==="DuplicateKey"&&(i.suggestion="All property names must be unique across the entire document. Rename one of the duplicate properties to make them unique."),r.errors.push(i)}return r}return await this.validateAsync(n.document,t,o)}addDocumentRule(e){this.documentRules.push(e)}addRepositoryRule(e){this.repositoryRules.push(e)}removeDocumentRule(e){let t=this.documentRules.findIndex(o=>o instanceof e);t>=0&&this.documentRules.splice(t,1)}removeRepositoryRule(e){let t=this.repositoryRules.findIndex(o=>o instanceof e);t>=0&&this.repositoryRules.splice(t,1)}addErrorsToResult(e,t){for(let o of t)o.severity==="Error"?e.errors.push(o):o.severity==="Info"?this.includeWarnings&&e.infos.push(o):this.includeWarnings&&e.warnings.push(o)}};export{Q as a,k as b,u as c,ze as d,ee as e,ne as f,re as g,ae as h,ie as i,se as j,ce as k,pe as l,le as m,me as n,ue as o,fe as p,de as q,ye as r,ge as s,ke as t,he as u,Re as v,be as w,Ve as x,Ee as y,ve as z,De as A,Ie as B,Ce as C,Se as D,Pe as E,Ue as F,Ae as G,Ot as H,Ut as I,xe as J,nt as K};
@@ -0,0 +1 @@
1
+ import{e as u}from"./chunk-2ACBWC7K.js";function g(t){let n=t.metadata?.namespace_;return n?`${n.publisher}/${n.package_}`:void 0}function d(t){let n=t.metadata?.namespace_;if(n)return n.version?`${n.publisher}/${n.package_}@${u(n.version)}`:`${n.publisher}/${n.package_}`}async function h(t,n){let e=new Set,s=new Set,o=[...t];for(;o.length>0;){let r=o.shift(),c=g(r),i=d(r);if(!c||!i||s.has(i))continue;s.add(i),e.add(c);let a=r.metadata?.imports;if(a)for(let[p,y]of Object.entries(a))for(let D of y)try{let m=await n.getHighestCompatibleVersionAsync(p,D);m&&o.push(m)}catch{}}return e}var l=class{constructor(n,e){this.inner=n;this.scope=e}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(e=>{let s=g(e);return s!==void 0&&this.scope.has(s)})}getDocumentAsync(n){return this.inner.getDocumentAsync(n)}getDocumentsByNamespaceAsync(n,e){return this.inner.getDocumentsByNamespaceAsync(n,e)}getHighestCompatibleVersionAsync(n,e){return this.inner.getHighestCompatibleVersionAsync(n,e)}saveDocumentAsync(n,e){return this.inner.saveDocumentAsync(n,e)}deleteDocumentAsync(n){return this.inner.deleteDocumentAsync(n)}clearNamespaceAsync(n,e){return this.inner.clearNamespaceAsync(n,e)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(n){return this.inner.getDocumentContentAsync(n)}getDocumentUriAsync(n){return this.inner.getDocumentUriAsync(n)}};export{h as a,l as b};
@@ -1,2 +1,2 @@
1
- import{H as W,I as X}from"./chunk-FPUQEPYK.js";import{b as B,c as V,l as N}from"./chunk-MX3DEXMV.js";import{a as b,d as K,e as q,f as z}from"./chunk-ZP6P7HNU.js";import{c as G,d as x,m as w,r as E,t as F,v as D,w as Y,y as v}from"./chunk-7BHDZHJY.js";import{a as L}from"./chunk-FUUTGGJS.js";import{d as U}from"./chunk-2ACBWC7K.js";var Q=(t=>(t.Class="Class",t.DatatypeProperty="DatatypeProperty",t.ObjectProperty="ObjectProperty",t.AnnotationProperty="AnnotationProperty",t.Instance="Instance",t.Datatype="Datatype",t.Unknown="Unknown",t))(Q||{}),Z=(p=>(p.InstanceOf="instanceOf",p.SubClassOf="subClassOf",p.Domain="domain",p.Range="range",p.ObjectRelationship="objectRelationship",p.SubPropertyOf="subPropertyOf",p.PropertyValue="propertyValue",p.EmbeddedLink="embeddedLink",p))(Z||{}),I=class{static async buildFromRepository(e){let a=await new N().parseKanonaks(e),o=await e.getAllDocumentsAsync(),s=[],i=[],t=new Set,p=new Set,g=new Map;for(let u of a){let l=u;l.name&&(b.isClassType(l)&&t.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&p.add(l.name))}for(let u of o)for(let[l,f]of Object.entries(u.body))p.has(l)&&f?.range&&typeof f.range=="string"&&g.set(l,f.range);let y=new Map;for(let u of a){let l=u;l.name&&y.set(l.name,l)}for(let u of o){let l=u.metadata.namespace_,f=l?`${l.publisher}/${l.package_}`:"",c=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",d=H(u);for(let[k,m]of Object.entries(u.body)){if(!m||typeof m!="object")continue;let P=y.get(k),h="Unknown";if(P){let T=P;b.isClassType(T)?h="Class":b.isObjectPropertyType(T)?h="ObjectProperty":b.isDatatypePropertyType(T)?h="DatatypeProperty":b.isAnnotationPropertyType(T)?h="AnnotationProperty":b.isDatatypeType(T)?h="Datatype":b.isGenericPropertyType(T)?h="ObjectProperty":b.isInstanceOfKnownClass(T,t)&&(h="Instance")}let j=f&&c?`${f}/${k}@${c}`:k,A={};for(let[T,$]of Object.entries(m))T!=="type"&&(typeof $!="object"||$===null)&&(A[T]=$);s.push({id:j,label:m.label??k,type:h,namespace:f,properties:A}),J(j,m,h,t,p,i,f,c,d),_(j,m,p,g,s,i,f,c,d),ue(j,P,i)}}return{nodes:s,edges:i}}static buildFromDocument(e){let r=[],a=[],o=e.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",i=o?`${o.publisher}/${o.package_}`:"",t=new Set,p=new Set,g=new Map,y=H(e);for(let[f,c]of Object.entries(e.body)){let d=c?.type;d&&(pe(d,y)&&t.add(f),ce(d,y)&&(p.add(f),c.range&&typeof c.range=="string"&&g.set(f,c.range)))}for(let[f,c]of Object.entries(e.body)){if(!c||typeof c!="object")continue;let d=c.type,k=le(d,f,t,y),m=i&&s?`${i}/${f}@${s}`:f,P={};for(let[h,j]of Object.entries(c))h!=="type"&&(typeof j!="object"||j===null)&&(P[h]=j);r.push({id:m,label:c.label??f,type:k,namespace:i,properties:P}),J(m,c,k,t,p,a,i,s,y),_(m,c,p,g,r,a,i,s,y)}let u=new Set(r.map(f=>f.id)),l=a.filter(f=>u.has(f.source)&&u.has(f.target));return{nodes:r,edges:l}}};function H(n,e){let r=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let s of o){let i=s.alias??s.packageName,t=s.version,p=`${t.major}.${t.minor}.${t.patch}`;r.set(i,{publisher:a,package_:s.packageName,version:p})}return r}var ee={"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"},ie=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function M(n,e){if(n.includes(".")){let r=n.indexOf("."),a=n.substring(0,r),o=n.substring(r+1),s=e.get(a);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function pe(n,e){let r=M(n,e);return r?ee[r]==="Class":!1}function ce(n,e){let r=M(n,e);return r?ie.has(r):!1}function le(n,e,r,a){if(!n||n==="Package")return"Unknown";let o=M(n,a);if(o){let i=ee[o];if(i)return i;let t=o.split("/").pop()?.split("@")[0]??"";return r.has(t)?"Instance":"Unknown"}let s=n.split(".").pop()??n;return r.has(s)?"Instance":"Unknown"}var ne=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function J(n,e,r,a,o,s,i,t,p){let g=e.type,y=e.subClassOf;if(y){let c=Array.isArray(y)?y:[y];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let c=Array.isArray(u)?u:[u];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subPropertyOf",label:"subPropertyOf"})}if(r==="Instance"&&g){let c=g.split(".").pop()??g;s.push({source:n,target:O(c,i,t,p),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[c,d]of Object.entries(e)){if(ne.has(c)||!o.has(c))continue;let k=Array.isArray(d)?d:[d];for(let m of k)typeof m=="string"&&fe(m)&&s.push({source:n,target:O(m,i,t,p),type:"propertyValue",label:c,propertyId:O(c,i,t,p)})}let l=r==="ObjectProperty"||r==="DatatypeProperty",f=e.domain&&e.range;if((l||f)&&e.domain&&e.range){let c=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;c&&d&&s.push({source:O(c,i,t,p),target:O(d,i,t,p),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function _(n,e,r,a,o,s,i,t,p){for(let[g,y]of Object.entries(e)){if(ne.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let u=y,l=`${n}/${g}`,f=a.get(g),c=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,P]of Object.entries(u))(typeof P!="object"||P===null)&&(d[m]=P);o.push({id:l,label:`${c} (embedded)`,type:"Instance",namespace:i,properties:d});let k=i&&t?`${i}/${g}@${t}`:g;s.push({source:n,target:l,type:"propertyValue",label:g,propertyId:r.has(g)?k:void 0}),f&&s.push({source:l,target:O(c,i,t,p),type:"instanceOf",label:"type (inferred)"}),_(l,u,r,a,o,s,i,t,p)}}function ue(n,e,r){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof V))continue;let s=o.predicate?.subject?.name??"";for(let i of o.links){let t=i.target?.subject;if(!t)continue;let p=t.version,g=p&&typeof p.major=="number"?`@${p.major}.${p.minor}.${p.patch}`:"";r.push({source:n,target:`${t.publisher}/${t.package_}/${t.name}${g}`,type:"embeddedLink",label:s})}}}function fe(n){return!(!n||n.includes(" ")||n.includes(`
1
+ import{H as W,I as X}from"./chunk-7K5TAJ44.js";import{b as B,c as V,l as N}from"./chunk-MX3DEXMV.js";import{a as b,d as K,e as q,f as z}from"./chunk-ZP6P7HNU.js";import{c as G,d as x,m as w,r as E,t as F,v as D,w as Y,y as v}from"./chunk-7BHDZHJY.js";import{a as L}from"./chunk-FUUTGGJS.js";import{d as U}from"./chunk-2ACBWC7K.js";var Q=(t=>(t.Class="Class",t.DatatypeProperty="DatatypeProperty",t.ObjectProperty="ObjectProperty",t.AnnotationProperty="AnnotationProperty",t.Instance="Instance",t.Datatype="Datatype",t.Unknown="Unknown",t))(Q||{}),Z=(p=>(p.InstanceOf="instanceOf",p.SubClassOf="subClassOf",p.Domain="domain",p.Range="range",p.ObjectRelationship="objectRelationship",p.SubPropertyOf="subPropertyOf",p.PropertyValue="propertyValue",p.EmbeddedLink="embeddedLink",p))(Z||{}),I=class{static async buildFromRepository(e){let a=await new N().parseKanonaks(e),o=await e.getAllDocumentsAsync(),s=[],i=[],t=new Set,p=new Set,g=new Map;for(let u of a){let l=u;l.name&&(b.isClassType(l)&&t.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&p.add(l.name))}for(let u of o)for(let[l,f]of Object.entries(u.body))p.has(l)&&f?.range&&typeof f.range=="string"&&g.set(l,f.range);let y=new Map;for(let u of a){let l=u;l.name&&y.set(l.name,l)}for(let u of o){let l=u.metadata.namespace_,f=l?`${l.publisher}/${l.package_}`:"",c=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",d=H(u);for(let[k,m]of Object.entries(u.body)){if(!m||typeof m!="object")continue;let P=y.get(k),h="Unknown";if(P){let T=P;b.isClassType(T)?h="Class":b.isObjectPropertyType(T)?h="ObjectProperty":b.isDatatypePropertyType(T)?h="DatatypeProperty":b.isAnnotationPropertyType(T)?h="AnnotationProperty":b.isDatatypeType(T)?h="Datatype":b.isGenericPropertyType(T)?h="ObjectProperty":b.isInstanceOfKnownClass(T,t)&&(h="Instance")}let j=f&&c?`${f}/${k}@${c}`:k,A={};for(let[T,$]of Object.entries(m))T!=="type"&&(typeof $!="object"||$===null)&&(A[T]=$);s.push({id:j,label:m.label??k,type:h,namespace:f,properties:A}),J(j,m,h,t,p,i,f,c,d),_(j,m,p,g,s,i,f,c,d),ue(j,P,i)}}return{nodes:s,edges:i}}static buildFromDocument(e){let r=[],a=[],o=e.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",i=o?`${o.publisher}/${o.package_}`:"",t=new Set,p=new Set,g=new Map,y=H(e);for(let[f,c]of Object.entries(e.body)){let d=c?.type;d&&(pe(d,y)&&t.add(f),ce(d,y)&&(p.add(f),c.range&&typeof c.range=="string"&&g.set(f,c.range)))}for(let[f,c]of Object.entries(e.body)){if(!c||typeof c!="object")continue;let d=c.type,k=le(d,f,t,y),m=i&&s?`${i}/${f}@${s}`:f,P={};for(let[h,j]of Object.entries(c))h!=="type"&&(typeof j!="object"||j===null)&&(P[h]=j);r.push({id:m,label:c.label??f,type:k,namespace:i,properties:P}),J(m,c,k,t,p,a,i,s,y),_(m,c,p,g,r,a,i,s,y)}let u=new Set(r.map(f=>f.id)),l=a.filter(f=>u.has(f.source)&&u.has(f.target));return{nodes:r,edges:l}}};function H(n,e){let r=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let s of o){let i=s.alias??s.packageName,t=s.version,p=`${t.major}.${t.minor}.${t.patch}`;r.set(i,{publisher:a,package_:s.packageName,version:p})}return r}var ee={"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"},ie=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function M(n,e){if(n.includes(".")){let r=n.indexOf("."),a=n.substring(0,r),o=n.substring(r+1),s=e.get(a);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function pe(n,e){let r=M(n,e);return r?ee[r]==="Class":!1}function ce(n,e){let r=M(n,e);return r?ie.has(r):!1}function le(n,e,r,a){if(!n||n==="Package")return"Unknown";let o=M(n,a);if(o){let i=ee[o];if(i)return i;let t=o.split("/").pop()?.split("@")[0]??"";return r.has(t)?"Instance":"Unknown"}let s=n.split(".").pop()??n;return r.has(s)?"Instance":"Unknown"}var ne=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function J(n,e,r,a,o,s,i,t,p){let g=e.type,y=e.subClassOf;if(y){let c=Array.isArray(y)?y:[y];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let c=Array.isArray(u)?u:[u];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subPropertyOf",label:"subPropertyOf"})}if(r==="Instance"&&g){let c=g.split(".").pop()??g;s.push({source:n,target:O(c,i,t,p),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[c,d]of Object.entries(e)){if(ne.has(c)||!o.has(c))continue;let k=Array.isArray(d)?d:[d];for(let m of k)typeof m=="string"&&fe(m)&&s.push({source:n,target:O(m,i,t,p),type:"propertyValue",label:c,propertyId:O(c,i,t,p)})}let l=r==="ObjectProperty"||r==="DatatypeProperty",f=e.domain&&e.range;if((l||f)&&e.domain&&e.range){let c=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;c&&d&&s.push({source:O(c,i,t,p),target:O(d,i,t,p),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function _(n,e,r,a,o,s,i,t,p){for(let[g,y]of Object.entries(e)){if(ne.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let u=y,l=`${n}/${g}`,f=a.get(g),c=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,P]of Object.entries(u))(typeof P!="object"||P===null)&&(d[m]=P);o.push({id:l,label:`${c} (embedded)`,type:"Instance",namespace:i,properties:d});let k=i&&t?`${i}/${g}@${t}`:g;s.push({source:n,target:l,type:"propertyValue",label:g,propertyId:r.has(g)?k:void 0}),f&&s.push({source:l,target:O(c,i,t,p),type:"instanceOf",label:"type (inferred)"}),_(l,u,r,a,o,s,i,t,p)}}function ue(n,e,r){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof V))continue;let s=o.predicate?.subject?.name??"";for(let i of o.links){let t=i.target?.subject;if(!t)continue;let p=t.version,g=p&&typeof p.major=="number"?`@${p.major}.${p.minor}.${p.patch}`:"";r.push({source:n,target:`${t.publisher}/${t.package_}/${t.name}${g}`,type:"embeddedLink",label:s})}}}function fe(n){return!(!n||n.includes(" ")||n.includes(`
2
2
  `)||n.startsWith("http://")||n.startsWith("https://")||/^\d{4}-\d{2}/.test(n)||/^\d+(\.\d+)?$/.test(n))}function O(n,e,r,a){if(n.includes("@")&&n.includes("/"))return n;if(n.includes(".")){let o=n.indexOf("."),s=n.substring(0,o),i=n.substring(o+1);if(a){let t=a.get(s);if(t)return`${t.publisher}/${t.package_}/${i}@${t.version}`}return e&&r?`${e}/${i}@${r}`:i}return e&&r?`${e}/${n}@${r}`:n}function de(n){if(!n.expiresAt)return!1;let e=new Date(n.expiresAt),r=300*1e3;return e.getTime()<=Date.now()+r}function Se(n){return!!n.accessToken&&!de(n)}function Re(n){let e=n.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}var C="kanonak.org",R="core-rdf",re="core-xsd",te={publisher:C,package_:R,name:"subClassOf"},oe={publisher:C,package_:R,name:"label"},ye={publisher:C,package_:R,name:"comment"},se={publisher:C,package_:"core-owl",name:"oneOf"},ae=n=>n;function ge(n){let e=Y(n,te);if(e)return[e];let r=[];for(let a of v(n,te))a instanceof x&&r.push(a.subject);return r}function me(n,e,r){if(e.publisher===C&&e.package_===R&&e.name==="Literal")return{kind:"datatype",uri:e};let o=E(n,e);if(o){let s=ae(o);if(b.isDatatypeType(s))return{kind:"datatype",uri:e};if(b.isClassType(s))return{kind:"class",uri:K(o)??e,localName:o.name}}return e.publisher===C&&e.package_===re?{kind:"datatype",uri:e}:r==="datatype"?{kind:"datatype",uri:e}:{kind:"class",uri:e,localName:e.name}}function be(n,e,r){if(!e.range)throw new Error(`Property ${e.uri.publisher}/${e.uri.package_}/${e.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let a=me(n,e.range,e.kind),o=e.kind==="object"?"object":e.kind==="datatype"?"datatype":a.kind==="class"?"object":"datatype";return{uri:e.uri,localName:e.uri.name,kind:o,range:a,...e.label!==void 0?{label:e.label}:{},...e.comment!==void 0?{comment:e.comment}:{},...r??{}}}var S=n=>new L(C,re,n);function ke(n){return typeof n=="boolean"?S("boolean"):typeof n=="number"?Number.isInteger(n)?S("integer"):S("decimal"):S("string")}function he(n,e){let r=[];for(let a of v(e,se))if(a instanceof x){let o=E(n,a.subject),s=(o?K(o):void 0)??a.subject,i=o?D(o,oe):void 0;r.push({kind:"individual",uri:s,localName:s.name,...i!==void 0?{label:i}:{}})}else a instanceof B&&r.push({kind:"literal",value:a.value,datatype:ke(a.value)});return r}function Pe(n,e,r,a){let o=q(n,e),s=w(e);return z(n,e).filter(t=>r?!0:t.domains.some(p=>w(p)===s)).map(t=>be(n,t,X(a,o,t.uri)))}async function Te(n,e,r){let a=n.metadata?.namespace_;if(!a)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=r?.includeInherited??!1,s=await new N().parseKanonaks(e),i=W(s),t=[],p=[],g=new Set;for(let y of s){if(!(y instanceof G)||!b.isClassType(ae(y)))continue;let u=K(y);if(!u||u.publisher!==a.publisher||u.package_!==a.package_||u.version&&a.version&&!U(u.version,a.version))continue;let l=w(u);if(g.has(l))continue;g.add(l);let f=ge(y).map(k=>({uri:k,localName:k.name})),c=D(y,oe),d=D(y,ye);t.push({uri:u,localName:u.name,superClasses:f,properties:Pe(s,u,o,i),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}}),F(y,se)&&p.push({uri:u,localName:u.name,members:he(s,y),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}})}return{classes:t,enums:p}}export{Q as a,Z as b,I as c,de as d,Se as e,Re as f,Te as g};
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import{a as _r,b as Nr,c as jr,d as Or,e as Ie}from"./chunk-TVSHIXLA.js";import{a as An,c as De,e as Ye,h as Ze,i as Qe,j as In}from"./chunk-IHB7UVEH.js";import{a as Dr,b as $r,c as Tr,d as Q,e as ee,f as l,g as Kn}from"./chunk-EBH5WSSY.js";import{a as xn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as rr,b as nr,c as or,d as ir,e as sr,f as fr,g as yr,h as hr,i as gr}from"./chunk-GMEPM2QQ.js";import{a as ar,b as cr,c as lr,d as I,f as pr,g as dr,h as mr}from"./chunk-JYBKSBB5.js";import{a as tr}from"./chunk-4NO7MHS7.js";import{a as Mr,b as Vr,c as Lr,d as Ur}from"./chunk-S6VSAKXB.js";import{a as Fr,b as Xr}from"./chunk-PEUTCG3B.js";import{a as zr}from"./chunk-PEJALHXK.js";import{a as ur}from"./chunk-SC5M74NM.js";import{A as Rn,B as En,K as Cn,a as Yr,b as Zr,c as Qr,d as en,e as tn,f as rn,g as nn,h as on,i as sn,j as an,k as cn,l as ln,m as pn,n as dn,o as un,p as mn,q as fn,r as yn,s as hn,t as gn,u as kn,v as Sn,w as wn,x as bn,y as Pn,z as vn}from"./chunk-FPUQEPYK.js";import{a as P,b as Se,c as br,h as Z,i as qe,j as Ar,k as Ir,l as U}from"./chunk-MX3DEXMV.js";import{a as M}from"./chunk-NJ3AZYQD.js";import{a as Kr,b as Ke,c as Hr,d as v,e as Wr,f as Gr,g as Jr,h as qr}from"./chunk-ZP6P7HNU.js";import{a as Xe}from"./chunk-6U26UASC.js";import{a as Pr,b as vr,c as L,d as Rr,e as Er,g as Cr,k as xr}from"./chunk-GZPLWII7.js";import{a as kr,b as ke,c as b,d as C,e as wr,f as we,g as be,h as Pe,i as ve,j as Re,k as Ee,l as Ce,r as Y,w as V,x as xe,y as Ae}from"./chunk-7BHDZHJY.js";import{a as Sr}from"./chunk-FUUTGGJS.js";import{a as Jt,b as ge,c as X,d as qt,e as E,f as Xt,g as Yt,h as Zt,i as Qt,j as er}from"./chunk-2ACBWC7K.js";import{a as Br}from"./chunk-ODIECDN7.js";import{VersionOperator as Oa}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Zn,readFileSync as Qn}from"fs";import{homedir as eo}from"os";import{join as to}from"path";import{execFile as Dn}from"child_process";import{promisify as $n}from"util";var te=$n(Dn),Tn="kanonak",re="/usr/bin/security",m=class{constructor(e=Tn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await te(re,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
1
+ import{a as _r,b as Nr,c as Or,d as jr,e as Ie}from"./chunk-TVSHIXLA.js";import{a as An,c as Ke,e as Ye,h as Ze,i as Qe,j as In}from"./chunk-IHB7UVEH.js";import{a as Kr,b as $r,c as Tr,d as Q,e as ee,f as l,g as Dn}from"./chunk-S5URV3V7.js";import{a as xn}from"./chunk-EZSHR3CB.js";import"./chunk-QHABFCRC.js";import{a as rr,b as nr,c as or,d as ir,e as sr,f as fr,g as yr,h as hr,i as gr}from"./chunk-GMEPM2QQ.js";import{a as ar,b as cr,c as lr,d as D,f as dr,g as pr,h as mr}from"./chunk-JYBKSBB5.js";import{a as tr}from"./chunk-4NO7MHS7.js";import{a as Mr,b as Vr,c as Lr,d as Fr}from"./chunk-S6VSAKXB.js";import{a as Ur,b as Xr}from"./chunk-PEUTCG3B.js";import{a as zr}from"./chunk-PEJALHXK.js";import{a as ur}from"./chunk-SC5M74NM.js";import{A as Rn,B as En,K as Cn,a as Yr,b as Zr,c as Qr,d as en,e as tn,f as rn,g as nn,h as on,i as sn,j as an,k as cn,l as ln,m as dn,n as pn,o as un,p as mn,q as fn,r as yn,s as hn,t as gn,u as kn,v as Sn,w as wn,x as vn,y as bn,z as Pn}from"./chunk-7K5TAJ44.js";import"./chunk-ITKOKDBG.js";import{a as b,b as Se,c as vr,h as Z,i as qe,j as Ar,k as Ir,l as F}from"./chunk-MX3DEXMV.js";import{a as M}from"./chunk-NJ3AZYQD.js";import{a as Dr,b as De,c as Hr,d as P,e as Wr,f as Gr,g as Jr,h as qr}from"./chunk-ZP6P7HNU.js";import{a as Xe}from"./chunk-6U26UASC.js";import{a as br,b as Pr,c as L,d as Rr,e as Er,g as Cr,k as xr}from"./chunk-GZPLWII7.js";import{a as kr,b as ke,c as v,d as x,e as wr,f as we,g as ve,h as be,i as Pe,j as Re,k as Ee,l as Ce,r as Y,w as V,x as xe,y as Ae}from"./chunk-7BHDZHJY.js";import{a as Sr}from"./chunk-FUUTGGJS.js";import{a as Jt,b as ge,c as X,d as qt,e as C,f as Xt,g as Yt,h as Zt,i as Qt,j as er}from"./chunk-2ACBWC7K.js";import{a as Br}from"./chunk-ODIECDN7.js";import{VersionOperator as Ma}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Zn,readFileSync as Qn}from"fs";import{homedir as eo}from"os";import{join as to}from"path";import{execFile as Kn}from"child_process";import{promisify as $n}from"util";var te=$n(Kn),Tn="kanonak",re="/usr/bin/security",m=class{constructor(e=Tn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await te(re,["find-generic-password","-s",this.service,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
2
2
  Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(et(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${ne(n)}
3
3
  The Keychain may be locked or inaccessible.
4
4
  Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=l(e),o=JSON.stringify(t);try{await te(re,["add-generic-password","-s",this.service,"-a",n,"-U","-w",o],{timeout:1e4})}catch(i){throw new Error(`macOS Keychain write failed for '${n}': ${ne(i)}
5
5
  Ensure the Keychain is unlocked and the CLI has write permission.
6
6
  On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await te(re,["delete-generic-password","-s",this.service,"-a",t],{timeout:1e4})}catch(n){if(et(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${ne(n)}
7
7
  The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await te(re,["dump-keychain"],{timeout:1e4}),t=[],n=!1;for(let o of e.split(`
8
- `))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${ne(e)}`),[]}}};function et(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function ne(r){return r instanceof Error?r.message:String(r)}import{execFile as _n}from"child_process";import{promisify as Nn}from"util";var jn=Nn(_n),On="kanonak:",tt=2560,f=class{constructor(e=On){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+l(e),n=`
8
+ `))if(o.includes(`"svce"<blob>="${this.service}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let i=o.match(/"acct"<blob>="([^"]+)"/);i&&t.push(i[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${ne(e)}`),[]}}};function et(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function ne(r){return r instanceof Error?r.message:String(r)}import{execFile as _n}from"child_process";import{promisify as Nn}from"util";var On=Nn(_n),jn="kanonak:",tt=2560,f=class{constructor(e=jn){this.targetPrefix=e}targetPrefix;async get(e){let t=this.targetPrefix+l(e),n=`
9
9
  ${ie}
10
10
  $target = $env:KANONAK_CRED_TARGET
11
11
  $ptr = [IntPtr]::Zero
@@ -35,7 +35,7 @@ try {
35
35
  if (-not $result) { throw "CredWrite failed (Win32 error $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error()))" }
36
36
  } finally {
37
37
  [System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
38
- }`;try{await oe(s,{KANONAK_CRED_TARGET:n,KANONAK_CRED_JSON:o})}catch(a){let c=a,p=c.stderr&&c.stderr.trim()||c.message||String(a);throw new Error(`Windows Credential Manager write failed: ${p}`)}}async remove(e){let t=this.targetPrefix+l(e),n=`
38
+ }`;try{await oe(s,{KANONAK_CRED_TARGET:n,KANONAK_CRED_JSON:o})}catch(a){let c=a,d=c.stderr&&c.stderr.trim()||c.message||String(a);throw new Error(`Windows Credential Manager write failed: ${d}`)}}async remove(e){let t=this.targetPrefix+l(e),n=`
39
39
  ${ie}
40
40
  $target = $env:KANONAK_CRED_TARGET
41
41
  [CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await oe(n,{KANONAK_CRED_TARGET:t})}catch{}}async list(){let e=`
@@ -58,7 +58,7 @@ if ([CredMan]::CredEnumerate(($prefix + "*"), 0, [ref]$count, [ref]$pCreds)) {
58
58
  }
59
59
  [CredMan]::CredFree($pCreds)
60
60
  }`;try{let{stdout:t}=await oe(e,{KANONAK_CRED_PREFIX:this.targetPrefix});return t.trim().split(`
61
- `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function oe(r,e){let t=Buffer.from(r,"utf16le").toString("base64");for(let n of["pwsh","powershell"])try{return await jn(n,["-NoProfile","-NonInteractive","-EncodedCommand",t],{timeout:15e3,...e&&{env:{...process.env,...e}}})}catch(o){if(n==="powershell")throw o}throw new Error("Neither pwsh nor powershell found")}var ie=`
61
+ `).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function oe(r,e){let t=Buffer.from(r,"utf16le").toString("base64");for(let n of["pwsh","powershell"])try{return await On(n,["-NoProfile","-NonInteractive","-EncodedCommand",t],{timeout:15e3,...e&&{env:{...process.env,...e}}})}catch(o){if(n==="powershell")throw o}throw new Error("Neither pwsh nor powershell found")}var ie=`
62
62
  Add-Type -TypeDefinition @"
63
63
  using System;
64
64
  using System.Runtime.InteropServices;
@@ -89,15 +89,15 @@ public class CredMan {
89
89
  [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
90
90
  public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
91
91
  }
92
- "@`,Bn="";import{execFile as Mn,spawn as Vn}from"child_process";import{promisify as Ln}from"util";var se=Ln(Mn),Un="kanonak",y=class{constructor(e=Un){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await se("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((i,s)=>{let a=Vn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(o),a.stdin.end(),a.on("close",c=>{c===0?i():s(new Error(`secret-tool store exited with code ${c}`))}),a.on("error",s)})}async remove(e){let t=l(e);try{await se("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await se("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
93
- `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function x(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as rt,mkdirSync as nt,readFileSync as ot,writeFileSync as it}from"fs";import{createCipheriv as Fn,createDecipheriv as Hn,randomBytes as st}from"crypto";import{homedir as zn}from"os";import{join as _e,dirname as at}from"path";var lt=_e(zn(),".config","kanonak"),F=_e(lt,"keyring.key"),Wn=_e(lt,"credentials.enc"),ct="aes-256-gcm",$e=32,K=12,Te=16,h=class{constructor(e=Wn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!rt(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ot(this.secretsFile);if(t.length<K+Te)return{};let n=t.subarray(0,K),o=t.subarray(K,K+Te),i=t.subarray(K+Te),s=Hn(ct,e,n);s.setAuthTag(o);let a=Buffer.concat([s.update(i),s.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=st(K),o=Fn(ct,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(i),o.final()]),a=o.getAuthTag(),c=Buffer.concat([n,a,s]);nt(at(this.secretsFile),{recursive:!0}),it(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(rt(F)){let t=ot(F);if(t.length!==$e)throw new Error(`Credential keyring key is corrupted (expected ${$e} bytes, got ${t.length}). Delete ${F} and re-authenticate.`);return t}let e=st($e);return nt(at(F),{recursive:!0}),it(F,e,{mode:384}),e}};import{execFile as Gn}from"child_process";import{promisify as Jn}from"util";var qn=Jn(Gn),pt=3e4,H=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${ae(n)}
92
+ "@`,Bn="";import{execFile as Mn,spawn as Vn}from"child_process";import{promisify as Ln}from"util";var se=Ln(Mn),Fn="kanonak",y=class{constructor(e=Fn){this.service=e}service;async get(e){let t=l(e);try{let{stdout:n}=await se("secret-tool",["lookup","service",this.service,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((i,s)=>{let a=Vn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",this.service,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});a.stdin.write(o),a.stdin.end(),a.on("close",c=>{c===0?i():s(new Error(`secret-tool store exited with code ${c}`))}),a.on("error",s)})}async remove(e){let t=l(e);try{await se("secret-tool",["clear","service",this.service,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await se("secret-tool",["search","service",this.service],{timeout:1e4}),t=[];for(let n of e.split(`
93
+ `)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function A(){try{return await se("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as rt,mkdirSync as nt,readFileSync as ot,writeFileSync as it}from"fs";import{createCipheriv as Un,createDecipheriv as Hn,randomBytes as st}from"crypto";import{homedir as zn}from"os";import{join as _e,dirname as at}from"path";var lt=_e(zn(),".config","kanonak"),U=_e(lt,"keyring.key"),Wn=_e(lt,"credentials.enc"),ct="aes-256-gcm",$e=32,K=12,Te=16,h=class{constructor(e=Wn){this.secretsFile=e}secretsFile;async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!rt(this.secretsFile))return{};try{let e=this.getOrCreateKey(),t=ot(this.secretsFile);if(t.length<K+Te)return{};let n=t.subarray(0,K),o=t.subarray(K,K+Te),i=t.subarray(K+Te),s=Hn(ct,e,n);s.setAuthTag(o);let a=Buffer.concat([s.update(i),s.final()]);return JSON.parse(a.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=st(K),o=Un(ct,t,n),i=Buffer.from(JSON.stringify(e),"utf-8"),s=Buffer.concat([o.update(i),o.final()]),a=o.getAuthTag(),c=Buffer.concat([n,a,s]);nt(at(this.secretsFile),{recursive:!0}),it(this.secretsFile,c,{mode:384})}getOrCreateKey(){if(rt(U)){let t=ot(U);if(t.length!==$e)throw new Error(`Credential keyring key is corrupted (expected ${$e} bytes, got ${t.length}). Delete ${U} and re-authenticate.`);return t}let e=st($e);return nt(at(U),{recursive:!0}),it(U,e,{mode:384}),e}};import{execFile as Gn}from"child_process";import{promisify as Jn}from"util";var qn=Jn(Gn),dt=3e4,H=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${ae(n)}
94
94
  Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
95
95
  Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=l(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${ae(o)}
96
- Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${ae(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${ae(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await qn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:pt});return n}catch(n){throw Xn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
97
- Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Yn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${pt/1e3}s on '${e}'.
98
- The helper may be waiting for authentication to an external vault.`):n}}};function ae(r){return r instanceof Error?r.message:String(r)}function Xn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function Yn(r){return r instanceof Error&&"killed"in r&&r.killed}var Ne=to(eo(),".kanonak","config.json"),ce=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=ro(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!ee(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=no();return e.credentialHelper?new H(e.credentialHelper):process.platform==="darwin"?new m:process.platform==="win32"?new f:await x()?new y:new h}};function ro(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function no(){if(!Zn(Ne))return{};try{return JSON.parse(Qn(Ne,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ne}: ${e}
99
- Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as ft}from"os";import{join as A}from"path";import{mkdir as oo,writeFile as dt,readFile as ut,rm as mt}from"fs/promises";var je="kanonak-device",io=A(ft(),".config","kanonak","device-credentials.enc"),so=A(ft(),".kanonak","devices"),D=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=l(e).replace(/[^a-zA-Z0-9._-]/g,"_");return A(this.deps.certBaseDir??so,t)}async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){let t=await(await this.getBackend()).get(e);if(!t)return null;if(typeof t.certificatePem=="string"&&typeof t.chainPem=="string")return t;let n=this.certDir(e),o,i;try{o=await ut(A(n,"cert.pem"),"utf-8"),i=await ut(A(n,"chain.pem"),"utf-8")}catch{return null}return{...t,certificatePem:o,chainPem:i}}async store(e,t){let{certificatePem:n,chainPem:o,...i}=t,s=this.certDir(e);await oo(s,{recursive:!0}),await dt(A(s,"cert.pem"),n,"utf-8"),await dt(A(s,"chain.pem"),o,"utf-8");try{await(await this.getBackend()).store(e,i)}catch(a){throw await mt(s,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await mt(this.certDir(e),{recursive:!0,force:!0})}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(je):process.platform==="win32"?new f(`${je}:`):await x()?new y(je):new h(io)}};import{homedir as ao}from"os";import{join as co}from"path";var Oe="kanonak-session",lo=co(ao(),".config","kanonak","session-credentials.enc"),$=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Oe):process.platform==="win32"?new f(`${Oe}:`):await x()?new y(Oe):new h(lo)}};function le(r,e=5*6e4,t=Date.now()){let n=Date.parse(r.expiresAt);return Number.isNaN(n)?!0:t>=n-e}var yt="key_thumbprint",R=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=l(e);if(this.prCache.has(t))return this.prCache.get(t);let n=`https://${t}/.well-known/oauth-protected-resource`,o=await po(n),i=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],s=i.length>0?i:null;return this.prCache.set(t,s),s}async discover(e){let t=l(e);if(this.cache.has(t))return this.cache.get(t);let n=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(n);if(!o){let i=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(i)}return this.cache.set(t,o),o}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(o){let i=o instanceof Error?o.message:String(o);return i.includes("ENOTFOUND")||i.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${i})`),console.error(" If the server is behind a VPN, ensure you are connected.")):i.includes("CERT")||i.includes("SSL")||i.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${i})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${i}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(n.issuer),authorizationEndpoint:g(n.authorization_endpoint),tokenEndpoint:g(n.token_endpoint),registrationEndpoint:g(n.registration_endpoint),revocationEndpoint:g(n.revocation_endpoint),scopesSupported:k(n.scopes_supported),responseTypesSupported:k(n.response_types_supported),grantTypesSupported:k(n.grant_types_supported),codeChallengeMethodsSupported:k(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(n.dpop_signing_alg_values_supported),enrollmentEndpoint:g(n.enrollment_endpoint),enrollmentIssuanceProtocols:k(n.enrollment_issuance_protocols),enrollmentKeyTypes:k(n.enrollment_key_types),enrollmentScopesSupported:k(n.enrollment_scopes_supported),enrollmentConsentBindingParam:g(n.enrollment_consent_binding_param),sessionEndpoint:g(n.session_endpoint),sessionEndpointAuthMethod:g(n.session_endpoint_auth_method)}}};async function po(r){try{let e=await fetch(r);return e.ok?await e.json():null}catch{return null}}function g(r){return typeof r=="string"?r:null}function k(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):null}import*as ht from"https";import{createPrivateKey as uo}from"crypto";var mo="client_credentials",S=class extends Error{},T=class{constructor(e=ho){this.transport=e}transport;async exchange(e,t,n={}){let o=yo(t.keyMaterial),i=new URLSearchParams({grant_type:mo});n.scope&&i.set("scope",n.scope);let s=i.toString(),a;try{a=await this.transport({url:e,certPem:fo(t),keyPem:o,body:s,contentType:"application/x-www-form-urlencoded"})}catch(O){throw new S(`mTLS session exchange to ${e} failed: ${O.message}`)}if(a.status<200||a.status>=300)throw new S(`Session endpoint ${e} returned HTTP ${a.status}: ${a.body.slice(0,300)}`);let c;try{c=JSON.parse(a.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${a.body.slice(0,200)}`)}if(typeof c.access_token!="string"||!c.access_token)throw new S("Session response had no access_token.");let p=typeof c.expires_in=="number"?c.expires_in:0,d=n.nowMs??Date.now();return{token:c.access_token,tokenType:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expiresAt:new Date(d+p*1e3).toISOString(),scope:typeof c.scope=="string"?c.scope:""}}};function fo(r){let e=r.chainPem.trim();return e?`${r.certificatePem.replace(/\s+$/,"")}
96
+ Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${ae(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${ae(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await qn(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:dt});return n}catch(n){throw Xn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
97
+ Check the 'credentialHelper' path in ~/.kanonak/config.json.`):Yn(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${dt/1e3}s on '${e}'.
98
+ The helper may be waiting for authentication to an external vault.`):n}}};function ae(r){return r instanceof Error?r.message:String(r)}function Xn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function Yn(r){return r instanceof Error&&"killed"in r&&r.killed}var Ne=to(eo(),".kanonak","config.json"),ce=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=ro(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!ee(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=no();return e.credentialHelper?new H(e.credentialHelper):process.platform==="darwin"?new m:process.platform==="win32"?new f:await A()?new y:new h}};function ro(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function no(){if(!Zn(Ne))return{};try{return JSON.parse(Qn(Ne,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ne}: ${e}
99
+ Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{homedir as ft}from"os";import{join as I}from"path";import{mkdir as oo,writeFile as pt,readFile as ut,rm as mt}from"fs/promises";var Oe="kanonak-device",io=I(ft(),".config","kanonak","device-credentials.enc"),so=I(ft(),".kanonak","devices"),R=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;certDir(e){let t=l(e).replace(/[^a-zA-Z0-9._-]/g,"_");return I(this.deps.certBaseDir??so,t)}async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){let t=await(await this.getBackend()).get(e);if(!t)return null;if(typeof t.certificatePem=="string"&&typeof t.chainPem=="string")return t;let n=this.certDir(e),o,i;try{o=await ut(I(n,"cert.pem"),"utf-8"),i=await ut(I(n,"chain.pem"),"utf-8")}catch{return null}return{...t,certificatePem:o,chainPem:i}}async store(e,t){let{certificatePem:n,chainPem:o,...i}=t,s=this.certDir(e);await oo(s,{recursive:!0}),await pt(I(s,"cert.pem"),n,"utf-8"),await pt(I(s,"chain.pem"),o,"utf-8");try{await(await this.getBackend()).store(e,i)}catch(a){throw await mt(s,{recursive:!0,force:!0}).catch(()=>{}),a}}async remove(e){await(await this.getBackend()).remove(e),await mt(this.certDir(e),{recursive:!0,force:!0})}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(Oe):process.platform==="win32"?new f(`${Oe}:`):await A()?new y(Oe):new h(io)}};import{homedir as ao}from"os";import{join as co}from"path";var je="kanonak-session",lo=co(ao(),".config","kanonak","session-credentials.enc"),$=class{constructor(e={}){this.deps=e}deps;backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async get(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){return this.deps.backend?this.deps.backend:process.platform==="darwin"?new m(je):process.platform==="win32"?new f(`${je}:`):await A()?new y(je):new h(lo)}};function le(r,e=5*6e4,t=Date.now()){let n=Date.parse(r.expiresAt);return Number.isNaN(n)?!0:t>=n-e}var yt="key_thumbprint",E=class{cache=new Map;prCache=new Map;async discoverProtectedResource(e){let t=l(e);if(this.prCache.has(t))return this.prCache.get(t);let n=`https://${t}/.well-known/oauth-protected-resource`,o=await po(n),i=o&&Array.isArray(o.authorization_servers)?o.authorization_servers.filter(a=>typeof a=="string"):[],s=i.length>0?i:null;return this.prCache.set(t,s),s}async discover(e){let t=l(e);if(this.cache.has(t))return this.cache.get(t);let n=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(n);if(!o){let i=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(i)}return this.cache.set(t,o),o}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}static supportsEnrollment(e){return!!e.enrollmentEndpoint}static supportsSession(e){return!!e.sessionEndpoint}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(o){let i=o instanceof Error?o.message:String(o);return i.includes("ENOTFOUND")||i.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${i})`),console.error(" If the server is behind a VPN, ensure you are connected.")):i.includes("CERT")||i.includes("SSL")||i.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${i})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${i}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let n;try{n=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:g(n.issuer),authorizationEndpoint:g(n.authorization_endpoint),tokenEndpoint:g(n.token_endpoint),registrationEndpoint:g(n.registration_endpoint),revocationEndpoint:g(n.revocation_endpoint),scopesSupported:k(n.scopes_supported),responseTypesSupported:k(n.response_types_supported),grantTypesSupported:k(n.grant_types_supported),codeChallengeMethodsSupported:k(n.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:k(n.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:k(n.dpop_signing_alg_values_supported),enrollmentEndpoint:g(n.enrollment_endpoint),enrollmentIssuanceProtocols:k(n.enrollment_issuance_protocols),enrollmentKeyTypes:k(n.enrollment_key_types),enrollmentScopesSupported:k(n.enrollment_scopes_supported),enrollmentConsentBindingParam:g(n.enrollment_consent_binding_param),sessionEndpoint:g(n.session_endpoint),sessionEndpointAuthMethod:g(n.session_endpoint_auth_method)}}};async function po(r){try{let e=await fetch(r);return e.ok?await e.json():null}catch{return null}}function g(r){return typeof r=="string"?r:null}function k(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):null}import*as ht from"https";import{createPrivateKey as uo}from"crypto";var mo="client_credentials",S=class extends Error{},T=class{constructor(e=ho){this.transport=e}transport;async exchange(e,t,n={}){let o=yo(t.keyMaterial),i=new URLSearchParams({grant_type:mo});n.scope&&i.set("scope",n.scope);let s=i.toString(),a;try{a=await this.transport({url:e,certPem:fo(t),keyPem:o,body:s,contentType:"application/x-www-form-urlencoded"})}catch(j){throw new S(`mTLS session exchange to ${e} failed: ${j.message}`)}if(a.status<200||a.status>=300)throw new S(`Session endpoint ${e} returned HTTP ${a.status}: ${a.body.slice(0,300)}`);let c;try{c=JSON.parse(a.body)}catch{throw new S(`Session endpoint returned a non-JSON response: ${a.body.slice(0,200)}`)}if(typeof c.access_token!="string"||!c.access_token)throw new S("Session response had no access_token.");let d=typeof c.expires_in=="number"?c.expires_in:0,p=n.nowMs??Date.now();return{token:c.access_token,tokenType:typeof c.token_type=="string"&&c.token_type?c.token_type:"Bearer",expiresAt:new Date(p+d*1e3).toISOString(),scope:typeof c.scope=="string"?c.scope:""}}};function fo(r){let e=r.chainPem.trim();return e?`${r.certificatePem.replace(/\s+$/,"")}
100
100
  ${e}
101
- `:r.certificatePem}function yo(r){try{return uo({key:r,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var ho=r=>new Promise((e,t)=>{let n=new URL(r.url),o=ht.request({method:"POST",hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,cert:r.certPem,key:r.keyPem,headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(r.body),Accept:"application/json"},timeout:3e4},i=>{let s=[];i.on("data",a=>s.push(a)),i.on("end",()=>e({status:i.statusCode??0,body:Buffer.concat(s).toString("utf-8")}))});o.on("error",t),o.on("timeout",()=>o.destroy(new Error("mTLS request timed out"))),o.write(r.body),o.end()});var _=class extends Error{},N=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new R,this.deviceStore=e.deviceStore??new D,this.sessionStore=e.sessionStore??new $,this.exchange=e.exchange??new T}async acquire(e,t={}){let n=l(e),o=await this.sessionEndpoint(e);if(!o)throw new _(`'${n}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let i=await this.deviceStore.get(e);if(!i)throw new _(`No device certificate enrolled for '${n}'. Run 'kanonak device enroll ${e}' first.`);let s=await this.exchange.exchange(o,i,t),a={token:s.token,tokenType:s.tokenType,expiresAt:s.expiresAt,scope:s.scope};return await this.sessionStore.store(n,a),a}async getValidSession(e){let t=l(e),n=await this.sessionStore.get(t);return n&&!le(n)?n:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(l(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var pe=class{discovery;sessions;constructor(e={}){this.discovery=e.discovery??new R,this.sessions=e.sessionManager??new N}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;for(let n of t){let o=go(n);if(!o)continue;let i=await this.sessions.getValidSession(o);if(i)return{authority:o,token:i.token,expiresAt:i.expiresAt,scope:i.scope}}return null}};function go(r){try{return new URL(r).host}catch{return}}import{createHash as ko,createPrivateKey as So,generateKeyPairSync as wo,randomUUID as bo,sign as Po}from"crypto";function kt(){let{publicKey:r,privateKey:e}=wo("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function z(r,e,t,n,o,i){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:bo(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(a.ath=ko("sha256").update(o).digest("base64url")),i&&(a.nonce=i),vo(s,a,r)}function St(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function vo(r,e,t){let n=gt(JSON.stringify(r)),o=gt(JSON.stringify(e)),i=`${n}.${o}`,s=So({key:t,format:"jwk"}),c=Po("SHA256",Buffer.from(i),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function gt(r){return Buffer.from(r,"utf-8").toString("base64url")}function wt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return I(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return I(t,{method:o});Q(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(i.dpopKeyPair){let c=e.get(n);try{let p=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.Authorization=`DPoP ${i.accessToken}`,s.DPoP=p}catch(p){let d=p instanceof Error?p.message:String(p);console.error(` Error: Failed to create DPoP proof for '${n}': ${d}
102
- The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${i.accessToken}`}}else s.Authorization=`Bearer ${i.accessToken}`;let a=await I(t,{method:o,headers:s});if(a.status===401&&i.dpopKeyPair){let c=a.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let p=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.DPoP=p,a=await I(t,{method:o,headers:s})}catch{}}}return a}}import{readFileSync as Ro,writeFileSync as Eo,existsSync as Co}from"fs";import{createHash as xo}from"crypto";import bt from"js-yaml";var Pt="kanonak.lock",Ao=`# This file is generated by Kanonak CLI. Do not edit manually.
103
- `;function vt(r=Pt){if(!Co(r))return null;let e=Ro(r,"utf-8"),t=bt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Rt(r,e=Pt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=bt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Eo(e,Ao+n,"utf-8")}function Et(r){return`sha256:${xo("sha256").update(r).digest("hex")}`}import*as Ve from"js-yaml";import{canonicalForm as Io,canonicalHash as Ko}from"@kanonak-protocol/canonical";function Be(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as $t}from"@kanonak-protocol/canonical";function Ct(r){return Io(Be(r)?r:xt(r))}function de(r){return Ko(Be(r)?r:xt(r))}function xt(r){let e=[];for(let t of r)t instanceof b&&e.push({uri:_o(t),statements:Me(t.statement)});return{subjects:e}}function Me(r){let e=[];for(let t of r){let n=To(t);if(!n)continue;let o=Do(t);o&&e.push({predicate:n,value:o})}return e}function Do(r){if(r instanceof we&&r.carrier)return{lit:r.lexical??String(r.object),datatype:It(r.carrier)};if(r instanceof be)return{raw:r.object};if(r instanceof Pe)return{raw:r.lexical??String(r.object)};if(r instanceof ve)return{raw:r.lexical??String(r.object)};if(r instanceof Re)return{ref:Kt(r.object)};if(r instanceof Ee)return At(r.object);if(r instanceof Ce)return{list:r.object.map($o)}}function At(r){let e=Me(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function $o(r){if(r instanceof C)return{ref:Kt(r)};if(r instanceof P)return At(r);if(r instanceof Se){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:It(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof ke)return{embed:{statements:Me(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function It(r){return r===Z.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function To(r){let e=r.predicate;if(e)return Dt(e.subject)}function _o(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function Kt(r){return Dt(r.subject)}function Dt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as Tt}from"@kanonak-protocol/types/document/models/enums";var No="0.0.0",j=class{constructor(e,t=new M,n){this.repository=e;this.parser=t;this.objectParser=n??new U(this.parser)}repository;parser;objectParser;imports(){return new W}serializeValue(e,t){return jt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Le(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let s={[o]:i,...e.body},a=this.dump(s);return{yaml:a,byteCount:Nt(a),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},s=this.dump(i),a={yaml:s,byteCount:Nt(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(a.contentHash=o),a}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[_t]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ve.dump(o,{lineWidth:-1})),s=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Xe(i,this.repository))).filter(p=>p instanceof b&&p.namespace===s&&p.name!==_t);for(let p of c)p.namespace="ephemeral";return de(c)}},_t="__pkgbuilder_probe__";function Nt(r){return new TextEncoder().encode(r).length}function Le(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var W=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=Tt.Major){let s=`${e}/${t}@${n}`,a=this.byKey.get(s);if(a)return a.alias;let c=this.uniqueAlias(o);return this.byKey.set(s,{publisher:e,package_:t,version:n,alias:c,match:i}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,E(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,No,o??t,Tt.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ge(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=G(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function jt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof C)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>jt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof P)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(jo(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function G(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function jo(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ue=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${E(o)}`,s=this.produced.get(i);if(s)return s;let{document:a}=await e.produce(t,n,o);return this.produced.set(i,a),a}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=Ke(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ue={async authorize(){return{allowed:!0}}},Fe={async record(){}},J=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},me=class{inner;ctx;policy;meter;constructor(e,t,n=Ue,o=Fe){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new J(e,t.reason)}};var u="kanonak.org",w="view",Ot="core-kanonak",Oo={publisher:u,package_:w,name:"rootView"},Bo={publisher:u,package_:w,name:"bind"},Mo={publisher:u,package_:w,name:"produces"},Vo={publisher:u,package_:w,name:"projections"},Lo={publisher:u,package_:w,name:"where"},Uo={publisher:u,package_:w,name:"value"},Fo={publisher:u,package_:w,name:"as"},fe=class{constructor(e,t=new M){this.repository=e;this.parser=t;this.objectParser=new U(this.parser),this.builder=new j(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=V(o,Bo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let s=V(o,Mo);if(!s)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let a=Ho(o),c=Bt(n,u,Ot),p=Bt(n,u,w),d=this.builder.imports(),O=d.ensure(u,Ot,c,"ck"),Vt=d.ensure(u,w,p,"v"),Lt=d.ref(s),Ut=new Qe(this.repository,this.parser,this.objectParser),He=new Ye(Ut,n),Ft=this.readProjections(n,o),Ht=Go(o,Lo),zt=this.findInstances(n,i,await this.reason(t)),ze={},Wt=new Set;for(let q of zt){if(!await this.passesWhere(He,n,Ht,q))continue;let he={type:Lt};for(let Ge of Ft){let Gt=await this.evaluateValue(He,n,Ge.value,q),Je=this.builder.serializeValue(Mt(Gt),d);Je!==void 0&&(he[d.ref(Ge.as)]=Je)}let We=v(q);We&&(he[`${Vt}.derivedFrom`]=d.ref(We)),ze[this.rowName(q,Wt)]=he}let ye={};t.resolvedAt&&(ye[`${O}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ye[`${O}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:d,body:ze,contentHashProperty:`${O}.contentHash`,header:ye});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let n=Y(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=V(n,Oo);if(o){let i=Y(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of Ae(t,Vo)){let i=o instanceof P?o:o instanceof C?Y(e,o.subject):void 0;if(!i)continue;let s=xe(i,Uo),a=V(i,Fo);s&&a&&n.push({value:s,as:a})}return n}async reason(e){return new Ie({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=Wo(e),i=[],s=new Set;for(let a of n.getInstancesOfClass(t)){if(s.has(a))continue;s.add(a);let c=o.get(a);c&&i.push(c)}return i.sort((a,c)=>{let p=L(v(a)),d=L(v(c));return p<d?-1:p>d?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let s=await this.evaluateValue(e,t,i,o);if(!Jo(s))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ze(n,"view-projection",{catalog:t,depth:0}),s=new Map([["input",o]]);return e.evaluate(i,s)}rowName(e,t){let n=G(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Mt(r){return De(r)?r.value:Array.isArray(r)?r.map(Mt):r}function Ho(r){let e=v(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function Bt(r,e,t){let n=zo(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function zo(r,e,t){let n;for(let o of r){if(!(o instanceof b))continue;let i=v(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||X(i.version,n)>0)&&(n=i.version)}return n?E(n):void 0}function Wo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof b))continue;let o=v(n);if(!o||!o.version)continue;let i=L(o),s=t.get(i);(!s||X(o.version,s)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function Go(r,e){let t=xe(r,e);return t?[t]:Ae(r,e).filter(n=>n instanceof P)}function Jo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:De(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{kn as AmbiguousReferenceRule,ve as BooleanStatement,$t as CANONICAL_FORM_VERSION,Z as Carrier,Rn as ClassDefinitionRule,dn as ClassHierarchyCycleRule,or as CompositeKanonakDocumentRepository,pe as CredentialResolver,ce as CredentialStore,yt as DEFAULT_CONSENT_BINDING_PARAM,ke as DefinedKanonak,D as DeviceCertificateStore,nr as DocumentLocation,$r as EdgeType,P as EmbeddedKanonak,cn as EmbeddedKanonakTypeRule,Ee as EmbeddedStatement,J as EntitlementDeniedError,me as EntitlementProducer,rr as FileSystemKanonakDocumentRepository,Br as GitIgnoreFilter,Tr as GraphBuilder,mr as HttpKanonakDocumentRepository,W as ImportBook,ln as ImportExistenceRule,tr as InMemoryKanonakDocumentRepository,ar as KANONAK_USER_AGENT,kr as Kanonak,Vr as KanonakDocumentPositions,U as KanonakObjectParser,Cn as KanonakObjectValidator,M as KanonakParser,Sr as KanonakUri,Fr as KanonakUriBuilder,zr as KanonakUrlResolver,xr as KanonakVocabulary,Ce as ListStatement,Se as LiteralKanonak,fr as LocalFirstRepository,yr as LockAwareRepository,In as LookRenderer,En as MarkdownLinkRule,br as MarkdownStatement,hn as NamespaceImportCycleRule,rn as NamespacePrefixRule,Dr as NodeType,Pe as NumberStatement,R as OAuthDiscovery,jr as OWL_RL_CLASSIFICATION_RULES,wn as ObjectPropertyValueValidationRule,Qr as OntologyValidationError,Yr as OntologyValidationResult,j as PackageBuilder,an as PackageHeaderRule,ue as ProducerRepository,bn as PropertyDomainRule,un as PropertyHierarchyCycleRule,Pn as PropertyKindRangeConsistencyRule,Mr as PropertyMetadata,Sn as PropertyRangeReferenceRule,mn as PropertyRangeRequiredRule,on as PropertyTypeSpecificityRule,pr as PublisherConfigResolver,dr as PublisherIndex,Nr as RDFS_RULES,Ie as Reasoner,Or as ReasoningResult,C as ReferenceKanonak,Re as ReferenceStatement,sr as RepositoryFactory,vn as ReservedNameShadowRule,nn as ResourceNamingRule,Pr as ResourceResolver,Kr as ResourceTypeClassifier,we as ScalarStatement,_ as SessionError,T as SessionExchange,S as SessionExchangeError,N as SessionManager,$ as SessionStore,wr as Statement,be as StringStatement,fn as SubClassOfReferenceRule,yn as SubPropertyOfReferenceRule,b as SubjectKanonak,sn as SubjectKanonakTypeRequiredRule,_r as TripleStore,vr as TypeResolver,gn as UnresolvedPredicateRule,pn as UnresolvedReferenceRule,tn as ValidationCache,en as ValidationContext,Zr as ValidationSeverity,Oa as VersionOperator,fe as ViewMaterializer,Ue as allowAllPolicy,ur as assertPackageIdentity,gr as buildLocalFirstRepository,Kn as buildOntologyModel,Ct as canonicalForm,de as canonicalHash,qe as carrierOf,hr as collectKanonakFiles,X as compareVersions,Et as computeIntegrity,Le as contentAddressedName,qr as contextTypesOf,wt as createAuthenticatedFetch,z as createDPoPProof,Xt as createVersion,Ir as extractMarkdownLinks,xn as findDerivation,Xr as findInstancesByType,Ar as findMalformedReferences,Ur as findMarkdownLinkAt,Hr as formatKanonakAddress,E as formatVersion,kt as generateDPoPKeyPair,ir as getGlobalCachePath,lr as getKanonakUserAgent,ee as hasValidToken,Zt as isCompatibleVersion,Q as isExpired,Qt as isMajorCompatible,I as kanonakFetch,vt as loadLockFile,Rr as makeUriKey,Fe as noopMeter,l as normalizeHost,Ke as parseKanonakAddress,Yt as parseVersionString,Lr as parseWithPositions,er as pickHighestDocument,Gr as propertiesInScope,An as resolveDisplayValue,Jr as resolvePropertyStep,G as sanitizeName,Rt as saveLockFile,St as serverSupportsDPoP,le as sessionNeedsRefresh,cr as setKanonakUserAgent,v as subjectUri,Wr as superClassChain,Er as tripleKey,L as uriKey,Cr as uriTriple,Jt as versionOperatorFromChar,ge as versionOperatorToChar,qt as versionsEqual};
101
+ `:r.certificatePem}function yo(r){try{return uo({key:r,format:"jwk"}).export({type:"pkcs8",format:"pem"})}catch(e){throw new S(`The device key is not an exportable software private key, so it cannot present mTLS in software (a future hardware key provider would do the handshake itself): ${e.message}`)}}var ho=r=>new Promise((e,t)=>{let n=new URL(r.url),o=ht.request({method:"POST",hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,cert:r.certPem,key:r.keyPem,headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(r.body),Accept:"application/json"},timeout:3e4},i=>{let s=[];i.on("data",a=>s.push(a)),i.on("end",()=>e({status:i.statusCode??0,body:Buffer.concat(s).toString("utf-8")}))});o.on("error",t),o.on("timeout",()=>o.destroy(new Error("mTLS request timed out"))),o.write(r.body),o.end()});var _=class extends Error{},N=class{discovery;deviceStore;sessionStore;exchange;constructor(e={}){this.discovery=e.discovery??new E,this.deviceStore=e.deviceStore??new R,this.sessionStore=e.sessionStore??new $,this.exchange=e.exchange??new T}async acquire(e,t={}){let n=l(e),o=await this.sessionEndpoint(e);if(!o)throw new _(`'${n}' does not advertise a session endpoint \u2014 it issues no scoped sessions (public registries need no credential).`);let i=await this.deviceStore.get(e);if(!i)throw new _(`No device certificate enrolled for '${n}'. Run 'kanonak device enroll ${e}' first.`);let s=await this.exchange.exchange(o,i,t),a={token:s.token,tokenType:s.tokenType,expiresAt:s.expiresAt,scope:s.scope};return await this.sessionStore.store(n,a),a}async getValidSession(e){let t=l(e),n=await this.sessionStore.get(t);return n&&!le(n)?n:!await this.sessionEndpoint(e)||!await this.deviceStore.get(e)?null:this.acquire(e)}async clear(e){await this.sessionStore.remove(l(e))}async sessionEndpoint(e){return(await this.discovery.discover(e))?.sessionEndpoint??null}};var de=class{discovery;sessions;devices;constructor(e={}){this.discovery=e.discovery??new E,this.sessions=e.sessionManager??new N({discovery:this.discovery}),this.devices=e.deviceStore??new R}async resolve(e){let t=await this.discovery.discoverProtectedResource(e);if(!t||t.length===0)return null;let n=t.map(go).filter(s=>s!==void 0);for(let s of n){let a=await this.sessionFor(s);if(a)return a}let i=(await this.devices.list()).map(l).filter(s=>!n.includes(s));if(i.length===0)return null;for(let s of n){let a=(await this.discovery.discover(s))?.sessionEndpoint;if(a)for(let c of i){if((await this.discovery.discover(c))?.sessionEndpoint!==a)continue;let p=await this.sessionFor(c);if(p)return p}}return null}async sessionFor(e){let t=await this.sessions.getValidSession(e);return t?{authority:e,token:t.token,expiresAt:t.expiresAt,scope:t.scope}:null}};function go(r){try{return new URL(r).host}catch{return}}import{createHash as ko,createPrivateKey as So,generateKeyPairSync as wo,randomUUID as vo,sign as bo}from"crypto";function kt(){let{publicKey:r,privateKey:e}=wo("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function z(r,e,t,n,o,i){let s={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},a={jti:vo(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(a.ath=ko("sha256").update(o).digest("base64url")),i&&(a.nonce=i),Po(s,a,r)}function St(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Po(r,e,t){let n=gt(JSON.stringify(r)),o=gt(JSON.stringify(e)),i=`${n}.${o}`,s=So({key:t,format:"jwk"}),c=bo("SHA256",Buffer.from(i),{key:s,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${i}.${c}`}function gt(r){return Buffer.from(r,"utf-8").toString("base64url")}function wt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return D(t,{method:o});let i=await r.getCredential(n);if(!i?.accessToken)return D(t,{method:o});Q(i)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let s={};if(i.dpopKeyPair){let c=e.get(n);try{let d=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.Authorization=`DPoP ${i.accessToken}`,s.DPoP=d}catch(d){let p=d instanceof Error?d.message:String(d);console.error(` Error: Failed to create DPoP proof for '${n}': ${p}
102
+ The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),s.Authorization=`Bearer ${i.accessToken}`}}else s.Authorization=`Bearer ${i.accessToken}`;let a=await D(t,{method:o,headers:s});if(a.status===401&&i.dpopKeyPair){let c=a.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let d=z(i.dpopKeyPair.privateKey,i.dpopKeyPair.publicKey,o,t,i.accessToken,c);s.DPoP=d,a=await D(t,{method:o,headers:s})}catch{}}}return a}}import{readFileSync as Ro,writeFileSync as Eo,existsSync as Co}from"fs";import{createHash as xo}from"crypto";import vt from"js-yaml";var bt="kanonak.lock",Ao=`# This file is generated by Kanonak CLI. Do not edit manually.
103
+ `;function Pt(r=bt){if(!Co(r))return null;let e=Ro(r,"utf-8"),t=vt.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function Rt(r,e=bt){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=vt.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Eo(e,Ao+n,"utf-8")}function Et(r){return`sha256:${xo("sha256").update(r).digest("hex")}`}import*as Ve from"js-yaml";import{canonicalForm as Io,canonicalHash as Do}from"@kanonak-protocol/canonical";function Be(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as $t}from"@kanonak-protocol/canonical";function Ct(r){return Io(Be(r)?r:xt(r))}function pe(r){return Do(Be(r)?r:xt(r))}function xt(r){let e=[];for(let t of r)t instanceof v&&e.push({uri:_o(t),statements:Me(t.statement)});return{subjects:e}}function Me(r){let e=[];for(let t of r){let n=To(t);if(!n)continue;let o=Ko(t);o&&e.push({predicate:n,value:o})}return e}function Ko(r){if(r instanceof we&&r.carrier)return{lit:r.lexical??String(r.object),datatype:It(r.carrier)};if(r instanceof ve)return{raw:r.object};if(r instanceof be)return{raw:r.lexical??String(r.object)};if(r instanceof Pe)return{raw:r.lexical??String(r.object)};if(r instanceof Re)return{ref:Dt(r.object)};if(r instanceof Ee)return At(r.object);if(r instanceof Ce)return{list:r.object.map($o)}}function At(r){let e=Me(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function $o(r){if(r instanceof x)return{ref:Dt(r)};if(r instanceof b)return At(r);if(r instanceof Se){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:It(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof ke)return{embed:{statements:Me(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function It(r){return r===Z.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function To(r){let e=r.predicate;if(e)return Kt(e.subject)}function _o(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function Dt(r){return Kt(r.subject)}function Kt(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as Tt}from"@kanonak-protocol/types/document/models/enums";var No="0.0.0",O=class{constructor(e,t=new M,n){this.repository=e;this.parser=t;this.objectParser=n??new F(this.parser)}repository;parser;objectParser;imports(){return new W}serializeValue(e,t){return Ot(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=Le(n),i={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(i[e.contentHashProperty]=n),Object.assign(i,e.header??{}),i.imports=t;let s={[o]:i,...e.body},a=this.dump(s);return{yaml:a,byteCount:Nt(a),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let i={[e.name]:n,...e.body},s=this.dump(i),a={yaml:s,byteCount:Nt(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(a.contentHash=o),a}dump(e){return Ve.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[_t]:{type:"EphemeralPackage",publisher:e,imports:t},...n},i=this.parser.parse(Ve.dump(o,{lineWidth:-1})),s=i.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new Xe(i,this.repository))).filter(d=>d instanceof v&&d.namespace===s&&d.name!==_t);for(let d of c)d.namespace="ephemeral";return pe(c)}},_t="__pkgbuilder_probe__";function Nt(r){return new TextEncoder().encode(r).length}function Le(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var W=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,i=Tt.Major){let s=`${e}/${t}@${n}`,a=this.byKey.get(s);if(a)return a.alias;let c=this.uniqueAlias(o);return this.byKey.set(s,{publisher:e,package_:t,version:n,alias:c,match:i}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,C(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,No,o??t,Tt.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,i)=>o.package_<i.package_?-1:1).map(o=>({package:o.package_,match:ge(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=G(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function Ot(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof x)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>Ot(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof b)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(Oo(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function G(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Oo(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var ue=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let i=`${t}/${n}@${C(o)}`,s=this.produced.get(i);if(s)return s;let{document:a}=await e.produce(t,n,o);return this.produced.set(i,a),a}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},i=await n.resolveVersion(e,t.packageName,o);return i?this.produceCached(n,e,t.packageName,i):null}async getDocumentAsync(e){let t;try{t=De(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Fe={async authorize(){return{allowed:!0}}},Ue={async record(){}},J=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},me=class{inner;ctx;policy;meter;constructor(e,t,n=Fe,o=Ue){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let i=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,i),i}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new J(e,t.reason)}};var u="kanonak.org",w="view",jt="core-kanonak",jo={publisher:u,package_:w,name:"rootView"},Bo={publisher:u,package_:w,name:"bind"},Mo={publisher:u,package_:w,name:"produces"},Vo={publisher:u,package_:w,name:"projections"},Lo={publisher:u,package_:w,name:"where"},Fo={publisher:u,package_:w,name:"value"},Uo={publisher:u,package_:w,name:"as"},fe=class{constructor(e,t=new M){this.repository=e;this.parser=t;this.objectParser=new F(this.parser),this.builder=new O(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),i=V(o,Bo);if(!i)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let s=V(o,Mo);if(!s)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let a=Ho(o),c=Bt(n,u,jt),d=Bt(n,u,w),p=this.builder.imports(),j=p.ensure(u,jt,c,"ck"),Vt=p.ensure(u,w,d,"v"),Lt=p.ref(s),Ft=new Qe(this.repository,this.parser,this.objectParser),He=new Ye(Ft,n),Ut=this.readProjections(n,o),Ht=Go(o,Lo),zt=this.findInstances(n,i,await this.reason(t)),ze={},Wt=new Set;for(let q of zt){if(!await this.passesWhere(He,n,Ht,q))continue;let he={type:Lt};for(let Ge of Ut){let Gt=await this.evaluateValue(He,n,Ge.value,q),Je=this.builder.serializeValue(Mt(Gt),p);Je!==void 0&&(he[p.ref(Ge.as)]=Je)}let We=P(q);We&&(he[`${Vt}.derivedFrom`]=p.ref(We)),ze[this.rowName(q,Wt)]=he}let ye={};t.resolvedAt&&(ye[`${j}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ye[`${j}.id`]=t.invocationId);let B=await this.builder.buildContentAddressed({publisher:a,book:p,body:ze,contentHashProperty:`${j}.contentHash`,header:ye});return{yaml:B.yaml,contentHash:B.contentHash,packageName:B.packageName,publisher:B.publisher,rowCount:B.resourceCount}}resolveView(e,t){let n=Y(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=V(n,jo);if(o){let i=Y(e,o);if(!i)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return i}return n}readProjections(e,t){let n=[];for(let o of Ae(t,Vo)){let i=o instanceof b?o:o instanceof x?Y(e,o.subject):void 0;if(!i)continue;let s=xe(i,Fo),a=V(i,Uo);s&&a&&n.push({value:s,as:a})}return n}async reason(e){return new Ie({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=Wo(e),i=[],s=new Set;for(let a of n.getInstancesOfClass(t)){if(s.has(a))continue;s.add(a);let c=o.get(a);c&&i.push(c)}return i.sort((a,c)=>{let d=L(P(a)),p=L(P(c));return d<p?-1:d>p?1:0}),i}async passesWhere(e,t,n,o){for(let i of n){let s=await this.evaluateValue(e,t,i,o);if(!Jo(s))return!1}return!0}async evaluateValue(e,t,n,o){let i=Ze(n,"view-projection",{catalog:t,depth:0}),s=new Map([["input",o]]);return e.evaluate(i,s)}rowName(e,t){let n=G(e.name)||"row",o=n,i=2;for(;t.has(o);)o=`${n}-${i++}`;return t.add(o),o}};function Mt(r){return Ke(r)?r.value:Array.isArray(r)?r.map(Mt):r}function Ho(r){let e=P(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function Bt(r,e,t){let n=zo(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function zo(r,e,t){let n;for(let o of r){if(!(o instanceof v))continue;let i=P(o);!i||i.publisher!==e||i.package_!==t||!i.version||(!n||X(i.version,n)>0)&&(n=i.version)}return n?C(n):void 0}function Wo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof v))continue;let o=P(n);if(!o||!o.version)continue;let i=L(o),s=t.get(i);(!s||X(o.version,s)>0)&&(t.set(i,o.version),e.set(i,n))}return e}function Go(r,e){let t=xe(r,e);return t?[t]:Ae(r,e).filter(n=>n instanceof b)}function Jo(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Ke(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{kn as AmbiguousReferenceRule,Pe as BooleanStatement,$t as CANONICAL_FORM_VERSION,Z as Carrier,Rn as ClassDefinitionRule,pn as ClassHierarchyCycleRule,or as CompositeKanonakDocumentRepository,de as CredentialResolver,ce as CredentialStore,yt as DEFAULT_CONSENT_BINDING_PARAM,ke as DefinedKanonak,R as DeviceCertificateStore,nr as DocumentLocation,$r as EdgeType,b as EmbeddedKanonak,cn as EmbeddedKanonakTypeRule,Ee as EmbeddedStatement,J as EntitlementDeniedError,me as EntitlementProducer,rr as FileSystemKanonakDocumentRepository,Br as GitIgnoreFilter,Tr as GraphBuilder,mr as HttpKanonakDocumentRepository,W as ImportBook,ln as ImportExistenceRule,tr as InMemoryKanonakDocumentRepository,ar as KANONAK_USER_AGENT,kr as Kanonak,Vr as KanonakDocumentPositions,F as KanonakObjectParser,Cn as KanonakObjectValidator,M as KanonakParser,Sr as KanonakUri,Ur as KanonakUriBuilder,zr as KanonakUrlResolver,xr as KanonakVocabulary,Ce as ListStatement,Se as LiteralKanonak,fr as LocalFirstRepository,yr as LockAwareRepository,In as LookRenderer,En as MarkdownLinkRule,vr as MarkdownStatement,hn as NamespaceImportCycleRule,rn as NamespacePrefixRule,Kr as NodeType,be as NumberStatement,E as OAuthDiscovery,Or as OWL_RL_CLASSIFICATION_RULES,wn as ObjectPropertyValueValidationRule,Qr as OntologyValidationError,Yr as OntologyValidationResult,O as PackageBuilder,an as PackageHeaderRule,ue as ProducerRepository,vn as PropertyDomainRule,un as PropertyHierarchyCycleRule,bn as PropertyKindRangeConsistencyRule,Mr as PropertyMetadata,Sn as PropertyRangeReferenceRule,mn as PropertyRangeRequiredRule,on as PropertyTypeSpecificityRule,dr as PublisherConfigResolver,pr as PublisherIndex,Nr as RDFS_RULES,Ie as Reasoner,jr as ReasoningResult,x as ReferenceKanonak,Re as ReferenceStatement,sr as RepositoryFactory,Pn as ReservedNameShadowRule,nn as ResourceNamingRule,br as ResourceResolver,Dr as ResourceTypeClassifier,we as ScalarStatement,_ as SessionError,T as SessionExchange,S as SessionExchangeError,N as SessionManager,$ as SessionStore,wr as Statement,ve as StringStatement,fn as SubClassOfReferenceRule,yn as SubPropertyOfReferenceRule,v as SubjectKanonak,sn as SubjectKanonakTypeRequiredRule,_r as TripleStore,Pr as TypeResolver,gn as UnresolvedPredicateRule,dn as UnresolvedReferenceRule,tn as ValidationCache,en as ValidationContext,Zr as ValidationSeverity,Ma as VersionOperator,fe as ViewMaterializer,Fe as allowAllPolicy,ur as assertPackageIdentity,gr as buildLocalFirstRepository,Dn as buildOntologyModel,Ct as canonicalForm,pe as canonicalHash,qe as carrierOf,hr as collectKanonakFiles,X as compareVersions,Et as computeIntegrity,Le as contentAddressedName,qr as contextTypesOf,wt as createAuthenticatedFetch,z as createDPoPProof,Xt as createVersion,Ir as extractMarkdownLinks,xn as findDerivation,Xr as findInstancesByType,Ar as findMalformedReferences,Fr as findMarkdownLinkAt,Hr as formatKanonakAddress,C as formatVersion,kt as generateDPoPKeyPair,ir as getGlobalCachePath,lr as getKanonakUserAgent,ee as hasValidToken,Zt as isCompatibleVersion,Q as isExpired,Qt as isMajorCompatible,D as kanonakFetch,Pt as loadLockFile,Rr as makeUriKey,Ue as noopMeter,l as normalizeHost,De as parseKanonakAddress,Yt as parseVersionString,Lr as parseWithPositions,er as pickHighestDocument,Gr as propertiesInScope,An as resolveDisplayValue,Jr as resolvePropertyStep,G as sanitizeName,Rt as saveLockFile,St as serverSupportsDPoP,le as sessionNeedsRefresh,cr as setKanonakUserAgent,P as subjectUri,Wr as superClassChain,Er as tripleKey,L as uriKey,Cr as uriTriple,Jt as versionOperatorFromChar,ge as versionOperatorToChar,qt as versionsEqual};
@@ -7,6 +7,12 @@ import type { IKanonakDocumentRepository, KanonakDocument, DocumentReference, Im
7
7
  * happens to be in the global cache. Unresolved imports are skipped (the page
8
8
  * still renders, just without that layer). Cross-publisher imports are followed
9
9
  * (an import names its own publisher), so the closure can span publishers.
10
+ *
11
+ * Resolving every import through `repo` has a deliberate side effect on a
12
+ * tiered repository: an import only the HTTP tier can satisfy is fetched (and
13
+ * parked in that tier) by the walk, so a subsequent `getAllDocumentsAsync()`
14
+ * enumerates the full closure. `ValidationCache` relies on this to build a
15
+ * complete catalog on a cold cache.
10
16
  */
11
17
  export declare function deriveImportClosure(seedDocs: KanonakDocument[], repo: IKanonakDocumentRepository): Promise<Set<string>>;
12
18
  /**
@@ -1,7 +1,7 @@
1
- import{j as ee}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as O,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{l as X}from"../chunk-MX3DEXMV.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as Z}from"../chunk-ZP6P7HNU.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as be,s as Q}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as M,e as F,f as L,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as De,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";function Se(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function H(t,e){let n=new Set,r=[...t];for(;r.length>0;){let s=r.shift(),a=Se(s);if(!a||n.has(a))continue;n.add(a);let m=s.metadata?.imports;if(m)for(let[p,k]of Object.entries(m))for(let d of k)try{let u=await e.getHighestCompatibleVersionAsync(p,d);u&&r.push(u)}catch{}}return n}var V=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let r=Se(n);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var we=[{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 T(t){let e=t?.render;if(e&&e.length>0){let n=[];for(let r of e)try{let s=Z(r);s.kind==="package"?n.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&n.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(n.length>0)return n}return we}function C(t){return`${t.publisher}/${t.package_}`}function W(t){let e={"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"},n=[];for(let r of t)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";n.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&n.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return n}function re(t){let{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,renderStack:p,producers:k}=t,d=new Map,u=new Map,o=new Map,h=new Set;for(let y of r){if(!(y instanceof be))continue;let b=y.namespace||"";if(!a.has(b))continue;d.set(`${b}/${y.name}`,y);let $=b.split("/")[1]??"",[w,_]=$.split("@");if(!w||!_)continue;let I=ue(_);I&&(h.has($)||(h.add($),u.has(w)||u.set(w,[]),u.get(w).push({verStr:_,version:I})),y.name===w&&o.set($,y))}for(let y of u.values())y.sort((b,$)=>M($.version,b.version));return{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,bySubject:d,pkgVersions:u,pkgSelfByVer:o,renderStack:p,...k?{producers:k}:{}}}async function se(t,e={}){let n=new E,r=new ge(n),s=[],a=[];for(let c of J(t)){let l;try{l=De(c,"utf-8")}catch{continue}let v;try{v=n.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:F(N),version:N,source:l})}a.sort((c,l)=>M(l.version,c.version));for(let c of a)await r.saveDocumentAsync(n.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),s.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(s.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!m.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)p=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let k=new Set,d=new Map;for(let c of s)c.publisher===p&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),o=new he(u,!0,n),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let y=e.repository??new ye(r,o,new Y(h)),b=e.log??(()=>{}),$=T(void 0),w=[],_=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>M(v,l)).map(F);if(!e.repository){b(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new O({fetchFn:e.fetchFn}):new O;for(let l of $){let v=C(l),N=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(N.length>0){let S=_(N);w.push({...l,origin:"workspace",versions:S}),b(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await o.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=_(U);w.push({...l,origin:"cache",versions:S}),b(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let f=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let j=await c.getPackageUrl(l.publisher,l.package_,S),i=await(e.fetchFn?e.fetchFn(j,l.publisher):me(j));if(!i.ok){let f=`fetch ${j} failed: HTTP ${i.status} ${i.statusText}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let g=await i.text();await r.saveDocumentAsync(n.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let f=$e(u,l.publisher);je(f,{recursive:!0}),_e($e(f,`${l.package_}@${S}.kan.yml`),g,"utf-8"),w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, installed to cache`)}catch(f){w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, but cache ${u} is NOT WRITABLE (${f.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let j=`fetch failed: ${S.message}`;w.push({...l,origin:"missing",reason:j}),b(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let I=y;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await H(c,y);for(let v of $)l.add(C(v));I=new V(y,l)}let B=await new X(n).parseKanonaks(I),oe=new ee(B),G=(c,l)=>Q(B,{publisher:c,package_:l,name:l}).length>0,A;if(e.repository){A=[];for(let c of $){let l=await y.getDocumentsByNamespaceAsync(c.publisher,c.package_);A.push(l.length>0?{...c,origin:"repository",versions:_(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=w.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=W(A);for(let c of q)b(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:m,catalog:B,lookRenderer:oe,localNamespaces:k,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:A,warnings:q}})}import{existsSync as Ce,readFileSync as Ae,writeFileSync as Ie,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function ae(t,e={}){let n=new E,r=Z(t),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),m=e.cacheRoot??z(),p=(i,g,f)=>Re(m,i,`${g}@${f}.kan.yml`),k=new Set,d=new Set,u=new Map,o=new Y({getFromCache:(i,g,f)=>{let D=p(i,g,f),R=Ce(D)?Ae(D,"utf-8"):null;return R!==null&&k.add(`${i}/${g}`),R},onFetch:(i,g,f,D)=>{d.add(`${i}/${g}`);try{let R=Re(m,i);Ne(R,{recursive:!0}),Ie(p(i,g,f),D,"utf-8")}catch(R){u.set(`${i}/${g}`,R.message),a(`[render] fetched ${i}/${g}@${f} but cache ${m} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new O(e.fetchFn?{fetchFn:e.fetchFn}:void 0),y;if(r.kind==="resource"){let i=r.uri.version;y=[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;y=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else y=(await h.listLatestPackages(s)).map(g=>({package_:g.packageName}));let b=async(i,g,f)=>{try{let D=f?n.buildImport(g,"=",f,i):n.buildImport(g,"*","0.0.0",i),R=await o.getHighestCompatibleVersionAsync(i,D);return R?{doc:R}:{doc:null,error:`${i} did not resolve ${g}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(D){return{doc:null,error:D.message}}},$=[],w=[];for(let i of y){let{doc:g,error:f}=await b(s,i.package_,i.version);g?$.push(g):f&&w.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${s}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=await new ke(e.fetchFn).getConfig(s).catch(()=>{}),I=T(_),B=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,f)=>M(f,g)).map(F);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${B}); cache: ${m}`);let G=[],A=[];for(let i of I){let g=C(i),{doc:f,error:D}=await b(i.publisher,i.package_,void 0);if(f){G.push(f);let R=oe([f]),pe=d.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...i,origin:pe,versions:R}),a(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...i,origin:"missing",reason:D??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${D??"unresolved"}`)}let q=await H([...$,...G],o),de=new V(o,q),c=await new X(n).parseKanonaks(de),l=new ee(c),v=A.map(i=>i.origin==="missing"||Q(c,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),N=W(v);for(let i of N)a(`[render-stack] WARNING: ${i}`);let U={contractSource:B,cachePath:m,packages:v,warnings:N},S=new Set,j=new Map;for(let i of await o.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==s)continue;let f=F(g.version),D=`${g.publisher}/${g.package_}@${f}`;S.add(D);let R=await o.getDocumentContentAsync(D);R!==null&&j.set(`${g.package_}@${f}`,R)}return re({publisher:s,availablePublishers:[s],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:j,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:n,renderStack:r,catalog:s}=t,a=e.explainStylesheet(e.publisherSubject(n)),m=[...a.tokens.entries()].map(([o,h])=>({name:o,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,k={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},d=new Map;for(let o of s){let h=o.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([o,h])=>({namespace:o,resources:h})).sort((o,h)=>o.namespace.localeCompare(h.namespace));return{publisher:n,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Fe(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ie(t){let e=Fe,n=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
2
- `),s=t.renderStack.packages.map(d=>{let u=d.origin!=="missing"&&!d.resolvedButNotInCatalog,o=d.origin==="missing"?'<span class="bad">MISSING</span>':d.resolvedButNotInCatalog?`<span class="bad">${e(d.origin)} (not in catalog)</span>`:`<span class="good">${e(d.origin)}</span>`,h=d.reason?e(d.reason):e((d.versions??[]).join(", "));return`<tr class="${u?"":"row-bad"}"><td><code>${e(d.package_)}</code></td><td>${o}</td><td>${h}</td></tr>`}).join(`
3
- `),a=t.stylesheet.baseStylesheet,m=a.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(a.source??"")}</code> (${a.bytes} bytes, ${e(a.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${a.problem?` \u2014 ${e(a.problem)}`:""}${a.candidates.length>0?`<br>candidates considered: ${a.candidates.map(d=>`<code>${e(d)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,p=t.stylesheet.tokens.map(d=>`<tr><td><code>--kan-${e(d.name)}</code></td><td><code>${e(d.value)}</code></td><td><code>${e(d.source)}</code></td><td>${e(d.level)}</td></tr>`).join(`
4
- `),k=t.catalog.map(d=>`<tr><td><code>${e(d.namespace)}</code></td><td>${d.resources}</td></tr>`).join(`
1
+ import{j as ee}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as L,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{a as O,b as T}from"../chunk-ITKOKDBG.js";import{l as X}from"../chunk-MX3DEXMV.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as Z}from"../chunk-ZP6P7HNU.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import{c as be,s as Q}from"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import{c as V,e as D,f as B,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as Pe,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";var Se=[{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 W(t){let e=t?.render;if(e&&e.length>0){let s=[];for(let r of e)try{let o=Z(r);o.kind==="package"?s.push({publisher:o.publisher,package_:o.package_}):o.kind==="resource"&&s.push({publisher:o.uri.publisher,package_:o.uri.package_})}catch{}if(s.length>0)return s}return Se}function F(t){return`${t.publisher}/${t.package_}`}function H(t){let e={"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"},s=[];for(let r of t)if(r.origin==="missing"){let o=F(r),i=e[o]??"whatever this package contributes to rendering is lost";s.push(`Render-stack package ${o} is MISSING (${r.reason??"unknown reason"}) \u2014 ${i}. Fix: kanonak install ${o} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&s.push(`Render-stack package ${F(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return s}function re(t){let{publisher:e,availablePublishers:s,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:f,renderStack:p,producers:b}=t,d=new Map,u=new Map,n=new Map,h=new Set;for(let k of r){if(!(k instanceof be))continue;let y=k.namespace||"";if(!i.has(y))continue;d.set(`${y}/${k.name}`,k);let w=y.split("/")[1]??"",[$,j]=w.split("@");if(!$||!j)continue;let M=ue(j);M&&(h.has(w)||(h.add(w),u.has($)||u.set($,[]),u.get($).push({verStr:j,version:M})),k.name===$&&n.set(w,k))}for(let k of u.values())k.sort((y,w)=>V(w.version,y.version));return{publisher:e,availablePublishers:s,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:f,bySubject:d,pkgVersions:u,pkgSelfByVer:n,renderStack:p,...b?{producers:b}:{}}}async function se(t,e={}){let s=new E,r=new ge(s),o=[],i=[];for(let c of J(t)){let l;try{l=Pe(c,"utf-8")}catch{continue}let v;try{v=s.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let I=v.version;i.push({publisher:v.publisher,package_:v.package_,verStr:D(I),version:I,source:l})}i.sort((c,l)=>V(l.version,c.version));for(let c of i)await r.saveDocumentAsync(s.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),o.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let f=[...new Set(o.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!f.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${f.join(", ")||"(none)"}`)}else if(f.length===1)p=f[0];else throw f.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${f.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let b=new Set,d=new Map;for(let c of o)c.publisher===p&&(b.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),n=new he(u,!0,s),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let k=e.repository??new ye(r,n,new Y(h)),y=e.log??(()=>{}),w=W(void 0),$=[],j=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>V(v,l)).map(D);if(!e.repository){y(`[render-stack] resolving ${w.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new L({fetchFn:e.fetchFn}):new L;for(let l of w){let v=F(l),I=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(I.length>0){let S=j(I);$.push({...l,origin:"workspace",versions:S}),y(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await n.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=j(U);$.push({...l,origin:"cache",versions:S}),y(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let m=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;$.push({...l,origin:"missing",reason:m}),y(`[render-stack] ${v} \u2014 MISSING: ${m}`);continue}let C=await c.getPackageUrl(l.publisher,l.package_,S),a=await(e.fetchFn?e.fetchFn(C,l.publisher):me(C));if(!a.ok){let m=`fetch ${C} failed: HTTP ${a.status} ${a.statusText}`;$.push({...l,origin:"missing",reason:m}),y(`[render-stack] ${v} \u2014 MISSING: ${m}`);continue}let g=await a.text();await r.saveDocumentAsync(s.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let m=$e(u,l.publisher);je(m,{recursive:!0}),_e($e(m,`${l.package_}@${S}.kan.yml`),g,"utf-8"),$.push({...l,origin:"fetched",versions:[S]}),y(`[render-stack] ${v}@${S} \u2014 fetched from ${C}, installed to cache`)}catch(m){$.push({...l,origin:"fetched",versions:[S]}),y(`[render-stack] ${v}@${S} \u2014 fetched from ${C}, but cache ${u} is NOT WRITABLE (${m.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let C=`fetch failed: ${S.message}`;$.push({...l,origin:"missing",reason:C}),y(`[render-stack] ${v} \u2014 MISSING: ${C}`)}}}let M=k;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await O(c,k);for(let v of w)l.add(F(v));M=new T(k,l)}let A=await new X(s).parseKanonaks(M),oe=new ee(A),G=(c,l)=>Q(A,{publisher:c,package_:l,name:l}).length>0,N;if(e.repository){N=[];for(let c of w){let l=await k.getDocumentsByNamespaceAsync(c.publisher,c.package_);N.push(l.length>0?{...c,origin:"repository",versions:j(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else N=$.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=H(N);for(let c of q)y(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:f,catalog:A,lookRenderer:oe,localNamespaces:b,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:N,warnings:q}})}import{existsSync as Ce,readFileSync as Fe,writeFileSync as Ne,mkdirSync as Me}from"fs";import{join as we}from"path";async function ae(t,e={}){let s=new E,r=Z(t),o=r.kind==="resource"?r.uri.publisher:r.publisher,i=e.log??(()=>{}),f=e.cacheRoot??z(),p=(a,g,m)=>we(f,a,`${g}@${m}.kan.yml`),b=new Set,d=new Set,u=new Map,n=new Y({getFromCache:(a,g,m)=>{let _=p(a,g,m),R=Ce(_)?Fe(_,"utf-8"):null;return R!==null&&b.add(`${a}/${g}`),R},onFetch:(a,g,m,_)=>{d.add(`${a}/${g}`);try{let R=we(f,a);Me(R,{recursive:!0}),Ne(p(a,g,m),_,"utf-8")}catch(R){u.set(`${a}/${g}`,R.message),i(`[render] fetched ${a}/${g}@${m} but cache ${f} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new L(e.fetchFn?{fetchFn:e.fetchFn}:void 0),k;if(r.kind==="resource"){let a=r.uri.version;k=[a?{package_:r.uri.package_,version:`${a.major}.${a.minor}.${a.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let a=r.version;k=[a?{package_:r.package_,version:`${a.major}.${a.minor}.${a.patch}`}:{package_:r.package_}]}else k=(await h.listLatestPackages(o)).map(g=>({package_:g.packageName}));let y=async(a,g,m)=>{try{let _=m?s.buildImport(g,"=",m,a):s.buildImport(g,"*","0.0.0",a),R=await n.getHighestCompatibleVersionAsync(a,_);return R?{doc:R}:{doc:null,error:`${a} did not resolve ${g}${m?`@${m}`:""} (not in its index, or unreachable)`}}catch(_){return{doc:null,error:_.message}}},w=[],$=[];for(let a of k){let{doc:g,error:m}=await y(o,a.package_,a.version);g?w.push(g):m&&$.push(m)}if(w.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${o}".`+($.length>0?` Reasons: ${$.join("; ")}`:""));let j=await new ke(e.fetchFn).getConfig(o).catch(()=>{}),M=W(j),A=j?.render&&j.render.length>0?"publisher-well-known":"universal-default",oe=a=>a.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,m)=>V(m,g)).map(D);i(`[render-stack] resolving ${M.length} ambient look-stack package(s) (contract: ${A}); cache: ${f}`);let G=[],N=[];for(let a of M){let g=F(a),{doc:m,error:_}=await y(a.publisher,a.package_,void 0);if(m){G.push(m);let R=oe([m]),pe=d.has(g)?"fetched":b.has(g)?"cache":"fetched";N.push({...a,origin:pe,versions:R}),i(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else N.push({...a,origin:"missing",reason:_??"unresolved"}),i(`[render-stack] ${g} \u2014 MISSING: ${_??"unresolved"}`)}let q=await O([...w,...G],n),de=new T(n,q),c=await new X(s).parseKanonaks(de),l=new ee(c),v=N.map(a=>a.origin==="missing"||Q(c,{publisher:a.publisher,package_:a.package_,name:a.package_}).length>0?a:{...a,resolvedButNotInCatalog:!0}),I=H(v);for(let a of I)i(`[render-stack] WARNING: ${a}`);let U={contractSource:A,cachePath:f,packages:v,warnings:I},S=new Set,C=new Map;for(let a of await n.getAllDocumentsAsync()){let g=a.metadata.namespace_;if(!g?.version||g.publisher!==o)continue;let m=D(g.version),_=`${g.publisher}/${g.package_}@${m}`;S.add(_);let R=await n.getDocumentContentAsync(_);R!==null&&C.set(`${g.package_}@${m}`,R)}return re({publisher:o,availablePublishers:[o],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:C,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:s,renderStack:r,catalog:o}=t,i=e.explainStylesheet(e.publisherSubject(s)),f=[...i.tokens.entries()].map(([n,h])=>({name:n,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=i.baseStylesheet,b={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},d=new Map;for(let n of o){let h=n.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([n,h])=>({namespace:n,resources:h})).sort((n,h)=>n.namespace.localeCompare(h.namespace));return{publisher:s,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(n=>({package_:F(n),origin:n.origin,...n.versions!==void 0?{versions:n.versions}:{},...n.reason!==void 0?{reason:n.reason}:{},...n.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:n.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:f,baseStylesheet:b,...i.look?{look:{sourceClass:`${i.look.sourceClass.publisher}/${i.look.sourceClass.package_}/${i.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...i.warnings.filter(n=>!r.warnings.includes(n))]}}function Ie(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ie(t){let e=Ie,s=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
2
+ `),o=t.renderStack.packages.map(d=>{let u=d.origin!=="missing"&&!d.resolvedButNotInCatalog,n=d.origin==="missing"?'<span class="bad">MISSING</span>':d.resolvedButNotInCatalog?`<span class="bad">${e(d.origin)} (not in catalog)</span>`:`<span class="good">${e(d.origin)}</span>`,h=d.reason?e(d.reason):e((d.versions??[]).join(", "));return`<tr class="${u?"":"row-bad"}"><td><code>${e(d.package_)}</code></td><td>${n}</td><td>${h}</td></tr>`}).join(`
3
+ `),i=t.stylesheet.baseStylesheet,f=i.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(i.source??"")}</code> (${i.bytes} bytes, ${e(i.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${i.problem?` \u2014 ${e(i.problem)}`:""}${i.candidates.length>0?`<br>candidates considered: ${i.candidates.map(d=>`<code>${e(d)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,p=t.stylesheet.tokens.map(d=>`<tr><td><code>--kan-${e(d.name)}</code></td><td><code>${e(d.value)}</code></td><td><code>${e(d.source)}</code></td><td>${e(d.level)}</td></tr>`).join(`
4
+ `),b=t.catalog.map(d=>`<tr><td><code>${e(d.namespace)}</code></td><td>${d.resources}</td></tr>`).join(`
5
5
  `);return`<!doctype html>
6
6
  <html lang="en">
7
7
  <head>
@@ -21,12 +21,12 @@ import{j as ee}from"../chunk-IHB7UVEH.js";import"../chunk-QHABFCRC.js";import{a
21
21
  .row-bad td { background: #fff5f5; }
22
22
  .meta { color: #666; font-size: .85rem; }
23
23
  .status-banner { font-size: 1.1rem; padding: .5rem 1rem; border-radius: 6px; display: inline-block; margin-bottom: 1rem;
24
- background: ${n?"#ecfdf3":"#fef2f2"}; border: 1px solid ${n?"#0a7d33":"#b91c1c"}; }
24
+ background: ${s?"#ecfdf3":"#fef2f2"}; border: 1px solid ${s?"#0a7d33":"#b91c1c"}; }
25
25
  </style>
26
26
  </head>
27
27
  <body>
28
28
  <h1>Render diagnostics \u2014 ${e(t.publisher)}</h1>
29
- <p class="status-banner">${n?"\u2713 Healthy":`\u2717 ${t.warnings.length} problem(s) found`}</p>
29
+ <p class="status-banner">${s?"\u2713 Healthy":`\u2717 ${t.warnings.length} problem(s) found`}</p>
30
30
  <p class="meta">Machine-readable version: <a href="/.well-known/kanonak-render.json"><code>/.well-known/kanonak-render.json</code></a></p>
31
31
 
32
32
  <h2>Problems</h2>
@@ -37,12 +37,12 @@ ${r}
37
37
  Contract: <code>${e(t.renderStack.contractSource)}</code> \xB7 Package cache: <code>${e(t.renderStack.cachePath)}</code></p>
38
38
  <table>
39
39
  <tr><th>Package</th><th>Origin</th><th>Versions / reason</th></tr>
40
- ${s}
40
+ ${o}
41
41
  </table>
42
42
 
43
43
  <h2>Base stylesheet</h2>
44
44
  <p class="meta">Everything after the <code>:root</code> block in generated CSS comes from a <code>look-styles/base-stylesheet</code> asset in the render catalog.</p>
45
- ${m}
45
+ ${f}
46
46
 
47
47
  <h2>Design tokens (:root)</h2>
48
48
  <p class="meta">Resolved for the publisher landing page. Each token shows which resource in the cascade supplied it.</p>
@@ -58,9 +58,9 @@ ${t.stylesheet.look?`<p><span class="good">\u2713</span> Bands resolve from <cod
58
58
  <p class="meta">Everything the renderer can see for this publisher \u2014 the served packages, their import closure, and the ambient render stack.</p>
59
59
  <table>
60
60
  <tr><th>Package version</th><th>Resources</th></tr>
61
- ${k}
61
+ ${b}
62
62
  </table>
63
63
  </body>
64
- </html>`}var x={".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"},P=(t,e,n,r)=>({status:t,headers:{"Content-Type":e,...r||{}},body:n}),K=t=>P(404,x[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),Ke=t=>({status:301,headers:{Location:t},body:""}),Me=t=>({status:302,headers:{Location:t},body:""});function Ve(t){switch(t.kind){case"exact":return{operator:ne.Exact,version:L(t.major,t.minor,t.patch)};case"minor-pin":return{operator:ne.Compatible,version:L(t.major,t.minor,0)};case"major-pin":return{operator:ne.Major,version:L(t.major,0,0)};default:return{operator:ne.Any,version:L(0,0,0)}}}async function Be(t,e,n,r){if(!r)return null;let s=t.producers?.find(k=>k.canProduce(t.publisher,e));if(!s)return null;let a=await s.resolveVersion(t.publisher,e,Ve(n));if(!a)return null;let m=F(a);if(n.kind!=="exact")return Me(`/${e}/${m}.kan.yml`);let{source:p}=await s.produce(t.publisher,e,a);return P(200,x[".kan.yml"],p)}function xe(t,e,n){let r=t.pkgVersions.get(e);if(!r||r.length===0)return null;switch(n.kind){case"any":return r[0].verStr;case"major-pin":return r.find(s=>s.version.major===n.major)?.verStr??null;case"minor-pin":return r.find(s=>s.version.major===n.major&&s.version.minor===n.minor)?.verStr??null;case"exact":return r.find(s=>s.version.major===n.major&&s.version.minor===n.minor&&s.version.patch===n.patch)?.verStr??null;default:return null}}async function ce(t,e,n=""){let{lookRenderer:r,publisher:s}=t;if(e==="/.well-known/kanonak.json"){let o=fe(s);return t.producers&&t.producers.length>0&&(o.resolveByRedirect=!0),P(200,x[".json"],JSON.stringify(o,null,2))}if(e==="/index.txt"){let o=[...t.localNamespaces].map(h=>h.split("/")[1].replace("@","/")).sort();return P(200,x[".txt"],o.join(`
64
+ </html>`}var x={".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"},P=(t,e,s,r)=>({status:t,headers:{"Content-Type":e,...r||{}},body:s}),K=t=>P(404,x[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),De=t=>({status:301,headers:{Location:t},body:""}),Ke=t=>({status:302,headers:{Location:t},body:""});function Ve(t){switch(t.kind){case"exact":return{operator:ne.Exact,version:B(t.major,t.minor,t.patch)};case"minor-pin":return{operator:ne.Compatible,version:B(t.major,t.minor,0)};case"major-pin":return{operator:ne.Major,version:B(t.major,0,0)};default:return{operator:ne.Any,version:B(0,0,0)}}}async function Ae(t,e,s,r){if(!r)return null;let o=t.producers?.find(b=>b.canProduce(t.publisher,e));if(!o)return null;let i=await o.resolveVersion(t.publisher,e,Ve(s));if(!i)return null;let f=D(i);if(s.kind!=="exact")return Ke(`/${e}/${f}.kan.yml`);let{source:p}=await o.produce(t.publisher,e,i);return P(200,x[".kan.yml"],p)}function Re(t,e,s){let r=t.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(o=>o.version.major===s.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===s.major&&o.version.minor===s.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===s.major&&o.version.minor===s.minor&&o.version.patch===s.patch)?.verStr??null;default:return null}}async function ce(t,e,s=""){let{lookRenderer:r,publisher:o}=t;if(e==="/.well-known/kanonak.json"){let n=fe(o);return t.producers&&t.producers.length>0&&(n.resolveByRedirect=!0),P(200,x[".json"],JSON.stringify(n,null,2))}if(e==="/index.txt"){let n=[...t.localNamespaces].map(h=>h.split("/")[1].replace("@","/")).sort();return P(200,x[".txt"],n.join(`
65
65
  `)+`
66
- `)}if(e==="/.well-known/kanonak-render.json")return P(200,x[".json"],JSON.stringify(te(t),null,2));if(e==="/.well-known/kanonak-render")return P(200,x[".html"],ie(te(t)));if(e==="/"||e==="/index.html"||e==="/index.css"){let o=r.publisherSubject(s);return e==="/index.css"?P(200,x[".css"],r.renderStylesheet(o)):P(200,x[".html"],await r.renderDocument(o,{rootIndex:!0}))}let a=".html",m=!1,p=e;for(let o of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(o)){a=o,m=!0,p=e.slice(0,-o.length);break}let k=!m&&/application\/yaml|text\/yaml/i.test(n),d=p.endsWith("/");d&&p!=="/"&&(p=p.slice(0,-1));let u=ve.parse(p,s);if(!u)return K(e);if(u.kind==="package"){let o=xe(t,u.package_,u.versionSpec);if(!o)return await Be(t,u.package_,u.versionSpec,a===".kan.yml"||k)??K(e);if(a===".kan.yml"||k){let b=t.rawByNsKey.get(`${u.package_}@${o}`);return b!==void 0?P(200,x[".kan.yml"],b):K(e)}let h=t.pkgSelfByVer.get(`${u.package_}@${o}`);if(!h)return K(e);if(a===".css")return P(200,x[".css"],r.renderStylesheet(h));if(!d)return Ke(p+"/");let y=u.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(h)){let b=(t.pkgVersions.get(u.package_)||[]).map($=>$.verStr);return P(200,x[".html"],r.renderPackageVersionList(u.package_,b,h))}return P(200,x[".html"],await r.renderDocument(h,y?{bareOverview:!0}:void 0))}if(u.kind==="resource"){let o=xe(t,u.package_,u.versionSpec);if(!o)return K(e);let h=t.bySubject.get(`${s}/${u.package_}@${o}/${u.name}`);if(!h)return K(e);switch(a){case".css":return P(200,x[".css"],r.renderStylesheet(h));case".svg":return P(200,x[".svg"],await r.renderSvg(h));case".md":{let y=r.renderRawMarkdown(h);return y===void 0?K(e):P(200,x[".md"],y)}default:return P(200,x[".html"],await r.renderDocument(h))}}return K(e)}import{readFileSync as Ee}from"fs";var le=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,n=new Set;if(this.options.root!==void 0){let r=new E;for(let s of J(this.options.root))try{let a=r.parse(Ee(s,"utf-8")).metadata?.namespace_;if(!a?.version)continue;let m=a.version;e.add(`${a.publisher}/${a.package_}@${m.major}.${m.minor}.${m.patch}`),n.add(`${a.publisher}/${a.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:n},this.workspaceIndex}async modelFor(e,n,r){let s=this.getWorkspaceIndex(),a={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},m=n?r?s.exact.has(`${e}/${n}@${r}`):s.pkgs.has(`${e}/${n}`):[...s.pkgs].some(o=>o.startsWith(`${e}/`)),p,k;if(m&&this.options.root!==void 0){let o=this.options.root;p=`ws:${e}`,k=()=>se(o,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let o=n?r?`${e}/${n}@${r}`:`${e}/${n}`:e;p=`rm:${o}`,k=()=>ae(o,a)}let d=this.models.get(p);if(d)return d;let u=await k();return u.lookRenderer.setLinkMode("open-world"),this.models.set(p,u),u}async handle(e,n=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Pe()};let s=r[0];if(!s.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=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),m=!a&&r.length>=2?r[1]:void 0,p=!a&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,k=await this.modelFor(s,m,p),d=e.endsWith("/")&&r.length>1?"/":"",u="/"+r.slice(1).join("/")+d,o=await ce(k,u,n);return o.headers.Location?{...o,headers:{...o.headers,Location:`/${s}${o.headers.Location}`}}:o}};function Pe(){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{V as ClosureScopedRepository,le as RequestRouter,we as UNIVERSAL_RENDER_BASE,te as buildRenderDiagnostics,W as buildRenderStackWarnings,H as deriveImportClosure,Pe as landingPage,ae as loadResourceModel,se as loadServerModel,ie as renderDiagnosticsHtml,C as renderRefKey,T as resolveRenderContract,ce as route};
66
+ `)}if(e==="/.well-known/kanonak-render.json")return P(200,x[".json"],JSON.stringify(te(t),null,2));if(e==="/.well-known/kanonak-render")return P(200,x[".html"],ie(te(t)));if(e==="/"||e==="/index.html"||e==="/index.css"){let n=r.publisherSubject(o);return e==="/index.css"?P(200,x[".css"],r.renderStylesheet(n)):P(200,x[".html"],await r.renderDocument(n,{rootIndex:!0}))}let i=".html",f=!1,p=e;for(let n of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(n)){i=n,f=!0,p=e.slice(0,-n.length);break}let b=!f&&/application\/yaml|text\/yaml/i.test(s),d=p.endsWith("/");d&&p!=="/"&&(p=p.slice(0,-1));let u=ve.parse(p,o);if(!u)return K(e);if(u.kind==="package"){let n=Re(t,u.package_,u.versionSpec);if(!n)return await Ae(t,u.package_,u.versionSpec,i===".kan.yml"||b)??K(e);if(i===".kan.yml"||b){let y=t.rawByNsKey.get(`${u.package_}@${n}`);return y!==void 0?P(200,x[".kan.yml"],y):K(e)}let h=t.pkgSelfByVer.get(`${u.package_}@${n}`);if(!h)return K(e);if(i===".css")return P(200,x[".css"],r.renderStylesheet(h));if(!d)return De(p+"/");let k=u.versionSpec.kind==="any";if(k&&!r.hasDeclaredView(h)){let y=(t.pkgVersions.get(u.package_)||[]).map(w=>w.verStr);return P(200,x[".html"],r.renderPackageVersionList(u.package_,y,h))}return P(200,x[".html"],await r.renderDocument(h,k?{bareOverview:!0}:void 0))}if(u.kind==="resource"){let n=Re(t,u.package_,u.versionSpec);if(!n)return K(e);let h=t.bySubject.get(`${o}/${u.package_}@${n}/${u.name}`);if(!h)return K(e);switch(i){case".css":return P(200,x[".css"],r.renderStylesheet(h));case".svg":return P(200,x[".svg"],await r.renderSvg(h));case".md":{let k=r.renderRawMarkdown(h);return k===void 0?K(e):P(200,x[".md"],k)}default:return P(200,x[".html"],await r.renderDocument(h))}}return K(e)}import{readFileSync as Ee}from"fs";var le=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 E;for(let o of J(this.options.root))try{let i=r.parse(Ee(o,"utf-8")).metadata?.namespace_;if(!i?.version)continue;let f=i.version;e.add(`${i.publisher}/${i.package_}@${f.major}.${f.minor}.${f.patch}`),s.add(`${i.publisher}/${i.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:s},this.workspaceIndex}async modelFor(e,s,r){let o=this.getWorkspaceIndex(),i={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},f=s?r?o.exact.has(`${e}/${s}@${r}`):o.pkgs.has(`${e}/${s}`):[...o.pkgs].some(n=>n.startsWith(`${e}/`)),p,b;if(f&&this.options.root!==void 0){let n=this.options.root;p=`ws:${e}`,b=()=>se(n,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let n=s?r?`${e}/${s}@${r}`:`${e}/${s}`:e;p=`rm:${n}`,b=()=>ae(n,i)}let d=this.models.get(p);if(d)return d;let u=await b();return u.lookRenderer.setLinkMode("open-world"),this.models.set(p,u),u}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:xe()};let o=r[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 i=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),f=!i&&r.length>=2?r[1]:void 0,p=!i&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,b=await this.modelFor(o,f,p),d=e.endsWith("/")&&r.length>1?"/":"",u="/"+r.slice(1).join("/")+d,n=await ce(b,u,s);return n.headers.Location?{...n,headers:{...n.headers,Location:`/${o}${n.headers.Location}`}}:n}};function xe(){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{T as ClosureScopedRepository,le as RequestRouter,Se as UNIVERSAL_RENDER_BASE,te as buildRenderDiagnostics,H as buildRenderStackWarnings,O as deriveImportClosure,xe as landingPage,ae as loadResourceModel,se as loadServerModel,ie as renderDiagnosticsHtml,F as renderRefKey,W as resolveRenderContract,ce as route};
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,J as H,K as I,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-FPUQEPYK.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import"../chunk-ZP6P7HNU.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{u as AmbiguousReferenceRule,A as ClassDefinitionRule,n as ClassHierarchyCycleRule,H as DiamondNameClashRule,C as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,I as KanonakObjectValidator,D as LookSemanticSvgPathRule,B as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,w as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,G as OwlOneOfRule,j as PackageHeaderRule,x as PropertyDomainRule,o as PropertyHierarchyCycleRule,y as PropertyKindRangeConsistencyRule,v as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,z as ReservedNameShadowRule,g as ResourceNamingRule,F as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,E as TxExpressionPathRule,t as UnresolvedPredicateRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
1
+ import{A,B,C,D,E,F,G,J as H,K as I,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-7K5TAJ44.js";import"../chunk-ITKOKDBG.js";import"../chunk-MX3DEXMV.js";import"../chunk-NJ3AZYQD.js";import"../chunk-ZP6P7HNU.js";import"../chunk-6U26UASC.js";import"../chunk-GZPLWII7.js";import"../chunk-7BHDZHJY.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{u as AmbiguousReferenceRule,A as ClassDefinitionRule,n as ClassHierarchyCycleRule,H as DiamondNameClashRule,C as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,I as KanonakObjectValidator,D as LookSemanticSvgPathRule,B as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,w as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,G as OwlOneOfRule,j as PackageHeaderRule,x as PropertyDomainRule,o as PropertyHierarchyCycleRule,y as PropertyKindRangeConsistencyRule,v as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,z as ReservedNameShadowRule,g as ResourceNamingRule,F as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,E as TxExpressionPathRule,t as UnresolvedPredicateRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanonak-protocol/sdk",
3
- "version": "5.1.0",
3
+ "version": "5.3.0",
4
4
  "description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -126,7 +126,7 @@
126
126
  ],
127
127
  "dependencies": {
128
128
  "@kanonak-protocol/canonical": "^0.1.1",
129
- "@kanonak-protocol/types": "^5.1.0",
129
+ "@kanonak-protocol/types": "^5.3.0",
130
130
  "ignore": "^7.0.5",
131
131
  "js-yaml": "^4.1.0",
132
132
  "yaml": "^2.7.0"