@kanonak-protocol/sdk 5.17.1 → 5.19.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,4 +1,4 @@
1
- import{a as lt}from"./chunk-ITKOKDBG.js";import{a as I,b as Fe,c as at,d as G,h as M,k as pt,m as S}from"./chunk-V6KIDED2.js";import{a as nt}from"./chunk-NJ3AZYQD.js";import{j as We,k as it,o as v,p as w,q as z,r as H,s as W,v as st,w as L,x as ct}from"./chunk-SVUMCLK5.js";import{c as f,d as D,j as He,k as Q,l as Y,m as R,n as X,p as P,r as k,t as ee,u as x,v as F,w as y,x as $,y as b,z as q}from"./chunk-YW6P24RF.js";import{a as rt}from"./chunk-FUUTGGJS.js";import{e as U}from"./chunk-2ACBWC7K.js";var te=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 g=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(g||{});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 Xe=class c{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new c;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var oe=class{constructor(e){this.underlying=e;this.repository=new Ze(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 lt(e,this.repository);let t={};return{merged:await new S().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},Ze=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 E(c,e,t){return t?t.getKanonaks():new S().parseKanonaks(new ne(c,e))}async function C(c,e,t){let o=await E(c,e,t),n=Ge(c);return n?o.filter(r=>r instanceof f&&r.namespace===n):[]}async function re(c,e,t){let o=Ge(c);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new S().parseKanonaks(new ne(c,e),r),n=r.authored??[]}return n.filter(r=>r instanceof f&&r.sourceDoc===o)}function Ge(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ne=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 ae=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 ie=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 se=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),d=new u;d.ruleType=this.ruleName,d.severity="Error",d.entityName=n,d.propertyName="type",d.actualValue=p,d.expectedValue=m,d.message=`Invalid property type '${p}'. Use '${m}' instead.`,d.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(d)}}}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 ce=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 lt}from"./chunk-M443OYKT.js";import{a as I,b as Fe,c as at,d as G,h as M,k as pt,m as S}from"./chunk-V6KIDED2.js";import{a as nt}from"./chunk-NJ3AZYQD.js";import{j as We,k as it,o as v,p as w,q as z,r as H,s as W,v as st,w as L,x as ct}from"./chunk-SVUMCLK5.js";import{c as f,d as D,j as He,k as Q,l as Y,m as R,n as X,p as P,r as k,t as ee,u as x,v as F,w as y,x as $,y as b,z as q}from"./chunk-YW6P24RF.js";import{a as rt}from"./chunk-FUUTGGJS.js";import{e as U}from"./chunk-2ACBWC7K.js";var te=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 g=(o=>(o.Info="Info",o.Warning="Warning",o.Error="Error",o))(g||{});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 Xe=class c{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new c;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var oe=class{constructor(e){this.underlying=e;this.repository=new Ze(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 lt(e,this.repository);let t={};return{merged:await new S().parseKanonaks(this.underlying,t),authored:t.authored??[]}})()),this.parsePromise}},Ze=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 E(c,e,t){return t?t.getKanonaks():new S().parseKanonaks(new ne(c,e))}async function C(c,e,t){let o=await E(c,e,t),n=Ge(c);return n?o.filter(r=>r instanceof f&&r.namespace===n):[]}async function re(c,e,t){let o=Ge(c);if(!o)return[];let n;if(t)n=await t.getAuthoredKanonaks();else{let r={};await new S().parseKanonaks(new ne(c,e),r),n=r.authored??[]}return n.filter(r=>r instanceof f&&r.sourceDoc===o)}function Ge(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ne=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 ae=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 ie=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 se=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),d=new u;d.ruleType=this.ruleName,d.severity="Error",d.entityName=n,d.propertyName="type",d.actualValue=p,d.expectedValue=m,d.message=`Invalid property type '${p}'. Use '${m}' instead.`,d.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(d)}}}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 ce=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
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 $t=new Set(["EphemeralPackage"]),pe=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_?(!$t.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.:
@@ -36,17 +36,17 @@ line (let the line run long), or check for an unterminated [[.`,n}};var bt="kano
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 po(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function Z(c,e,t){let o=[];return _e(c,t,{input:e},o),o}function _e(c,e,t,o){if(P(e,M.VarRef)){let a=F(e,M.varName);return a?t[a]:void 0}if(P(e,M.PropertyRead)){let a=$(e,M.readSource),i=a?_e(c,a,t,o):void 0,s=y(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=$(e,M.traverseSource),i=a?_e(c,a,t,o):void 0,s=y(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=$(e,M.step);return l?_e(c,l,{...t,input:p},o):void 0}let n=F(e,M.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of lo(e))_e(c,a,r,o)}function lo(c){let e=[];for(let t of c.statement){let o=t.object;if(o instanceof I)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof I&&e.push(n)}return e}var Le="kanonak.org",Me="look",mo={publisher:Le,package_:Me,name:"semanticSvg"},uo={publisher:Le,package_:Me,name:"tierChip"},fo={publisher:Le,package_:Me,name:"tierIcon"},yo={publisher:Le,package_:Me,name:"tierCard"},go={publisher:Le,package_:Me,name:"tierFull"},ko=[uo,fo,yo,go],je=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new q(e,t));let a=ho(e);if(!a)return n;for(let i of r)i instanceof f&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=$(t,mo);if(!n)return;let r=w(t);if(r)for(let a of ko){let i=$(n,a);if(i)for(let s of Z(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 po(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}function Z(c,e,t){let o=[];return Le(c,t,{input:e},o),o}function Le(c,e,t,o){if(P(e,M.VarRef)){let a=F(e,M.varName);return a?t[a]:void 0}if(P(e,M.PropertyRead)){let a=$(e,M.readSource),i=a?Le(c,a,t,o):void 0,s=y(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=$(e,M.traverseSource),i=a?Le(c,a,t,o):void 0,s=y(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=$(e,M.step);return l?Le(c,l,{...t,input:p},o):void 0}let n=F(e,M.loopVar),r=n?{...t,[n]:void 0}:t;for(let a of lo(e))Le(c,a,r,o)}function lo(c){let e=[];for(let t of c.statement){let o=t.object;if(o instanceof I)e.push(o);else if(Array.isArray(o))for(let n of o)n instanceof I&&e.push(n)}return e}var Me="kanonak.org",Be="look",mo={publisher:Me,package_:Be,name:"semanticSvg"},uo={publisher:Me,package_:Be,name:"tierChip"},fo={publisher:Me,package_:Be,name:"tierIcon"},yo={publisher:Me,package_:Be,name:"tierCard"},go={publisher:Me,package_:Be,name:"tierFull"},ko=[uo,fo,yo,go],je=class{ruleName="LookSemanticSvgPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new q(e,t));let a=ho(e);if(!a)return n;for(let i of r)i instanceof f&&i.namespace===a&&this.checkSemanticSvg(r,i,n);return n}checkSemanticSvg(e,t,o){let n=$(t,mo);if(!n)return;let r=w(t);if(r)for(let a of ko){let i=$(n,a);if(i)for(let s of Z(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 ho(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Ro="kanonak.org",K=(c,e)=>({publisher:Ro,package_:c,name:e}),Ko=K("derivation","look"),bo=K("look","bands"),Vo=K("look","Distribution"),Eo=K("look","StatRow"),vo=K("look","VersionDelta"),Do=K("look","Timeline"),Io=K("look","VersionDiff"),Co=K("look","TimePlot"),So=K("look","ReferenceList"),Po=K("look","Diagram"),jo=K("look","alphaPath"),Oo=K("look","betaPath"),tt=K("look","metricPath"),Et=K("look","lowerPath"),vt=K("look","upperPath"),Dt=K("look","hueBy"),$o=K("look","statPath"),Uo=K("look","laneBy"),It=K("look","labelPath"),wo=K("look","badgePath"),Ao=K("look","mapPath"),xo=K("look","nodeNote"),No=K("look","edgeValue"),To=K("look","stats"),_o=K("look","facets"),Lo=K("look","channels"),Mo=K("look","track"),Bo=K("look","source"),Fo=K("look","relation"),Ho=K("look","entries"),Be=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new q(e,t));let a=Go(e);if(!a)return n;for(let i of r)i instanceof f&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=$(t,Ko);if(!n)return;let r=w(t);if(!r)return;let a=b(n,bo).filter(i=>i instanceof I);for(let i of a)for(let s of this.carriersOf(e,i,r))for(let p of Z(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=$(t,a);s&&n.push({slot:`look.${a.name}`,context:i,expr:s})};if(P(t,Vo))for(let a of[jo,Oo,tt,Et,vt,Dt])r(a,o);if(P(t,vo)&&r(tt,o),P(t,Eo)){let a=b(t,To).filter(i=>i instanceof I);for(let i of a){let s=$(i,$o);s&&n.push({slot:"look.stats[].statPath",context:o,expr:s})}}if(P(t,Do)||P(t,Io)){let a=this.rangeOf(e,o,y(t,Mo));if(a)for(let i of[tt,Et,vt,Dt])r(i,a)}if(P(t,Co)){let a=this.rangeOf(e,o,y(t,Bo));if(a)for(let i of[Uo,It])r(i,a)}if(P(t,So))for(let a of b(t,Ho)){let i=a instanceof I?void 0:Wo(a),s=this.rangeOf(e,o,i);if(s)for(let p of[It,wo])r(p,s)}if(P(t,Po)){let a=b(t,_o).filter(i=>i instanceof I);for(let i of a){let s=this.rangeOf(e,o,y(i,Fo));if(!s)continue;let p=$(i,xo);p&&n.push({slot:"look.facets[].nodeNote",context:s,expr:p});let l=$(i,No);l&&n.push({slot:"look.facets[].edgeValue",context:s,expr:l});let m=b(i,Lo).filter(d=>d instanceof I);for(let d of m){let h=$(d,Ao);h&&n.push({slot:"look.facets[].channels[].mapPath",context:s,expr:h})}}}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 ho(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Ro="kanonak.org",K=(c,e)=>({publisher:Ro,package_:c,name:e}),Ko=K("derivation","look"),bo=K("look","bands"),Vo=K("look","Distribution"),Eo=K("look","StatRow"),vo=K("look","VersionDelta"),Do=K("look","Timeline"),Io=K("look","VersionDiff"),Co=K("look","TimePlot"),So=K("look","ReferenceList"),Po=K("look","Diagram"),jo=K("look","alphaPath"),Oo=K("look","betaPath"),tt=K("look","metricPath"),Et=K("look","lowerPath"),vt=K("look","upperPath"),Dt=K("look","hueBy"),$o=K("look","statPath"),Uo=K("look","laneBy"),It=K("look","labelPath"),wo=K("look","badgePath"),Ao=K("look","mapPath"),xo=K("look","nodeNote"),No=K("look","edgeValue"),To=K("look","stats"),_o=K("look","facets"),Lo=K("look","channels"),Mo=K("look","track"),Bo=K("look","source"),Fo=K("look","relation"),Ho=K("look","entries"),Oe=class{ruleName="LookBandPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new q(e,t));let a=Go(e);if(!a)return n;for(let i of r)i instanceof f&&i.namespace===a&&this.checkDeclaration(r,i,n);return n}checkDeclaration(e,t,o){let n=$(t,Ko);if(!n)return;let r=w(t);if(!r)return;let a=b(n,bo).filter(i=>i instanceof I);for(let i of a)for(let s of this.carriersOf(e,i,r))for(let p of Z(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=$(t,a);s&&n.push({slot:`look.${a.name}`,context:i,expr:s})};if(P(t,Vo))for(let a of[jo,Oo,tt,Et,vt,Dt])r(a,o);if(P(t,vo)&&r(tt,o),P(t,Eo)){let a=b(t,To).filter(i=>i instanceof I);for(let i of a){let s=$(i,$o);s&&n.push({slot:"look.stats[].statPath",context:o,expr:s})}}if(P(t,Do)||P(t,Io)){let a=this.rangeOf(e,o,y(t,Mo));if(a)for(let i of[tt,Et,vt,Dt])r(i,a)}if(P(t,Co)){let a=this.rangeOf(e,o,y(t,Bo));if(a)for(let i of[Uo,It])r(i,a)}if(P(t,So))for(let a of b(t,Ho)){let i=a instanceof I?void 0:Wo(a),s=this.rangeOf(e,o,i);if(s)for(let p of[It,wo])r(p,s)}if(P(t,Po)){let a=b(t,_o).filter(i=>i instanceof I);for(let i of a){let s=this.rangeOf(e,o,y(i,Fo));if(!s)continue;let p=$(i,xo);p&&n.push({slot:"look.facets[].nodeNote",context:s,expr:p});let l=$(i,No);l&&n.push({slot:"look.facets[].edgeValue",context:s,expr:l});let m=b(i,Lo).filter(d=>d instanceof I);for(let d of m){let h=$(d,Ao);h&&n.push({slot:"look.facets[].channels[].mapPath",context:s,expr:h})}}}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 Wo(c){let e=c.subject;return e&&typeof e.name=="string"?e:void 0}function Go(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var $e="kanonak.org",Ue="view",Yo={publisher:$e,package_:Ue,name:"bind"},qo={publisher:$e,package_:Ue,name:"produces"},zo={publisher:$e,package_:Ue,name:"projections"},Xo={publisher:$e,package_:Ue,name:"where"},Zo={publisher:$e,package_:Ue,name:"value"},Jo={publisher:$e,package_:Ue,name:"as"},Oe=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new q(e,t));let a=tn(e);if(!a)return n;for(let i of r)i instanceof f&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=y(t,Yo);if(!n)return;let r=y(t,qo),a=0;for(let s of en(e,b(t,zo))){let p=$(s,Zo);if(p)for(let m of Z(e,n,p))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=y(s,Jo);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 Qo(t,Xo)){for(let p of Z(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 Wo(c){let e=c.subject;return e&&typeof e.name=="string"?e:void 0}function Go(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Ue="kanonak.org",we="view",Yo={publisher:Ue,package_:we,name:"bind"},qo={publisher:Ue,package_:we,name:"produces"},zo={publisher:Ue,package_:we,name:"projections"},Xo={publisher:Ue,package_:we,name:"where"},Zo={publisher:Ue,package_:we,name:"value"},Jo={publisher:Ue,package_:we,name:"as"},$e=class{ruleName="TxExpressionPath";async validateAsync(e,t,o){let n=[],r;o?r=await o.getKanonaks():r=await new S().parseKanonaks(new q(e,t));let a=tn(e);if(!a)return n;for(let i of r)i instanceof f&&i.namespace===a&&this.checkView(r,i,n);return n}checkView(e,t,o){let n=y(t,Yo);if(!n)return;let r=y(t,qo),a=0;for(let s of en(e,b(t,zo))){let p=$(s,Zo);if(p)for(let m of Z(e,n,p))o.push(this.toError(t.name,`view.projections[${a}].value`,n,m));let l=y(s,Jo);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 Qo(t,Xo)){for(let p of Z(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 Qo(c,e){let t=$(c,e);return t?[t]:b(c,e).filter(o=>o instanceof I)}function en(c,e){let t=[];for(let o of e)if(o instanceof I)t.push(o);else if(o instanceof D){let n=k(c,o.subject);n&&t.push(n)}return t}function tn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ze="kanonak.org",on="core-shacl",A=c=>({publisher:ze,package_:on,name:c}),nn=A("NodeShape"),rn=A("PropertyShape"),an=A("targetClass"),sn=A("property"),cn=A("path"),pn=A("minCount"),ln=A("maxCount"),mn=A("datatype"),un=A("class"),Ct=A("in"),dn=A("pattern"),fn=A("flags"),yn=A("minLength"),gn=A("maxLength"),kn=A("minInclusive"),hn=A("maxInclusive"),Rn=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),St=c=>c,Ae=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Kn(e);if(!a)return n;let i=new Set;for(let s of r){if(!(s instanceof f)||s.namespace!==a||!P(s,nn))continue;let p=y(s,an);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.",J(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 b(s,sn)){let m;if(l instanceof I)m=l;else if(l instanceof D){let d=k(r,l.subject);d&&(m=d,i.add(R(l.subject)))}m&&this.checkPropertyShape(r,s.name,m,p??void 0,n)}}for(let s of r){if(!(s instanceof f)||s.namespace!==a||!P(s,rn))continue;let p=w(s);p&&i.has(R(p))||this.checkPropertyShape(r,s.name,s,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=y(o,cn);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=k(e,a),s=i?W(e,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.`,J(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.",J(a)));let p=y(o,mn),l=y(o,un);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.",J(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.",J(l)));let m=we(x(o,pn)),d=we(x(o,ln));this.checkOrder(t,"minCount",m,"maxCount",d,r);let h=we(x(o,yn)),V=we(x(o,gn));this.checkOrder(t,"minLength",h,"maxLength",V,r);let T=we(x(o,kn)),j=we(x(o,hn));this.checkOrder(t,"minInclusive",T,"maxInclusive",j,r);let O=F(o,dn);if(O!==void 0){let B=F(o,fn);try{new RegExp(O,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}')`:"")+`: ${O}`,"Provide a valid regular expression and flags.",O))}}if(ee(o,Ct)&&b(o,Ct).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;_&&((O!==void 0||h!==void 0||V!==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.",J(a))),(T!==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.",J(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=k(e,t);return o?v.isClassType(St(o)):!1}resolvesToDatatype(e,t){if(t.publisher===ze&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=k(e,t);return o?v.isDatatypeType(St(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===ze&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===ze&&e.package_==="core-xsd"&&Rn.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 we(c){return typeof c=="number"?c:void 0}function J(c){return`${c.publisher}/${c.package_}/${c.name}`}function Kn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Pt={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},bn=c=>c,xe=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 f)||i.namespace!==a||!ee(i,Pt))continue;let s=b(i,Pt);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 Fe)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 D){let l=k(r,p.subject);l&&v.isSchemaDefinitionType(bn(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 En="kanonak.org",vn="core-shacl",N=c=>({publisher:En,package_:vn,name:c}),Dn=N("NodeShape"),In=N("targetClass"),Cn=N("property"),Sn=N("path"),Pn=N("minCount"),jn=N("maxCount"),On=N("in"),$n=N("pattern"),Un=N("flags"),wn=N("minLength"),An=N("maxLength"),xn=N("minInclusive"),Nn=N("maxInclusive"),Tn=N("message");function Ne(c){return typeof c=="number"?c:void 0}function _n(c){let e={},t=Ne(x(c,Pn)),o=Ne(x(c,jn));t!==void 0&&(e.minCount=t),o!==void 0&&(e.maxCount=o);let n=Ne(x(c,wn)),r=Ne(x(c,An));n!==void 0&&(e.minLength=n),r!==void 0&&(e.maxLength=r);let a=Ne(x(c,xn)),i=Ne(x(c,Nn));a!==void 0&&(e.minInclusive=a),i!==void 0&&(e.maxInclusive=i);let s=F(c,$n);if(s!==void 0){let m=F(c,Un);e.pattern=m!==void 0?{regex:s,flags:m}:{regex:s}}let p=b(c,On).filter(m=>m instanceof Fe).map(m=>m.value);p.length>0&&(e.enumValues=p);let l=F(c,Tn);return l!==void 0&&(e.message=l),e}function Ln(c,e){let t=[];for(let o of b(e,Cn))if(o instanceof I)t.push(o);else if(o instanceof D){let n=k(c,o.subject);n&&t.push(n)}return t}function jt(c){let e=new Map;for(let t of c){if(!(t instanceof f)||!P(t,Dn))continue;let o=y(t,In);if(!o)continue;let n=R(o);for(let r of Ln(c,t)){let a=y(r,Sn);if(!a)continue;let i={pathKey:R(a),constraints:_n(r)},s=e.get(n);s?s.push(i):e.set(n,[i])}}return e}function Mn(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=R(t),n=!1,r={};for(let a=e.length-1;a>=0;a--){let i=c.get(R(e[a]));if(i)for(let s of i)s.pathKey===o&&(n=!0,Mn(r,s.constraints))}if(n)return r.cardinality=r.maxCount===1?"single":"list",r.required=(r.minCount??0)>=1,r}var Bn=c=>c,Fn=new rt("kanonak.org","core-rdf","Resource"),Te=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Hn(e);if(!a)return n;let i=jt(r);for(let s of r){if(!(s instanceof f)||s.namespace!==a||!v.isClassType(Bn(s)))continue;let p=w(s);if(!p)continue;let l=z(r,p),m=R(p),d=new Set(l.map(V=>R(V)));d.delete(m),d.delete(R(Fn));let h=new Map;for(let V of st(r,p)){if(!V.domains.some(O=>d.has(R(O))))continue;let j=h.get(V.uri.name);j?j.push(V):h.set(V.uri.name,[V])}for(let[V,T]of h){if(T.length<2)continue;let j=_=>Ot(i,l,_.uri)?.cardinality,O=new Set(T.map(_=>_.range?R(_.range):void 0).filter(_=>_!==void 0)),B=new Set(T.map(j).filter(_=>_!==void 0));O.size<=1&&B.size<=1||n.push(this.toError(s.name,V,T,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 Qo(c,e){let t=$(c,e);return t?[t]:b(c,e).filter(o=>o instanceof I)}function en(c,e){let t=[];for(let o of e)if(o instanceof I)t.push(o);else if(o instanceof D){let n=k(c,o.subject);n&&t.push(n)}return t}function tn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ze="kanonak.org",on="core-shacl",A=c=>({publisher:ze,package_:on,name:c}),nn=A("NodeShape"),rn=A("PropertyShape"),an=A("targetClass"),sn=A("property"),cn=A("path"),pn=A("minCount"),ln=A("maxCount"),mn=A("datatype"),un=A("class"),Ct=A("in"),dn=A("pattern"),fn=A("flags"),yn=A("minLength"),gn=A("maxLength"),kn=A("minInclusive"),hn=A("maxInclusive"),Rn=new Set(["decimal","integer","int","long","short","byte","float","double","nonNegativeInteger","positiveInteger","negativeInteger","nonPositiveInteger","unsignedInt","unsignedLong","unsignedShort","unsignedByte"]),St=c=>c,xe=class{ruleName="ShaclShape";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Kn(e);if(!a)return n;let i=new Set;for(let s of r){if(!(s instanceof f)||s.namespace!==a||!P(s,nn))continue;let p=y(s,an);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.",J(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 b(s,sn)){let m;if(l instanceof I)m=l;else if(l instanceof D){let d=k(r,l.subject);d&&(m=d,i.add(R(l.subject)))}m&&this.checkPropertyShape(r,s.name,m,p??void 0,n)}}for(let s of r){if(!(s instanceof f)||s.namespace!==a||!P(s,rn))continue;let p=w(s);p&&i.has(R(p))||this.checkPropertyShape(r,s.name,s,void 0,n)}return n}checkPropertyShape(e,t,o,n,r){let a=y(o,cn);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=k(e,a),s=i?W(e,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.`,J(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.",J(a)));let p=y(o,mn),l=y(o,un);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.",J(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.",J(l)));let m=Ae(x(o,pn)),d=Ae(x(o,ln));this.checkOrder(t,"minCount",m,"maxCount",d,r);let h=Ae(x(o,yn)),V=Ae(x(o,gn));this.checkOrder(t,"minLength",h,"maxLength",V,r);let T=Ae(x(o,kn)),j=Ae(x(o,hn));this.checkOrder(t,"minInclusive",T,"maxInclusive",j,r);let O=F(o,dn);if(O!==void 0){let B=F(o,fn);try{new RegExp(O,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}')`:"")+`: ${O}`,"Provide a valid regular expression and flags.",O))}}if(ee(o,Ct)&&b(o,Ct).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;_&&((O!==void 0||h!==void 0||V!==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.",J(a))),(T!==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.",J(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=k(e,t);return o?v.isClassType(St(o)):!1}resolvesToDatatype(e,t){if(t.publisher===ze&&t.package_==="core-rdf"&&t.name==="Literal")return!0;let o=k(e,t);return o?v.isDatatypeType(St(o)):!1}isNumericDatatypeRange(e){return!e||e.publisher===ze&&e.package_==="core-rdf"&&e.name==="Literal"?!0:e.publisher===ze&&e.package_==="core-xsd"&&Rn.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 Ae(c){return typeof c=="number"?c:void 0}function J(c){return`${c.publisher}/${c.package_}/${c.name}`}function Kn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var Pt={publisher:"kanonak.org",package_:"core-owl",name:"oneOf"},bn=c=>c,Ne=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 f)||i.namespace!==a||!ee(i,Pt))continue;let s=b(i,Pt);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 Fe)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 D){let l=k(r,p.subject);l&&v.isSchemaDefinitionType(bn(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 En="kanonak.org",vn="core-shacl",N=c=>({publisher:En,package_:vn,name:c}),Dn=N("NodeShape"),In=N("targetClass"),Cn=N("property"),Sn=N("path"),Pn=N("minCount"),jn=N("maxCount"),On=N("in"),$n=N("pattern"),Un=N("flags"),wn=N("minLength"),An=N("maxLength"),xn=N("minInclusive"),Nn=N("maxInclusive"),Tn=N("message");function Te(c){return typeof c=="number"?c:void 0}function _n(c){let e={},t=Te(x(c,Pn)),o=Te(x(c,jn));t!==void 0&&(e.minCount=t),o!==void 0&&(e.maxCount=o);let n=Te(x(c,wn)),r=Te(x(c,An));n!==void 0&&(e.minLength=n),r!==void 0&&(e.maxLength=r);let a=Te(x(c,xn)),i=Te(x(c,Nn));a!==void 0&&(e.minInclusive=a),i!==void 0&&(e.maxInclusive=i);let s=F(c,$n);if(s!==void 0){let m=F(c,Un);e.pattern=m!==void 0?{regex:s,flags:m}:{regex:s}}let p=b(c,On).filter(m=>m instanceof Fe).map(m=>m.value);p.length>0&&(e.enumValues=p);let l=F(c,Tn);return l!==void 0&&(e.message=l),e}function Ln(c,e){let t=[];for(let o of b(e,Cn))if(o instanceof I)t.push(o);else if(o instanceof D){let n=k(c,o.subject);n&&t.push(n)}return t}function jt(c){let e=new Map;for(let t of c){if(!(t instanceof f)||!P(t,Dn))continue;let o=y(t,In);if(!o)continue;let n=R(o);for(let r of Ln(c,t)){let a=y(r,Sn);if(!a)continue;let i={pathKey:R(a),constraints:_n(r)},s=e.get(n);s?s.push(i):e.set(n,[i])}}return e}function Mn(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=R(t),n=!1,r={};for(let a=e.length-1;a>=0;a--){let i=c.get(R(e[a]));if(i)for(let s of i)s.pathKey===o&&(n=!0,Mn(r,s.constraints))}if(n)return r.cardinality=r.maxCount===1?"single":"list",r.required=(r.minCount??0)>=1,r}var Bn=c=>c,Fn=new rt("kanonak.org","core-rdf","Resource"),_e=class{ruleName="DiamondNameClash";async validateAsync(e,t,o){let n=[],r=o?await o.getKanonaks():await new S().parseKanonaks(t),a=Hn(e);if(!a)return n;let i=jt(r);for(let s of r){if(!(s instanceof f)||s.namespace!==a||!v.isClassType(Bn(s)))continue;let p=w(s);if(!p)continue;let l=z(r,p),m=R(p),d=new Set(l.map(V=>R(V)));d.delete(m),d.delete(R(Fn));let h=new Map;for(let V of st(r,p)){if(!V.domains.some(O=>d.has(R(O))))continue;let j=h.get(V.uri.name);j?j.push(V):h.set(V.uri.name,[V])}for(let[V,T]of h){if(T.length<2)continue;let j=_=>Ot(i,l,_.uri)?.cardinality,O=new Set(T.map(_=>_.range?R(_.range):void 0).filter(_=>_!==void 0)),B=new Set(T.map(j).filter(_=>_!==void 0));O.size<=1&&B.size<=1||n.push(this.toError(s.name,V,T,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 Hn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ot=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new nt,this.documentRules=[new ae,new ie,new se,new ce,new pe],this.repositoryRules=[new le,new me,new ue,new de,new fe,new ye,new ge,new ke,new he,new Re,new Ke,new be,new Ee,new ve,new De,new Ie,new Ce,new Se,new Pe,new je,new Be,new Oe,new Ae,new xe,new Te]}async validateAsync(e,t,o){let n=new te;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 oe(new ne(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 oe(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 te;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{te as a,g as b,u as c,Xe as d,oe as e,ae as f,ie as g,se as h,ce as i,pe as j,le as k,me as l,ue as m,de as n,fe as o,ye as p,ge as q,ke as r,he as s,Re as t,Ke as u,be as v,Ee as w,ve as x,De as y,Ie as z,Ce as A,Se as B,Pe as C,je as D,Oe as E,Ae as F,xe as G,jt as H,Ot as I,Te as J,ot as K};
63
+ \u2022 make the ranges/cardinalities compatible (identical) if they are meant to be the same property.`,i}};function Hn(c){let e=c.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${U(e.version)}`}var ot=class{parser;documentRules;repositoryRules;includeWarnings=!0;constructor(e){this.parser=e??new nt,this.documentRules=[new ae,new ie,new se,new ce,new pe],this.repositoryRules=[new le,new me,new ue,new de,new fe,new ye,new ge,new ke,new he,new Re,new Ke,new be,new Ee,new ve,new De,new Ie,new Ce,new Se,new Pe,new je,new Oe,new $e,new xe,new Ne,new _e]}async validateAsync(e,t,o){let n=new te;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 oe(new ne(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 oe(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 te;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{te as a,g as b,u as c,Xe as d,oe as e,ae as f,ie as g,se as h,ce as i,pe as j,le as k,me as l,ue as m,de as n,fe as o,ye as p,ge as q,ke as r,he as s,Re as t,Ke as u,be as v,Ee as w,ve as x,De as y,Ie as z,Ce as A,Se as B,Pe as C,je as D,Oe as E,$e as F,xe as G,Ne as H,jt as I,Ot as J,_e as K,ot as L};
package/dist/index.d.ts CHANGED
@@ -15,7 +15,9 @@ export type { IStatement } from './statements/index.js';
15
15
  export type { MarkdownLink } from './statements/index.js';
16
16
  export { Statement, ScalarStatement, StringStatement, NumberStatement, BooleanStatement, ReferenceStatement, EmbeddedStatement, ListStatement, MarkdownStatement } from './statements/index.js';
17
17
  export { extractMarkdownLinks, findMalformedReferences, type RawMarkdownLink, type MalformedMarkdownLink, } from './parsing/extractMarkdownLinks.js';
18
- export { OntologyValidationResult, OntologyValidationError, ValidationSeverity, ValidationContext, ValidationCache, KanonakObjectValidator, NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, PackageHeaderRule, EmbeddedKanonakTypeRule, ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, UnresolvedPredicateRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyKindRangeConsistencyRule, ReservedNameShadowRule, ClassDefinitionRule, MarkdownLinkRule } from './validation/index.js';
18
+ export { OntologyValidationResult, OntologyValidationError, ValidationSeverity, ValidationContext, ValidationCache, KanonakObjectValidator, NamespacePrefixRule, ResourceNamingRule, PropertyTypeSpecificityRule, SubjectKanonakTypeRequiredRule, PackageHeaderRule, EmbeddedKanonakTypeRule, ImportExistenceRule, UnresolvedReferenceRule, ClassHierarchyCycleRule, PropertyHierarchyCycleRule, PropertyRangeRequiredRule, SubClassOfReferenceRule, SubPropertyOfReferenceRule, NamespaceImportCycleRule, UnresolvedPredicateRule, AmbiguousReferenceRule, PropertyRangeReferenceRule, ObjectPropertyValueValidationRule, PropertyDomainRule, PropertyKindRangeConsistencyRule, ReservedNameShadowRule, ClassDefinitionRule, MarkdownLinkRule, DisplayLensScopeRule, LookSemanticSvgPathRule, LookBandPathRule, TxExpressionPathRule, ShaclShapeRule, OwlOneOfRule, DiamondNameClashRule } from './validation/index.js';
19
+ export { scopeFromRepositoryAsync, scopeFromCatalog, scopeFromDocumentAsync, buildShapesModel, lowerConstraint, foldFlagsIntoPattern, evaluateConformance, buildReportPackageAsync, } from './shacl/index.js';
20
+ export type { ConformanceScope, ShaclNodeShapeModel, ShaclPropertyConstraint, ShaclNodeKind, ShaclSeverity, LoweredCheck, LoweredExprNode, ShaclConformanceResult, ShaclFinding, } from './shacl/index.js';
19
21
  export type { IKanonakObjectValidator, DocumentValidationResult, IDocumentValidationRule, IRepositoryValidationRule } from './validation/index.js';
20
22
  export type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
21
23
  export type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as jr,b as Ar,c as Cr,d as Sr,e as L}from"./chunk-V3IPBWWU.js";import{a as te,b as oe,c as ae}from"./chunk-35A2VF5S.js";import{a as xn,c as F,e as ie,h as se,i as ce,j as Kn}from"./chunk-4PY3JJH3.js";import{a as Ir,b as vr,c as Vr,d as gn,e as hn,f as Pn,g as bn,h as Rn,i as wn,j as In,k as T,l as vn,m as Vn}from"./chunk-QLVKAGUU.js";import{a as En}from"./chunk-LYSCTQC2.js";import"./chunk-QHABFCRC.js";import{a as Se,b as De,c as Ue,d as Oe,e as _e,f as qe,g as Ge,h as Xe,i as Ye}from"./chunk-RLQFTA5D.js";import{a as Me,b as Ne,c as $e,d as Le,e as Fe,f as Te,h as ze,i as Z,j as Q,k as ee,l as re,m as Be,n as We}from"./chunk-W35FCNM7.js";import{a as Ce}from"./chunk-4NO7MHS7.js";import{a as Ur,b as Or,c as _r,d as Mr}from"./chunk-5NH5XDGO.js";import{a as Nr,b as Lr}from"./chunk-PEUTCG3B.js";import{a as $r}from"./chunk-PEJALHXK.js";import{a as He}from"./chunk-SC5M74NM.js";import{A as yn,B as kn,K as fn,a as Fr,b as Tr,c as zr,d as Br,e as Hr,f as Wr,g as qr,h as Gr,i as Xr,j as Yr,k as Jr,l as Zr,m as Qr,n as en,o as rn,p as nn,q as tn,r as on,s as an,t as sn,u as cn,v as pn,w as un,x as ln,y as dn,z as mn}from"./chunk-Q6XQ5IXW.js";import"./chunk-ITKOKDBG.js";import{a as f,b as er,c as pr,i as wr,j as Er,k as xr,l as Kr,m as E}from"./chunk-V6KIDED2.js";import{a as P}from"./chunk-NJ3AZYQD.js";import{a as ur,b as lr,c as M,d as dr,e as R,f as mr,g as yr,i as kr,m as fr,o as gr,p as m,q as hr,v as Pr,w as br,x as Rr}from"./chunk-SVUMCLK5.js";import{a as Je,b as Ze,c as k,d as b,e as rr,f as nr,g as tr,h as or,i as ar,j as ir,k as sr,l as cr,r as j,w,x as N,y as $,z as ne}from"./chunk-YW6P24RF.js";import{a as Qe}from"./chunk-FUUTGGJS.js";import{a as xe,b as _,c as V,d as Ke,e as y,f as Ie,g as ve,h as Ve,i as je,j as Ae}from"./chunk-2ACBWC7K.js";import{a as Dr}from"./chunk-ODIECDN7.js";import{VersionOperator as $t}from"@kanonak-protocol/types/document/models/enums";import*as z from"js-yaml";import{VersionOperator as pe}from"@kanonak-protocol/types/document/models/enums";var jn="0.0.0",g=class{constructor(e,r=new P,n){this.repository=e;this.parser=r;this.objectParser=n??new E(this.parser)}repository;parser;objectParser;imports(){return new x}serializeValue(e,r){return de(e,r)}async buildContentAddressed(e){let r=e.book.toImports(),n=await this.hashBody(e.publisher,r,e.body),t=B(n),a={type:"EphemeralPackage",publisher:e.publisher,imports:r};e.contentHashProperty&&(a[e.contentHashProperty]=n),Object.assign(a,e.header??{}),a.imports=r;let i={[t]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:le(s),contentHash:n,packageName:t,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let r=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:r},t;e.contentHashProperty&&(t=await this.hashBody(e.publisher,r,e.body),n[e.contentHashProperty]=t),Object.assign(n,e.header??{}),n.imports=r;let a={[e.name]:n,...e.body},i=this.dump(a),s={yaml:i,byteCount:le(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return t!==void 0&&(s.contentHash=t),s}dump(e){return z.dump(e,{lineWidth:-1})}async hashBody(e,r,n){let t={[ue]:{type:"EphemeralPackage",publisher:e,imports:r},...n},a=this.parser.parse(z.dump(t,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new ne(a,this.repository))).filter(u=>u instanceof k&&u.namespace===i&&u.name!==ue);for(let u of c)u.namespace="ephemeral";return T(c)}},ue="__pkgbuilder_probe__";function le(o){return new TextEncoder().encode(o).length}function B(o){let e="sha256:",r=o.startsWith(e)?e.length:0;return`q-${o.slice(r,r+16)}`}var x=class{byKey=new Map;aliases=new Set;ensure(e,r,n,t,a=pe.Major){let i=`${e}/${r}@${n}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(t);return this.byKey.set(i,{publisher:e,package_:r,version:n,alias:c,match:a}),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_,y(e.version),e.package_)}.${e.name}`}refLatest(e,r,n,t){return`${this.ensure(e,r,jn,t??r,pe.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let t=e.get(n.publisher)??[];t.push(n),e.set(n.publisher,t)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((t,a)=>t.package_<a.package_?-1:1).map(t=>({package:t.package_,match:_(t.match),version:t.version,alias:t.alias}))}))}uniqueAlias(e){let r=K(e)||"pkg",n=r,t=2;for(;this.aliases.has(n);)n=`${r}${t++}`;return this.aliases.add(n),n}};function de(o,e){if(o!=null){if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(o instanceof b)return e.ref(o.subject);if(Array.isArray(o)){let r=o.map(n=>de(n,e)).filter(n=>n!==void 0);return r.length>0?r:void 0}if(o instanceof f)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(An(o))throw new Error(`Value produced a bare URI without a version (${o.publisher}/${o.package_}/${o.name}); cannot serialize it as a reference.`)}}function K(o){return o.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function An(o){return typeof o=="object"&&o!==null&&typeof o.publisher=="string"&&typeof o.package_=="string"&&typeof o.name=="string"}var A=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,r){return this.producers.find(n=>n.canProduce(e,r))}async produceCached(e,r,n,t){let a=`${r}/${n}@${y(t)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(r,n,t);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,r){let n=this.producerFor(e,r.packageName);if(!n)return null;let t={operator:r.versionOperator,version:r.version},a=await n.resolveVersion(e,r.packageName,t);return a?this.produceCached(n,e,r.packageName,a):null}async getDocumentAsync(e){let r;try{r=M(e)}catch{return null}if(r.kind!=="package"||!r.version)return null;let n=this.producerFor(r.publisher,r.package_);return n?this.produceCached(n,r.publisher,r.package_,r.version):null}async getDocumentsByNamespaceAsync(e,r){return Array.from(this.produced.values()).filter(n=>{let t=n.metadata.namespace_;return t!=null&&t.publisher===e&&t.package_===r})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,r){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,r){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 H={async authorize(){return{allowed:!0}}},W={async record(){}},I=class extends Error{constructor(r,n){let t=`${r.publisher}/${r.package_}${r.version?`@${r.version.major}.${r.version.minor}.${r.version.patch}`:""}`;super(`Not entitled to produce ${t}${n?`: ${n}`:""}`);this.address=r;this.reason=n;this.name="EntitlementDeniedError"}address;reason},C=class{inner;ctx;policy;meter;constructor(e,r,n=H,t=W){this.inner=e,this.ctx=r,this.policy=n,this.meter=t}canProduce(e,r){return this.inner.canProduce(e,r)}async resolveVersion(e,r,n){return await this.assertAllowed({publisher:e,package_:r,version:n.version}),this.inner.resolveVersion(e,r,n)}async produce(e,r,n){let t={publisher:e,package_:r,version:n};await this.assertAllowed(t);let a=await this.inner.produce(e,r,n);return await this.meter.record(this.ctx,t,a),a}async assertAllowed(e){let r=await this.policy.authorize(this.ctx,e);if(!r.allowed)throw new I(e,r.reason)}};var p="kanonak.org",d="view",me="core-kanonak",Cn={publisher:p,package_:d,name:"rootView"},Sn={publisher:p,package_:d,name:"bind"},Dn={publisher:p,package_:d,name:"produces"},Un={publisher:p,package_:d,name:"projections"},On={publisher:p,package_:d,name:"where"},_n={publisher:p,package_:d,name:"value"},Mn={publisher:p,package_:d,name:"as"},S=class{constructor(e,r=new P){this.repository=e;this.parser=r;this.objectParser=new E(this.parser),this.builder=new g(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,r={}){let n=await this.objectParser.parseKanonaks(this.repository),t=this.resolveView(n,e),a=w(t,Sn);if(!a)throw new Error(`View ${t.namespace}/${t.name} declares no view.bind; cannot materialize.`);let i=w(t,Dn);if(!i)throw new Error(`View ${t.namespace}/${t.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 s=Nn(t),c=ye(n,p,me),u=ye(n,p,d),l=this.builder.imports(),D=l.ensure(p,me,c,"ck"),fe=l.ensure(p,d,u,"v"),ge=l.ref(i),he=new ce(this.repository,this.parser,this.objectParser),q=new ie(he,n),Pe=this.readProjections(n,t),be=Fn(t,On),Re=this.findInstances(n,a,await this.reason(r)),G={},we=new Set;for(let v of Re){if(!await this.passesWhere(q,n,be,v))continue;let O={type:ge};for(let Y of Pe){let Ee=await this.evaluateValue(q,n,Y.value,v),J=this.builder.serializeValue(ke(Ee),l);J!==void 0&&(O[l.ref(Y.as)]=J)}let X=m(v);X&&(O[`${fe}.derivedFrom`]=l.ref(X)),G[this.rowName(v,we)]=O}let U={};r.resolvedAt&&(U[`${D}.resolvedAt`]=r.resolvedAt),r.invocationId&&(U[`${D}.id`]=r.invocationId);let h=await this.builder.buildContentAddressed({publisher:s,book:l,body:G,contentHashProperty:`${D}.contentHash`,header:U});return{yaml:h.yaml,contentHash:h.contentHash,packageName:h.packageName,publisher:h.publisher,rowCount:h.resourceCount}}resolveView(e,r){let n=j(e,r);if(!n)throw new Error(`View ${r.publisher}/${r.package_}/${r.name} not found in the catalog.`);let t=w(n,Cn);if(t){let a=j(e,t);if(!a)throw new Error(`ViewPackage ${r.name} names rootView ${t.name}, which is not in the catalog.`);return a}return n}readProjections(e,r){let n=[];for(let t of $(r,Un)){let a=t instanceof f?t:t instanceof b?j(e,t.subject):void 0;if(!a)continue;let i=N(a,_n),s=w(a,Mn);i&&s&&n.push({value:i,as:s})}return n}async reason(e){return new L({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,r,n){let t=Ln(e),a=[],i=new Set;for(let s of n.getInstancesOfClass(r)){if(i.has(s))continue;i.add(s);let c=t.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=R(m(s)),l=R(m(c));return u<l?-1:u>l?1:0}),a}async passesWhere(e,r,n,t){for(let a of n){let i=await this.evaluateValue(e,r,a,t);if(!Tn(i))return!1}return!0}async evaluateValue(e,r,n,t){let a=se(n,"view-projection",{catalog:r,depth:0}),i=new Map([["input",t]]);return e.evaluate(a,i)}rowName(e,r){let n=K(e.name)||"row",t=n,a=2;for(;r.has(t);)t=`${n}-${a++}`;return r.add(t),t}};function ke(o){return F(o)?o.value:Array.isArray(o)?o.map(ke):o}function Nn(o){let e=m(o);if(!e)throw new Error(`Could not derive a publisher from view ${o.namespace}/${o.name}.`);return e.publisher}function ye(o,e,r){let n=$n(o,e,r);if(!n)throw new Error(`Package ${e}/${r} is not in the catalog; it must be importable to materialize a view.`);return n}function $n(o,e,r){let n;for(let t of o){if(!(t instanceof k))continue;let a=m(t);!a||a.publisher!==e||a.package_!==r||!a.version||(!n||V(a.version,n)>0)&&(n=a.version)}return n?y(n):void 0}function Ln(o){let e=new Map,r=new Map;for(let n of o){if(!(n instanceof k))continue;let t=m(n);if(!t||!t.version)continue;let a=R(t),i=r.get(a);(!i||V(t.version,i)>0)&&(r.set(a,t.version),e.set(a,n))}return e}function Fn(o,e){let r=N(o,e);return r?[r]:$(o,e).filter(n=>n instanceof f)}function Tn(o){return o===!0?!0:o===!1||o===void 0||o===null?!1:typeof o=="string"?o.length>0:typeof o=="number"?o!==0:F(o)?o.value.length>0:Array.isArray(o)?o.length>0:!!o}export{cn as AmbiguousReferenceRule,ar as BooleanStatement,vn as CANONICAL_FORM_VERSION,wr as Carrier,yn as ClassDefinitionRule,en as ClassHierarchyCycleRule,Ue as CompositeKanonakDocumentRepository,hn as DEFAULT_CONSENT_BINDING_PARAM,Ze as DefinedKanonak,De as DocumentLocation,vr as EdgeType,f as EmbeddedKanonak,Jr as EmbeddedKanonakTypeRule,sr as EmbeddedStatement,I as EntitlementDeniedError,C as EntitlementProducer,Se as FileSystemKanonakDocumentRepository,Dr as GitIgnoreFilter,Vr as GraphBuilder,We as HttpKanonakDocumentRepository,Z as INTEGRITY_PREFIX,x as ImportBook,Zr as ImportExistenceRule,Ce as InMemoryKanonakDocumentRepository,Me as KANONAK_USER_AGENT,Je as Kanonak,Or as KanonakDocumentPositions,E as KanonakObjectParser,fn as KanonakObjectValidator,P as KanonakParser,Qe as KanonakUri,Nr as KanonakUriBuilder,$r as KanonakUrlResolver,fr as KanonakVocabulary,cr as ListStatement,er as LiteralKanonak,qe as LocalFirstRepository,Ge as LockAwareRepository,Kn as LookRenderer,kn as MarkdownLinkRule,pr as MarkdownStatement,an as NamespaceImportCycleRule,Wr as NamespacePrefixRule,Ir as NodeType,or as NumberStatement,Pn as OAuthDiscovery,Cr as OWL_RL_CLASSIFICATION_RULES,un as ObjectPropertyValueValidationRule,zr as OntologyValidationError,Fr as OntologyValidationResult,g as PackageBuilder,Yr as PackageHeaderRule,A as ProducerRepository,ln as PropertyDomainRule,rn as PropertyHierarchyCycleRule,dn as PropertyKindRangeConsistencyRule,Ur as PropertyMetadata,pn as PropertyRangeReferenceRule,nn as PropertyRangeRequiredRule,Gr as PropertyTypeSpecificityRule,ze as PublisherConfigResolver,Be as PublisherIndex,Ar as RDFS_RULES,L as Reasoner,Sr as ReasoningResult,b as ReferenceKanonak,ir as ReferenceStatement,_e as RepositoryFactory,mn as ReservedNameShadowRule,qr as ResourceNamingRule,ur as ResourceResolver,gr as ResourceTypeClassifier,nr as ScalarStatement,rr as Statement,tr as StringStatement,tn as SubClassOfReferenceRule,on as SubPropertyOfReferenceRule,k as SubjectKanonak,Xr as SubjectKanonakTypeRequiredRule,wn as TokenCredentialProvider,jr as TripleStore,lr as TypeResolver,sn as UnresolvedPredicateRule,Qr as UnresolvedReferenceRule,Hr as ValidationCache,Br as ValidationContext,Tr as ValidationSeverity,$t as VersionOperator,S as ViewMaterializer,H as allowAllPolicy,Le as assertHttpsUrl,He as assertPackageIdentity,Ye as buildLocalFirstRepository,Vn as buildOntologyModel,In as canonicalForm,T as canonicalHash,Er as carrierOf,Xe as collectKanonakFiles,V as compareVersions,ae as computeIntegrity,re as computeIntegrityAsync,B as contentAddressedName,Rr as contextTypesOf,Rn as createCredentialedFetch,Ie as createVersion,Kr as extractMarkdownLinks,En as findDerivation,Lr as findInstancesByType,xr as findMalformedReferences,Mr as findMarkdownLinkAt,dr as formatKanonakAddress,y as formatVersion,Oe as getGlobalCachePath,$e as getKanonakUserAgent,Ve as isCompatibleVersion,je as isMajorCompatible,Fe as kanonakFetch,te as loadLockFile,mr as makeUriKey,W as noopMeter,gn as normalizeHost,bn as parseAuthChallenge,M as parseKanonakAddress,Q as parseLockFile,ve as parseVersionString,_r as parseWithPositions,Ae as pickHighestDocument,Pr as propertiesInScope,xn as resolveDisplayValue,br as resolvePropertyStep,K as sanitizeName,oe as saveLockFile,ee as serializeLockFile,Te as setKanonakFetchRetries,Ne as setKanonakUserAgent,m as subjectUri,hr as superClassChain,yr as tripleKey,R as uriKey,kr as uriTriple,xe as versionOperatorFromChar,_ as versionOperatorToChar,Ke as versionsEqual};
1
+ import{a as Yt,b as Jt,c as Zt,d as Qt,e as T}from"./chunk-V3IPBWWU.js";import{a as Ge,b as We,c as ze}from"./chunk-35A2VF5S.js";import{a as er,c as Ee,e as qe,h as Xe,i as Ye,j as nr}from"./chunk-P36E2UV6.js";import{a as zt,b as qt,c as Xt,d as Go,e as be,f as Wo,g as zo,h as qo,i as Xo,j as Yo,k as Jo,l as Zo,m as tr}from"./chunk-5TI4E6M7.js";import{a as Qo}from"./chunk-LYSCTQC2.js";import"./chunk-QHABFCRC.js";import{a as lt,b as dt,c as mt,d as ft,e as yt,f as Ct,g as It,h as Kt,i as vt}from"./chunk-RLQFTA5D.js";import{a as kt,b as ht,c as gt,d as St,e as bt,f as Et,h as Pt,i as Me,j as De,k as $e,l as Te,m as Rt,n as _t}from"./chunk-W35FCNM7.js";import{a as le}from"./chunk-4NO7MHS7.js";import{a as no,b as to,c as oo,d as ro}from"./chunk-5NH5XDGO.js";import{a as ao,b as so}from"./chunk-PEUTCG3B.js";import{a as io}from"./chunk-PEJALHXK.js";import{a as xt}from"./chunk-SC5M74NM.js";import{A as Vo,B as jo,C as Uo,D as Ho,E as Mo,F as Do,G as $o,H as To,K as Fo,L as Bo,a as co,b as uo,c as po,d as lo,e as mo,f as fo,g as yo,h as ko,i as ho,j as go,k as So,l as bo,m as Eo,n as Po,o as Ro,p as xo,q as _o,r as Co,s as Io,t as Ko,u as vo,v as wo,w as No,x as Oo,y as Ao,z as Lo}from"./chunk-UYSEO3OT.js";import"./chunk-M443OYKT.js";import{a as x,b as D,c as ke,i as V,j as Se,k as Gt,l as Wt,m as O}from"./chunk-V6KIDED2.js";import{a as L}from"./chunk-NJ3AZYQD.js";import{a as Vt,b as jt,c as he,d as Ut,e as $,f as Ht,g as Mt,i as Dt,m as $t,o as Tt,p as g,q as Z,v as Ft,w as Bt,x as Q}from"./chunk-SVUMCLK5.js";import{a as wt,b as Nt,c as S,d as k,e as At,f as Lt,g as de,h as me,i as fe,j as q,k as ye,l as X,m as p,p as Fe,r as _,t as Be,u as w,v as Y,w as h,x as ge,y as N,z as J}from"./chunk-YW6P24RF.js";import{a as Ot}from"./chunk-FUUTGGJS.js";import{a as rt,b as pe,c as z,d as at,e as I,f as it,g as st,h as ct,i as ut,j as pt}from"./chunk-2ACBWC7K.js";import{a as eo}from"./chunk-ODIECDN7.js";async function Je(n){let e=await new O().parseKanonaks(n),o=await new T().reason(n);return{kind:"merged",catalog:e,reasoning:o}}function Ze(n,e){return{kind:"merged",catalog:n,reasoning:e}}async function Qe(n,e){let o=e??new le(new L);return{kind:"standalone",catalog:await new O().parseKanonaks(new J(n,o))}}var Pe="kanonak.org",Re="core-shacl",c=n=>({publisher:Pe,package_:Re,name:n}),en=c("NodeShape"),Tr=c("PropertyShape"),nn=c("targetClass"),tn=c("property"),on=c("path"),rn=c("minCount"),an=c("maxCount"),sn=c("datatype"),cn=c("class"),xe=c("in"),un=c("pattern"),pn=c("flags"),ln=c("minLength"),dn=c("maxLength"),mn=c("minInclusive"),fn=c("maxInclusive"),yn=c("message"),kn=c("targetNode"),hn=c("targetSubjectsOf"),gn=c("targetObjectsOf"),Sn=c("closed"),bn=c("ignoredProperties"),En=c("nodeKind"),Pn=c("IRI"),Rn=c("BlankNode"),xn=c("Literal"),_e=c("severity"),_n=c("Violation"),Cn=c("Warning"),In=c("Info"),Fr=c("ValidationReport"),Br=c("conforms"),Gr=c("result"),Wr=c("ValidationResult"),zr=c("focusNode"),qr=c("resultPath"),Xr=c("resultMessage"),Yr=c("resultSeverity"),Jr=c("sourceShape"),Zr=c("value"),Qr=c("sourceConstraintComponent"),Kn=c("MinCountConstraintComponent"),vn=c("MaxCountConstraintComponent"),wn=c("DatatypeConstraintComponent"),Nn=c("ClassConstraintComponent"),On=c("InConstraintComponent"),An=c("PatternConstraintComponent"),Ln=c("MinLengthConstraintComponent"),Vn=c("MaxLengthConstraintComponent"),jn=c("MinInclusiveConstraintComponent"),Un=c("MaxInclusiveConstraintComponent"),Hn=c("NodeKindConstraintComponent"),Ce=c("ClosedConstraintComponent");function H(n){return typeof n=="number"?n:void 0}function or(n){if(!n)return;let e=p(n);if(e===p(Pn))return"IRI";if(e===p(Rn))return"BlankNode";if(e===p(xn))return"Literal"}function Mn(n){if(!n)return;let e=p(n);if(e===p(_n))return"Violation";if(e===p(Cn))return"Warning";if(e===p(In))return"Info"}function Ie(n,e){let o=h(n,e);if(o)return[o];let t=[];for(let r of N(n,e))r instanceof k&&t.push(r.subject);return t}function rr(n,e){let o=h(n,on);if(!o)return;let t={path:o},r=H(w(n,rn)),a=H(w(n,an));r!==void 0&&(t.minCount=r),a!==void 0&&(t.maxCount=a);let s=H(w(n,ln)),i=H(w(n,dn));s!==void 0&&(t.minLength=s),i!==void 0&&(t.maxLength=i);let u=H(w(n,mn)),d=H(w(n,fn));u!==void 0&&(t.minInclusive=u),d!==void 0&&(t.maxInclusive=d);let m=Y(n,un);if(m!==void 0){let P=Y(n,pn);t.pattern=P!==void 0?{regex:m,flags:P}:{regex:m}}if(Be(n,xe)){let P=[],j=[];for(let U of N(n,xe))U instanceof D?P.push(U.value):U instanceof k&&j.push(U.subject);P.length>0&&(t.inValues=P),j.length>0&&(t.inRefs=j)}let b=h(n,sn);b&&(t.datatype=b);let E=h(n,cn);E&&(t.classRef=E);let l=or(h(n,En));l&&(t.nodeKind=l);let f=Y(n,yn);f!==void 0&&(t.message=f);let y=Mn(h(n,_e))??e;return y&&(t.severity=y),t}function ee(n){let e=[];for(let o of n){if(!(o instanceof S)||!Fe(o,en))continue;let t=Mn(h(o,_e)),r={name:o.name,uri:g(o),targetClass:h(o,nn),targetNodes:Ie(o,kn),targetSubjectsOf:Ie(o,hn),targetObjectsOf:Ie(o,gn),closed:w(o,Sn)===!0,ignoredProperties:[],severity:t,properties:[]};for(let a of N(o,bn))a instanceof k&&r.ignoredProperties.push(a.subject);for(let a of N(o,tn)){let s;if(a instanceof x?s=a:a instanceof k&&(s=_(n,a.subject)),!s)continue;let i=rr(s,t);i&&r.properties.push(i)}e.push(r)}return e}var C="kanonak.org/transformations",ne="values";var te="allowed",K=n=>({type:`${C}/VarRef`,varName:n}),Ke=n=>({type:`${C}/IntegerLiteral`,integerLiteral:n}),ar=n=>({type:`${C}/DecimalLiteral`,decimalLiteral:n}),Dn=n=>Number.isInteger(n)?Ke(n):ar(n),$n=n=>({type:`${C}/Count`,source:n}),Tn=(n,e)=>({type:`${C}/GreaterThanOrEqual`,compareLeft:n,compareRight:e}),Fn=(n,e)=>({type:`${C}/LessThanOrEqual`,compareLeft:n,compareRight:e});function ve(n,e){if(!e||e.length===0)return n;let o=new Set(["i","m","s"]),t=[...new Set(e.split(""))];if(t.filter(a=>!o.has(a)).length>0)throw new Error(`sh:flags '${e}' is outside the pinned regex subset (supported: i, m, s)`);return`(?${t.sort().join("")})${n}`}function oe(n){let e=[];return n.minCount!==void 0&&e.push({component:"minCount",per:"node",expr:Tn($n(K(ne)),Ke(n.minCount))}),n.maxCount!==void 0&&e.push({component:"maxCount",per:"node",expr:Fn($n(K(ne)),Ke(n.maxCount))}),(n.inValues!==void 0||n.inRefs!==void 0)&&e.push({component:"in",per:"value",expr:{type:`${C}/Contains`,haystack:K(te),needle:K("v")}}),n.pattern!==void 0&&e.push({component:"pattern",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:ve(n.pattern.regex,n.pattern.flags)}}),n.minLength!==void 0&&e.push({component:"minLength",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:`(?s)^.{${n.minLength},}$`}}),n.maxLength!==void 0&&e.push({component:"maxLength",per:"value",expr:{type:`${C}/Matches`,matchSource:K("v"),pattern:`(?s)^.{0,${n.maxLength}}$`}}),n.minInclusive!==void 0&&e.push({component:"minInclusive",per:"value",expr:Tn(K("v"),Dn(n.minInclusive))}),n.maxInclusive!==void 0&&e.push({component:"maxInclusive",per:"value",expr:Fn(K("v"),Dn(n.maxInclusive))}),e}import{evaluate as sr,ExpressionError as cr}from"@kanonak-protocol/expression";function Wn(n,e){let o=ur(e)?e:ee(e),t=[];for(let r of o)for(let a of pr(n,r))mr(n,r,a,t);return{conforms:!t.some(r=>r.severity==="Violation"),results:t}}function ur(n){return n.length>0&&!(n[0]instanceof Object&&"statement"in n[0])&&typeof n[0].name=="string"&&"properties"in n[0]}function re(n){let e=n.predicate;return e instanceof k?e:void 0}function pr(n,e){let o=new Map,t=n.catalog.filter(a=>a instanceof S),r=a=>{let s=g(a);o.set(s?p(s):`${a.namespace}/${a.name}`,a)};if(e.targetClass){let a=p(e.targetClass);if(n.reasoning){let s=new Set(n.reasoning.getInstancesOfClass(e.targetClass));for(let i of t){let u=g(i);u&&s.has(p(u))&&r(i)}}else for(let s of t)Q(s).some(u=>p(u)===a||Z(n.catalog,u).some(d=>p(d)===a))&&r(s)}for(let a of e.targetNodes){let s=_(n.catalog,a);s instanceof S&&r(s)}for(let a of e.targetSubjectsOf){let s=p(a);for(let i of t)i.statement.some(u=>{let d=re(u);return d&&p(d.subject)===s})&&r(i)}for(let a of e.targetObjectsOf){let s=p(a);for(let i of t)for(let u of i.statement){let d=re(u);if(!(!d||p(d.subject)!==s))for(let m of lr(u)){let b=_(n.catalog,m);b instanceof S&&r(b)}}}return[...o.values()]}function lr(n){return n instanceof q?[n.object.subject]:n instanceof X?(n.object??[]).filter(e=>e instanceof k).map(e=>e.subject):[]}function dr(n,e,o){let t=[];for(let r of n.statement){let a=re(r);if(!(!a||p(a.subject)!==e)){if(r instanceof de||r instanceof ke)t.push({kernel:r.object,kind:"string",literal:r.object});else if(r instanceof me)t.push({kernel:r.object,kind:"number",literal:r.object});else if(r instanceof fe)t.push({kernel:r.object?1:0,kind:"boolean",literal:r.object});else if(r instanceof q)t.push({kernel:{ref:p(r.object.subject)},kind:"reference",ref:r.object.subject});else if(r instanceof ye)t.push(Bn(r.object,o,t.length));else if(r instanceof X){for(let s of r.object??[])if(s instanceof k)t.push({kernel:{ref:p(s.subject)},kind:"reference",ref:s.subject});else if(s instanceof x)t.push(Bn(s,o,t.length));else if(s instanceof D){let i=s.value;typeof i=="boolean"?t.push({kernel:i?1:0,kind:"boolean",literal:i}):t.push({kernel:i,kind:typeof i=="number"?"number":"string",literal:i})}}}}return t}function Bn(n,e,o){let t=n.name&&n.name.length>0?n.name:String(o);return{kernel:{ref:`${e}#${t}`},kind:"embedded"}}function mr(n,e,o,t){let r=g(o),a=r?p(r):`${o.namespace}/${o.name}`;for(let s of e.properties)yr(n,e,o,a,r,s,t);e.closed&&br(e,o,a,r,t)}function we(n,e,o,t,r,a={},s){return{focusNode:e,focusUri:o,constraintComponent:t,severity:s??zn(n),message:r,sourceShape:n.name,sourceShapeUri:n.uri,...a}}function zn(n){return n.severity??"Violation"}var fr={minCount:Kn,maxCount:vn,in:On,pattern:An,minLength:Ln,maxLength:Vn,minInclusive:jn,maxInclusive:Un};function yr(n,e,o,t,r,a,s){let i=p(a.path),u=dr(o,i,t),d=a.severity??zn(e),m=a.path.name,b=[...(a.inValues??[]).map(l=>typeof l=="boolean"?l?1:0:l),...(a.inRefs??[]).map(l=>({ref:p(l)}))],E=(l,f,y)=>{s.push(we(e,t,r,l,a.message??f,{resultPath:a.path,value:y?.literal,valueRef:y?.ref},d))};for(let l of oe(a)){let f=fr[l.component];if(l.per==="node"){Gn(l,{[ne]:u.map(P=>P.kernel),[te]:b})||E(f,l.component==="minCount"?`'${m}' has ${u.length} value(s); minCount is ${a.minCount}.`:`'${m}' has ${u.length} value(s); maxCount is ${a.maxCount}.`);continue}for(let y of u){if((l.component==="pattern"||l.component==="minLength"||l.component==="maxLength")&&y.kind!=="string"){E(f,`'${m}' value is not a string; ${l.component} applies to string values.`,y);continue}Gn(l,{v:y.kernel,[te]:b})||E(f,kr(l,m,a,y),y)}}if(a.nodeKind)for(let l of u)hr(a.nodeKind,l)||E(Hn,`'${m}' value is ${l.kind}; nodeKind requires ${a.nodeKind}.`,l);if(a.datatype)for(let l of u){let f=gr(a.datatype,l);f&&E(wn,`'${m}' ${f}`,l)}if(a.classRef)for(let l of u){let f=Sr(n,a.classRef,l);f&&E(Nn,`'${m}' ${f}`,l)}}function kr(n,e,o,t){let r=t.ref?p(t.ref):JSON.stringify(t.literal);switch(n.component){case"in":return`'${e}' value ${r} is not in the permitted set.`;case"pattern":return`'${e}' value ${r} does not match pattern ${o.pattern?.regex}.`;case"minLength":return`'${e}' value ${r} is shorter than minLength ${o.minLength}.`;case"maxLength":return`'${e}' value ${r} is longer than maxLength ${o.maxLength}.`;case"minInclusive":return`'${e}' value ${r} is below minInclusive ${o.minInclusive} (or not numeric).`;case"maxInclusive":return`'${e}' value ${r} is above maxInclusive ${o.maxInclusive} (or not numeric).`;default:return`'${e}' value ${r} violates ${n.component}.`}}function Gn(n,e){let o=t=>{let r=t.varName;if(t.type==="kanonak.org/transformations/VarRef"&&typeof r=="string"&&r in e)return e[r];throw new cr(`Conformance lowering produced an unexpected leaf '${t.type}'`)};return sr(n.expr,void 0,o)===1}function hr(n,e){switch(n){case"IRI":return e.kind==="reference";case"BlankNode":return e.kind==="embedded";case"Literal":return e.kind==="string"||e.kind==="number"||e.kind==="boolean"}}function gr(n,e){if(e.kind==="reference"||e.kind==="embedded")return`value is a ${e.kind}; sh:datatype requires a literal of ${n.name}.`;let o=Se(n);if(o!==void 0)switch(o){case V.Boolean:return e.kind==="boolean"?void 0:`value is not a boolean (${n.name}).`;case V.Integer:return e.kind!=="number"?`value is not a number (${n.name}).`:Number.isInteger(e.literal)?void 0:`value is not an integer (${n.name}).`;case V.Decimal:case V.Double:case V.Float:return e.kind==="number"?void 0:`value is not a number (${n.name}).`;default:return e.kind==="string"?void 0:`value is not a string-carried literal (${n.name}).`}}function Sr(n,e,o){if(o.kind!=="reference"||!o.ref)return`value is not a reference; sh:class requires an instance of ${e.name}.`;let t=p(e);if(n.reasoning)return n.reasoning.isInstanceOf(o.ref,e)?void 0:`value ${p(o.ref)} is not an instance of ${e.name}.`;let r=_(n.catalog,o.ref);return r instanceof S?Q(r).some(s=>p(s)===t||Z(n.catalog,s).some(i=>p(i)===t))?void 0:`value ${p(o.ref)} is not an instance of ${e.name}.`:`value ${p(o.ref)} does not resolve in this scope (sh:class ${e.name}).`}function br(n,e,o,t,r){let a=new Set([...n.properties.map(i=>p(i.path)),...n.ignoredProperties.map(i=>p(i))]),s=new Set;for(let i of e.statement){let u=re(i);if(!u)continue;let d=p(u.subject);a.has(d)||s.has(d)||(s.add(d),r.push(we(n,o,t,Ce,`'${e.name}' carries undeclared property '${u.subject.name}' (closed shape).`,{resultPath:u.subject})))}for(let i of e.unresolvedPredicates)s.has(i.key)||(s.add(i.key),r.push(we(n,o,t,Ce,`'${e.name}' carries unresolvable property '${i.key}' (closed shape).`,{value:i.key})))}import*as Ne from"js-yaml";import{VersionOperator as qn}from"@kanonak-protocol/types/document/models/enums";var Er="0.0.0",A=class{constructor(e,o=new L,t){this.repository=e;this.parser=o;this.objectParser=t??new O(this.parser)}repository;parser;objectParser;imports(){return new F}serializeValue(e,o){return Jn(e,o)}async buildContentAddressed(e){let o=e.book.toImports(),t=await this.hashBody(e.publisher,o,e.body),r=Oe(t),a={type:"EphemeralPackage",publisher:e.publisher,imports:o};e.contentHashProperty&&(a[e.contentHashProperty]=t),Object.assign(a,e.header??{}),a.imports=o;let s={[r]:a,...e.body},i=this.dump(s);return{yaml:i,byteCount:Yn(i),contentHash:t,packageName:r,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let o=e.book.toImports(),t={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:o},r;e.contentHashProperty&&(r=await this.hashBody(e.publisher,o,e.body),t[e.contentHashProperty]=r),Object.assign(t,e.header??{}),t.imports=o;let a={[e.name]:t,...e.body},s=this.dump(a),i={yaml:s,byteCount:Yn(s),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return r!==void 0&&(i.contentHash=r),i}dump(e){return Ne.dump(e,{lineWidth:-1})}async hashBody(e,o,t){let r={[Xn]:{type:"EphemeralPackage",publisher:e,imports:o},...t},a=this.parser.parse(Ne.dump(r,{lineWidth:-1})),s=a.metadata.namespace_?.toString(),u=(await this.objectParser.parseKanonaks(new J(a,this.repository))).filter(d=>d instanceof S&&d.namespace===s&&d.name!==Xn);for(let d of u)d.namespace="ephemeral";return be(u)}},Xn="__pkgbuilder_probe__";function Yn(n){return new TextEncoder().encode(n).length}function Oe(n){let e="sha256:",o=n.startsWith(e)?e.length:0;return`q-${n.slice(o,o+16)}`}var F=class{byKey=new Map;aliases=new Set;ensure(e,o,t,r,a=qn.Major){let s=`${e}/${o}@${t}`,i=this.byKey.get(s);if(i)return i.alias;let u=this.uniqueAlias(r);return this.byKey.set(s,{publisher:e,package_:o,version:t,alias:u,match:a}),u}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_,I(e.version),e.package_)}.${e.name}`}refLatest(e,o,t,r){return`${this.ensure(e,o,Er,r??o,qn.Any)}.${t}`}toImports(){let e=new Map;for(let t of this.byKey.values()){let r=e.get(t.publisher)??[];r.push(t),e.set(t.publisher,r)}return[...e.keys()].sort().map(t=>({publisher:t,packages:e.get(t).sort((r,a)=>r.package_<a.package_?-1:1).map(r=>({package:r.package_,match:pe(r.match),version:r.version,alias:r.alias}))}))}uniqueAlias(e){let o=B(e)||"pkg",t=o,r=2;for(;this.aliases.has(t);)t=`${o}${r++}`;return this.aliases.add(t),t}};function Jn(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof k)return e.ref(n.subject);if(Array.isArray(n)){let o=n.map(t=>Jn(t,e)).filter(t=>t!==void 0);return o.length>0?o:void 0}if(n instanceof x)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(Pr(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function B(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Pr(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var Rr="1.1.0";async function Zn(n){let e=new A(n.repository),o=e.imports(),t=o.ensure(Pe,Re,Rr,"sh"),r=(i,u)=>i&&i.version&&typeof i.version.major=="number"?`${o.ensure(i.publisher,i.package_,I(i.version),i.package_)}.${i.name}`:u,a={},s=[];return n.result.results.forEach((i,u)=>{let d=`result-${u+1}`;s.push(d);let m={type:`${t}.ValidationResult`,[`${t}.focusNode`]:r(i.focusUri,i.focusNode),[`${t}.resultMessage`]:i.message,[`${t}.resultSeverity`]:`${t}.${i.severity}`,[`${t}.sourceConstraintComponent`]:`${t}.${i.constraintComponent.name}`};i.resultPath&&(m[`${t}.resultPath`]=r(i.resultPath,p(i.resultPath))),i.sourceShapeUri&&(m[`${t}.sourceShape`]=r(i.sourceShapeUri,i.sourceShape)),i.valueRef?m[`${t}.value`]=r(i.valueRef,p(i.valueRef)):i.value!==void 0&&(m[`${t}.value`]=i.value),a[d]=m}),a.report={type:`${t}.ValidationReport`,[`${t}.conforms`]:n.result.conforms,...s.length>0?{[`${t}.result`]:s}:{}},e.buildContentAddressed({publisher:n.publisher,book:o,body:a,...n.header!==void 0?{header:n.header}:{},contentHashProperty:"contentHash"})}import{VersionOperator as Ui}from"@kanonak-protocol/types/document/models/enums";var ae=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,o){return this.producers.find(t=>t.canProduce(e,o))}async produceCached(e,o,t,r){let a=`${o}/${t}@${I(r)}`,s=this.produced.get(a);if(s)return s;let{document:i}=await e.produce(o,t,r);return this.produced.set(a,i),i}async getHighestCompatibleVersionAsync(e,o){let t=this.producerFor(e,o.packageName);if(!t)return null;let r={operator:o.versionOperator,version:o.version},a=await t.resolveVersion(e,o.packageName,r);return a?this.produceCached(t,e,o.packageName,a):null}async getDocumentAsync(e){let o;try{o=he(e)}catch{return null}if(o.kind!=="package"||!o.version)return null;let t=this.producerFor(o.publisher,o.package_);return t?this.produceCached(t,o.publisher,o.package_,o.version):null}async getDocumentsByNamespaceAsync(e,o){return Array.from(this.produced.values()).filter(t=>{let r=t.metadata.namespace_;return r!=null&&r.publisher===e&&r.package_===o})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,o){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,o){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 Ae={async authorize(){return{allowed:!0}}},Le={async record(){}},G=class extends Error{constructor(o,t){let r=`${o.publisher}/${o.package_}${o.version?`@${o.version.major}.${o.version.minor}.${o.version.patch}`:""}`;super(`Not entitled to produce ${r}${t?`: ${t}`:""}`);this.address=o;this.reason=t;this.name="EntitlementDeniedError"}address;reason},ie=class{inner;ctx;policy;meter;constructor(e,o,t=Ae,r=Le){this.inner=e,this.ctx=o,this.policy=t,this.meter=r}canProduce(e,o){return this.inner.canProduce(e,o)}async resolveVersion(e,o,t){return await this.assertAllowed({publisher:e,package_:o,version:t.version}),this.inner.resolveVersion(e,o,t)}async produce(e,o,t){let r={publisher:e,package_:o,version:t};await this.assertAllowed(r);let a=await this.inner.produce(e,o,t);return await this.meter.record(this.ctx,r,a),a}async assertAllowed(e){let o=await this.policy.authorize(this.ctx,e);if(!o.allowed)throw new G(e,o.reason)}};var R="kanonak.org",v="view",Qn="core-kanonak",xr={publisher:R,package_:v,name:"rootView"},_r={publisher:R,package_:v,name:"bind"},Cr={publisher:R,package_:v,name:"produces"},Ir={publisher:R,package_:v,name:"projections"},Kr={publisher:R,package_:v,name:"where"},vr={publisher:R,package_:v,name:"value"},wr={publisher:R,package_:v,name:"as"},se=class{constructor(e,o=new L){this.repository=e;this.parser=o;this.objectParser=new O(this.parser),this.builder=new A(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,o={}){let t=await this.objectParser.parseKanonaks(this.repository),r=this.resolveView(t,e),a=h(r,_r);if(!a)throw new Error(`View ${r.namespace}/${r.name} declares no view.bind; cannot materialize.`);let s=h(r,Cr);if(!s)throw new Error(`View ${r.namespace}/${r.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let i=Nr(r),u=et(t,R,Qn),d=et(t,R,v),m=this.builder.imports(),b=m.ensure(R,Qn,u,"ck"),E=m.ensure(R,v,d,"v"),l=m.ref(s),f=new Ye(this.repository,this.parser,this.objectParser),y=new qe(f,t),P=this.readProjections(t,r),j=Lr(r,Kr),U=this.findInstances(t,a,await this.reason(o)),Ve={},tt=new Set;for(let W of U){if(!await this.passesWhere(y,t,j,W))continue;let ue={type:l};for(let Ue of P){let ot=await this.evaluateValue(y,t,Ue.value,W),He=this.builder.serializeValue(nt(ot),m);He!==void 0&&(ue[m.ref(Ue.as)]=He)}let je=g(W);je&&(ue[`${E}.derivedFrom`]=m.ref(je)),Ve[this.rowName(W,tt)]=ue}let ce={};o.resolvedAt&&(ce[`${b}.resolvedAt`]=o.resolvedAt),o.invocationId&&(ce[`${b}.id`]=o.invocationId);let M=await this.builder.buildContentAddressed({publisher:i,book:m,body:Ve,contentHashProperty:`${b}.contentHash`,header:ce});return{yaml:M.yaml,contentHash:M.contentHash,packageName:M.packageName,publisher:M.publisher,rowCount:M.resourceCount}}resolveView(e,o){let t=_(e,o);if(!t)throw new Error(`View ${o.publisher}/${o.package_}/${o.name} not found in the catalog.`);let r=h(t,xr);if(r){let a=_(e,r);if(!a)throw new Error(`ViewPackage ${o.name} names rootView ${r.name}, which is not in the catalog.`);return a}return t}readProjections(e,o){let t=[];for(let r of N(o,Ir)){let a=r instanceof x?r:r instanceof k?_(e,r.subject):void 0;if(!a)continue;let s=ge(a,vr),i=h(a,wr);s&&i&&t.push({value:s,as:i})}return t}async reason(e){return new T({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,o,t){let r=Ar(e),a=[],s=new Set;for(let i of t.getInstancesOfClass(o)){if(s.has(i))continue;s.add(i);let u=r.get(i);u&&a.push(u)}return a.sort((i,u)=>{let d=$(g(i)),m=$(g(u));return d<m?-1:d>m?1:0}),a}async passesWhere(e,o,t,r){for(let a of t){let s=await this.evaluateValue(e,o,a,r);if(!Vr(s))return!1}return!0}async evaluateValue(e,o,t,r){let a=Xe(t,"view-projection",{catalog:o,depth:0}),s=new Map([["input",r]]);return e.evaluate(a,s)}rowName(e,o){let t=B(e.name)||"row",r=t,a=2;for(;o.has(r);)r=`${t}-${a++}`;return o.add(r),r}};function nt(n){return Ee(n)?n.value:Array.isArray(n)?n.map(nt):n}function Nr(n){let e=g(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function et(n,e,o){let t=Or(n,e,o);if(!t)throw new Error(`Package ${e}/${o} is not in the catalog; it must be importable to materialize a view.`);return t}function Or(n,e,o){let t;for(let r of n){if(!(r instanceof S))continue;let a=g(r);!a||a.publisher!==e||a.package_!==o||!a.version||(!t||z(a.version,t)>0)&&(t=a.version)}return t?I(t):void 0}function Ar(n){let e=new Map,o=new Map;for(let t of n){if(!(t instanceof S))continue;let r=g(t);if(!r||!r.version)continue;let a=$(r),s=o.get(a);(!s||z(r.version,s)>0)&&(o.set(a,r.version),e.set(a,t))}return e}function Lr(n,e){let o=ge(n,e);return o?[o]:N(n,e).filter(t=>t instanceof x)}function Vr(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Ee(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{vo as AmbiguousReferenceRule,fe as BooleanStatement,Wo as CANONICAL_FORM_VERSION,V as Carrier,Vo as ClassDefinitionRule,Po as ClassHierarchyCycleRule,mt as CompositeKanonakDocumentRepository,qo as DEFAULT_CONSENT_BINDING_PARAM,Nt as DefinedKanonak,Fo as DiamondNameClashRule,Uo as DisplayLensScopeRule,dt as DocumentLocation,qt as EdgeType,x as EmbeddedKanonak,So as EmbeddedKanonakTypeRule,ye as EmbeddedStatement,G as EntitlementDeniedError,ie as EntitlementProducer,lt as FileSystemKanonakDocumentRepository,eo as GitIgnoreFilter,Xt as GraphBuilder,_t as HttpKanonakDocumentRepository,Me as INTEGRITY_PREFIX,F as ImportBook,bo as ImportExistenceRule,le as InMemoryKanonakDocumentRepository,kt as KANONAK_USER_AGENT,wt as Kanonak,to as KanonakDocumentPositions,O as KanonakObjectParser,Bo as KanonakObjectValidator,L as KanonakParser,Ot as KanonakUri,ao as KanonakUriBuilder,io as KanonakUrlResolver,$t as KanonakVocabulary,X as ListStatement,D as LiteralKanonak,Ct as LocalFirstRepository,It as LockAwareRepository,Mo as LookBandPathRule,nr as LookRenderer,Ho as LookSemanticSvgPathRule,jo as MarkdownLinkRule,ke as MarkdownStatement,Io as NamespaceImportCycleRule,fo as NamespacePrefixRule,zt as NodeType,me as NumberStatement,Xo as OAuthDiscovery,Zt as OWL_RL_CLASSIFICATION_RULES,No as ObjectPropertyValueValidationRule,po as OntologyValidationError,co as OntologyValidationResult,To as OwlOneOfRule,A as PackageBuilder,go as PackageHeaderRule,ae as ProducerRepository,Oo as PropertyDomainRule,Ro as PropertyHierarchyCycleRule,Ao as PropertyKindRangeConsistencyRule,no as PropertyMetadata,wo as PropertyRangeReferenceRule,xo as PropertyRangeRequiredRule,ko as PropertyTypeSpecificityRule,Pt as PublisherConfigResolver,Rt as PublisherIndex,Jt as RDFS_RULES,T as Reasoner,Qt as ReasoningResult,k as ReferenceKanonak,q as ReferenceStatement,yt as RepositoryFactory,Lo as ReservedNameShadowRule,yo as ResourceNamingRule,Vt as ResourceResolver,Tt as ResourceTypeClassifier,Lt as ScalarStatement,$o as ShaclShapeRule,At as Statement,de as StringStatement,_o as SubClassOfReferenceRule,Co as SubPropertyOfReferenceRule,S as SubjectKanonak,ho as SubjectKanonakTypeRequiredRule,Zo as TokenCredentialProvider,Yt as TripleStore,Do as TxExpressionPathRule,jt as TypeResolver,Ko as UnresolvedPredicateRule,Eo as UnresolvedReferenceRule,mo as ValidationCache,lo as ValidationContext,uo as ValidationSeverity,Ui as VersionOperator,se as ViewMaterializer,Ae as allowAllPolicy,St as assertHttpsUrl,xt as assertPackageIdentity,vt as buildLocalFirstRepository,tr as buildOntologyModel,Zn as buildReportPackageAsync,ee as buildShapesModel,Go as canonicalForm,be as canonicalHash,Se as carrierOf,Kt as collectKanonakFiles,z as compareVersions,ze as computeIntegrity,Te as computeIntegrityAsync,Oe as contentAddressedName,Q as contextTypesOf,Jo as createCredentialedFetch,it as createVersion,Wn as evaluateConformance,Wt as extractMarkdownLinks,Qo as findDerivation,so as findInstancesByType,Gt as findMalformedReferences,ro as findMarkdownLinkAt,ve as foldFlagsIntoPattern,Ut as formatKanonakAddress,I as formatVersion,ft as getGlobalCachePath,gt as getKanonakUserAgent,ct as isCompatibleVersion,ut as isMajorCompatible,bt as kanonakFetch,Ge as loadLockFile,oe as lowerConstraint,Ht as makeUriKey,Le as noopMeter,zo as normalizeHost,Yo as parseAuthChallenge,he as parseKanonakAddress,De as parseLockFile,st as parseVersionString,oo as parseWithPositions,pt as pickHighestDocument,Ft as propertiesInScope,er as resolveDisplayValue,Bt as resolvePropertyStep,B as sanitizeName,We as saveLockFile,Ze as scopeFromCatalog,Qe as scopeFromDocumentAsync,Je as scopeFromRepositoryAsync,$e as serializeLockFile,Et as setKanonakFetchRetries,ht as setKanonakUserAgent,g as subjectUri,Z as superClassChain,Mt as tripleKey,$ as uriKey,Dt as uriTriple,rt as versionOperatorFromChar,pe as versionOperatorToChar,at as versionsEqual};
@@ -1,4 +1,4 @@
1
- import{a as g}from"../chunk-4PY3JJH3.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-V6KIDED2.js";import"../chunk-NJ3AZYQD.js";import{p as m,x as S}from"../chunk-SVUMCLK5.js";import{c as v,m as p,r as E}from"../chunk-YW6P24RF.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
1
+ import{a as g}from"../chunk-P36E2UV6.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-V6KIDED2.js";import"../chunk-NJ3AZYQD.js";import{p as m,x as S}from"../chunk-SVUMCLK5.js";import{c as v,m as p,r as E}from"../chunk-YW6P24RF.js";import"../chunk-FUUTGGJS.js";import{c as x}from"../chunk-2ACBWC7K.js";import{homedir as P}from"os";import{join as d}from"path";import{existsSync as M,mkdirSync as D,readFileSync as j,writeFileSync as O}from"fs";import{createHash as C}from"crypto";import{pathToFileURL as B}from"url";var h="Xenova/all-MiniLM-L6-v2",w="q8",b=32;async function F(r){let{pipeline:e,env:t}=r.transformers;t.cacheDir=r.modelCacheDir??d(P(),".kanonak","models");let n=await e("feature-extraction",h,{dtype:w});return async s=>(await n(s,{pooling:"mean",normalize:!0})).tolist()}async function z(r){let e=d(r,"node_modules","@huggingface","transformers"),t=JSON.parse(j(d(e,"package.json"),"utf-8")),n=I(t);if(!n)throw new Error(`@huggingface/transformers at ${e} exposes no resolvable ESM entry.`);let s=await import(B(d(e,n)).href);return typeof s.pipeline=="function"?s:s.default}function I(r){let e=r.exports,t=n=>typeof n=="string"?n:n?.default;return typeof e=="string"?e:t(e?.node?.import)??t(e?.import)??t(e?.default)??r.module??r.main}var y=null;async function U(){return y||(y=(async()=>{let r;try{r=await import("@huggingface/transformers")}catch(e){throw new Error(`Semantic search requires the embedding runtime, which is an optional dependency.
2
2
  Install it with:
3
3
  npm install @huggingface/transformers
4
4
  (underlying import error: ${e.message})`)}return F({transformers:r})})()),y}function H(r,e){let t=0;for(let n=0;n<r.length;n++)t+=r[n]*e[n];return t}function R(r,e){return e?r.version?e.version?x(r.version,e.version)>0:!0:!1:!0}function K(r,e){let t=g(r,e),n=[t.label],s=S(e);if(s.length>0){let i=E(r,s[0]),a=i?g(r,i).label:s[0].name;a&&n.push(`\u2014 a ${a}.`)}return t.summary&&n.push(t.summary),n.join(" ")}function q(r){let e=new Map;for(let t of r){if(!(t instanceof v))continue;let n=m(t);if(!n)continue;let s=p(n),i=e.get(s);(!i||R(n,m(i)))&&e.set(s,t)}return[...e.values()].sort((t,n)=>{let s=m(t)?p(m(t)):t.name,i=m(n)?p(m(n)):n.name;return s.localeCompare(i)})}var k=class{entries=[];embedder;constructor(e={}){this.embedder=e.embedder}resolveEmbedder(){return this.embedder?Promise.resolve(this.embedder):U()}get size(){return this.entries.length}async build(e,t={}){let n=q(e);if(t.include&&(n=n.filter(t.include)),n.length===0)return this.entries=[],{size:0,cached:!1};let s=n.map(o=>K(e,o)),i=t.cacheDir,a;if(i){let o=C("sha256").update(h+"|"+w+`
@@ -1,12 +1,43 @@
1
1
  import type { IKanonakDocumentRepository, KanonakDocument, DocumentReference, Import } from '@kanonak-protocol/types/document/models';
2
+ /**
3
+ * An import edge the closure walk could not resolve to a compatible document.
4
+ * Surfaced to the caller so a partial closure is VISIBLE — a package whose
5
+ * import fails still parses, but every statement authored against the missing
6
+ * package's entities drops into `unresolvedPredicates`, which downstream reads
7
+ * as e.g. a band-less look and an empty page (typescript#91). The edge names
8
+ * exactly what to fix.
9
+ */
10
+ export interface UnresolvedImportEdge {
11
+ /** `publisher/package@version` of the document declaring the import. */
12
+ readonly fromNamespace: string;
13
+ /** The imported package's publisher. */
14
+ readonly publisher: string;
15
+ /** The imported package's name. */
16
+ readonly packageName: string;
17
+ /** The declared constraint, e.g. `^1.21.0`. */
18
+ readonly constraint: string;
19
+ /** Why: no version in the repository satisfies it, or resolution threw. */
20
+ readonly reason: 'no-compatible-version' | 'resolution-error';
21
+ }
22
+ export interface DeriveImportClosureOptions {
23
+ /**
24
+ * Called once per import edge the walk cannot resolve. The walk still
25
+ * proceeds (a render is more useful degraded than absent), but the caller
26
+ * MUST surface these — loadServerModel/loadResourceModel thread them into
27
+ * `RenderStackReport.warnings`; silence is how typescript#91 shipped.
28
+ */
29
+ onUnresolvedEdge?: (edge: UnresolvedImportEdge) => void;
30
+ }
2
31
  /**
3
32
  * The transitive import closure of `seedDocs`, as a set of `publisher/package`
4
33
  * keys: every package reachable by following `imports:` recursively, each import
5
34
  * resolved through `repo`. This is exactly the set of packages a render needs —
6
35
  * what makes a render a pure function of its seed, independent of whatever else
7
- * happens to be in the global cache. Unresolved imports are skipped (the page
8
- * still renders, just without that layer). Cross-publisher imports are followed
9
- * (an import names its own publisher), so the closure can span publishers.
36
+ * happens to be in the global cache. Unresolved imports are reported through
37
+ * `options.onUnresolvedEdge` and then skipped (the page still renders, just
38
+ * without that layer and the report is what keeps that degradation visible).
39
+ * Cross-publisher imports are followed (an import names its own publisher), so
40
+ * the closure can span publishers.
10
41
  *
11
42
  * Resolving every import through `repo` has a deliberate side effect on a
12
43
  * tiered repository: an import only the HTTP tier can satisfy is fetched (and
@@ -14,7 +45,7 @@ import type { IKanonakDocumentRepository, KanonakDocument, DocumentReference, Im
14
45
  * enumerates the full closure. `ValidationCache` relies on this to build a
15
46
  * complete catalog on a cold cache.
16
47
  */
17
- export declare function deriveImportClosure(seedDocs: KanonakDocument[], repo: IKanonakDocumentRepository): Promise<Set<string>>;
48
+ export declare function deriveImportClosure(seedDocs: KanonakDocument[], repo: IKanonakDocumentRepository, options?: DeriveImportClosureOptions): Promise<Set<string>>;
18
49
  /**
19
50
  * Wraps a repository so the catalog enumeration (`getAllDocumentsAsync`) yields
20
51
  * ONLY documents whose `publisher/package` is in `scope` — a render's resolved
@@ -5,6 +5,7 @@ export { route } from './route.js';
5
5
  export { RequestRouter, landingPage } from './requestRouter.js';
6
6
  export type { RequestRouterOptions } from './requestRouter.js';
7
7
  export { deriveImportClosure, ClosureScopedRepository } from './closure.js';
8
+ export type { UnresolvedImportEdge, DeriveImportClosureOptions } from './closure.js';
8
9
  export { UNIVERSAL_RENDER_BASE, resolveRenderContract, renderRefKey, buildRenderStackWarnings, } from './renderStack.js';
9
10
  export type { RenderPackageRef, RenderPackageStatus, RenderStackReport, } from './renderStack.js';
10
11
  export { buildRenderDiagnostics, renderDiagnosticsHtml } from './renderDiagnostics.js';
@@ -1,7 +1,7 @@
1
- import{c as we}from"../chunk-35A2VF5S.js";import{j as te}from"../chunk-4PY3JJH3.js";import"../chunk-QHABFCRC.js";import{a as fe,d as Q,f as be,h as Z}from"../chunk-RLQFTA5D.js";import{e as ke,g as ye,m as G,n as X}from"../chunk-W35FCNM7.js";import{a as me}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as $e}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{a as q,b as z}from"../chunk-ITKOKDBG.js";import{m as re}from"../chunk-V6KIDED2.js";import{a as O}from"../chunk-NJ3AZYQD.js";import{c as Se}from"../chunk-SVUMCLK5.js";import{c as ve,s as ee}from"../chunk-YW6P24RF.js";import"../chunk-FUUTGGJS.js";import{c as L,e as D,f as H,g as he}from"../chunk-2ACBWC7K.js";import{readFileSync as ie,writeFileSync as je,mkdirSync as Ce}from"fs";import{join as oe}from"path";import Fe from"js-yaml";var Re=[{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 U(t){return Re}function F(t){return`${t.publisher}/${t.package_}`}function Y(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 i=F(r),o=e[i]??"whatever this package contributes to rendering is lost";s.push(`Render-stack package ${i} is MISSING (${r.reason??"unknown reason"}) \u2014 ${o}. Fix: kanonak install ${i} (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 ne(t){let{publisher:e,availablePublishers:s,catalog:r,lookRenderer:i,localNamespaces:o,rawByNsKey:m,renderStack:p,producers:k,lockSource:c,configSource:h}=t,n=new Map,g=new Map,w=new Map,v=new Set;for(let $ of r){if(!($ instanceof ve))continue;let R=$.namespace||"";if(!o.has(R))continue;n.set(`${R}/${$.name}`,$);let _=R.split("/")[1]??"",[j,N]=_.split("@");if(!j||!N)continue;let K=he(N);K&&(v.has(_)||(v.add(_),g.has(j)||g.set(j,[]),g.get(j).push({verStr:N,version:K})),$.name===j&&w.set(_,$))}for(let $ of g.values())$.sort((R,_)=>L(_.version,R.version));return{publisher:e,availablePublishers:s,catalog:r,lookRenderer:i,localNamespaces:o,rawByNsKey:m,bySubject:n,pkgVersions:g,pkgSelfByVer:w,renderStack:p,...k?{producers:k}:{},...c?{lockSource:c}:{},...h?{configSource:h}:{}}}async function ce(t,e={}){let s=new O,r=new me(s),i=[],o=[];for(let l of Z(t)){let u;try{u=ie(l,"utf-8")}catch{continue}let y;try{y=s.parse(u).metadata?.namespace_}catch{continue}if(!y?.version)continue;let I=y.version;o.push({publisher:y.publisher,package_:y.package_,verStr:D(I),version:I,source:u})}o.sort((l,u)=>L(u.version,l.version));for(let l of o)await r.saveDocumentAsync(s.parse(l.source),`${l.publisher}/${l.package_}@${l.verStr}`),i.push({publisher:l.publisher,package_:l.package_,verStr:l.verStr,source:l.source});let m=[...new Set(i.map(l=>l.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,c=new Map;for(let l of i)l.publisher===p&&(k.add(`${l.publisher}/${l.package_}@${l.verStr}`),c.set(`${l.package_}@${l.verStr}`,l.source));let h=Q(),n=new fe(h,!0,s),g={};e.httpCache&&(g.getFromCache=e.httpCache.getFromCache,g.onFetch=e.httpCache.onFetch),e.fetchFn&&(g.fetchFn=e.fetchFn);let w=e.repository??new be(r,n,new X(g)),v=e.log??(()=>{}),$=U(void 0),R=[],_=l=>l.map(u=>u.metadata.namespace_?.version).filter(u=>u!==void 0).sort((u,y)=>L(y,u)).map(D);if(!e.repository){v(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${h}`);let l=e.fetchFn?new G({fetchFn:e.fetchFn}):new G;for(let u of $){let y=F(u),I=await r.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(I.length>0){let d=_(I);R.push({...u,origin:"workspace",versions:d}),v(`[render-stack] ${y} \u2014 workspace (${d.join(", ")})`);continue}let a=await n.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(a.length>0){let d=_(a);R.push({...u,origin:"cache",versions:d}),v(`[render-stack] ${y} \u2014 cache (${d.join(", ")})`);continue}try{let f=(await l.getLock(u.publisher))?.packages[`${u.publisher}/${u.package_}`];if(!f){let C=`publisher ${u.publisher} reachable but its lock does not pin ${u.package_}`;R.push({...u,origin:"missing",reason:C}),v(`[render-stack] ${y} \u2014 MISSING: ${C}`);continue}let S=f.version,b=f.resolved,E=await(e.fetchFn?e.fetchFn(b,u.publisher):ke(b));if(!E.ok){let C=`fetch ${b} failed: HTTP ${E.status} ${E.statusText}`;R.push({...u,origin:"missing",reason:C}),v(`[render-stack] ${y} \u2014 MISSING: ${C}`);continue}let ge=await E.text();await r.saveDocumentAsync(s.parse(ge),`${u.publisher}/${u.package_}@${S}`);try{let C=oe(h,u.publisher);Ce(C,{recursive:!0}),je(oe(C,`${u.package_}@${S}.kan.yml`),ge,"utf-8"),R.push({...u,origin:"fetched",versions:[S]}),v(`[render-stack] ${y}@${S} \u2014 fetched from ${b}, installed to cache`)}catch(C){R.push({...u,origin:"fetched",versions:[S]}),v(`[render-stack] ${y}@${S} \u2014 fetched from ${b}, but cache ${h} is NOT WRITABLE (${C.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(d){let f=`fetch failed: ${d.message}`;R.push({...u,origin:"missing",reason:f}),v(`[render-stack] ${y} \u2014 MISSING: ${f}`)}}}let j=w;if(!e.repository){let l=(await r.getAllDocumentsAsync()).filter(y=>y.metadata.namespace_?.publisher===p),u=await q(l,w);for(let y of $)u.add(F(y));j=new z(w,u)}let N=await new re(s).parseKanonaks(j),K=new te(N),T=(l,u)=>ee(N,{publisher:l,package_:u,name:u}).length>0,V;if(e.repository){V=[];for(let l of $){let u=await w.getDocumentsByNamespaceAsync(l.publisher,l.package_);V.push(u.length>0?{...l,origin:"repository",versions:_(u)}:{...l,origin:"missing",reason:"not present in the caller-supplied repository"})}}else V=R.map(l=>l.origin==="missing"||T(l.publisher,l.package_)?l:{...l,resolvedButNotInCatalog:!0});let J=Y(V);for(let l of J)v(`[render-stack] WARNING: ${l}`);let W={contractSource:"universal-default",cachePath:h,packages:V,warnings:J},B;try{B=ie(oe(t,"kanonak.lock"),"utf-8")}catch{B=Ne(p,i,s)}let A;try{A=ie(oe(t,".well-known","kanonak.json"),"utf-8")}catch{A=void 0}return ne({publisher:p,availablePublishers:m,catalog:N,lookRenderer:K,localNamespaces:k,rawByNsKey:c,renderStack:W,...B?{lockSource:B}:{},...A?{configSource:A}:{}})}function Ne(t,e,s){let r=new Map;for(let o of e)o.publisher===t&&(r.has(o.package_)||r.set(o.package_,{verStr:o.verStr,source:o.source}));if(r.size===0)return;let i={};for(let o of[...r.keys()].sort()){let{verStr:m,source:p}=r.get(o),k={},c;try{c=s.parse(p).metadata?.imports}catch{c=void 0}for(let n of c?.[t]??[]){let g=r.get(n.packageName);g&&(k[`${t}/${n.packageName}`]=g.verStr)}let h={};for(let n of Object.keys(k).sort())h[n]=k[n];i[`${t}/${o}`]={version:m,resolved:`https://${t}/${o}/${m}.kan.yml`,integrity:we(p),dependencies:h}}return Fe.dump({version:"1",lastUpdated:"",packages:i},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Me,readFileSync as Ie,writeFileSync as De,mkdirSync as Ke}from"fs";import{join as xe}from"path";async function le(t,e={}){let s=new O,r=Se(t),i=r.kind==="resource"?r.uri.publisher:r.publisher,o=e.log??(()=>{}),m=e.cacheRoot??Q(),p=(a,d,f)=>xe(m,a,`${d}@${f}.kan.yml`),k=new Set,c=new Set,h=new Map,n=new X({getFromCache:(a,d,f)=>{let S=p(a,d,f),b=Me(S)?Ie(S,"utf-8"):null;return b!==null&&k.add(`${a}/${d}`),b},onFetch:(a,d,f,S)=>{c.add(`${a}/${d}`);try{let b=xe(m,a);Ke(b,{recursive:!0}),De(p(a,d,f),S,"utf-8")}catch(b){h.set(`${a}/${d}`,b.message),o(`[render] fetched ${a}/${d}@${f} but cache ${m} is NOT WRITABLE (${b.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new G(e.fetchFn?{fetchFn:e.fetchFn}:void 0),w;if(r.kind==="resource"){let a=r.uri.version;w=[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;w=[a?{package_:r.package_,version:`${a.major}.${a.minor}.${a.patch}`}:{package_:r.package_}]}else w=((await g.getConfig(i)).featured_packages??[]).map(d=>({package_:d}));let v=async(a,d,f)=>{try{let S=f?s.buildImport(d,"=",f,a):s.buildImport(d,"*","0.0.0",a),b=await n.getHighestCompatibleVersionAsync(a,S);return b?{doc:b}:{doc:null,error:`${a} did not resolve ${d}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(S){return{doc:null,error:S.message}}},$=[],R=[];for(let a of w){let{doc:d,error:f}=await v(i,a.package_,a.version);d?$.push(d):f&&R.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${i}".`+(R.length>0?` Reasons: ${R.join("; ")}`:""));let _=U(),j="universal-default",N=a=>a.map(d=>d.metadata.namespace_?.version).filter(d=>d!==void 0).sort((d,f)=>L(f,d)).map(D);o(`[render-stack] resolving ${_.length} ambient look-stack package(s) (contract: ${j}); cache: ${m}`);let K=[],T=[];for(let a of _){let d=F(a),{doc:f,error:S}=await v(a.publisher,a.package_,void 0);if(f){K.push(f);let b=N([f]),E=c.has(d)?"fetched":k.has(d)?"cache":"fetched";T.push({...a,origin:E,versions:b}),o(`[render-stack] ${d} \u2014 ${E} (${b.join(", ")})`+(h.has(d)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else T.push({...a,origin:"missing",reason:S??"unresolved"}),o(`[render-stack] ${d} \u2014 MISSING: ${S??"unresolved"}`)}let V=await q([...$,...K],n),J=new z(n,V),W=await new re(s).parseKanonaks(J),B=new te(W),A=T.map(a=>a.origin==="missing"||ee(W,{publisher:a.publisher,package_:a.package_,name:a.package_}).length>0?a:{...a,resolvedButNotInCatalog:!0}),l=Y(A);for(let a of l)o(`[render-stack] WARNING: ${a}`);let u={contractSource:j,cachePath:m,packages:A,warnings:l},y=new Set,I=new Map;for(let a of await n.getAllDocumentsAsync()){let d=a.metadata.namespace_;if(!d?.version||d.publisher!==i)continue;let f=D(d.version),S=`${d.publisher}/${d.package_}@${f}`;y.add(S);let b=await n.getDocumentContentAsync(S);b!==null&&I.set(`${d.package_}@${f}`,b)}return ne({publisher:i,availablePublishers:[i],catalog:W,lookRenderer:B,localNamespaces:y,rawByNsKey:I,renderStack:u})}import{VersionOperator as ae}from"@kanonak-protocol/types/document/models/enums";function se(t){let{lookRenderer:e,publisher:s,renderStack:r,catalog:i}=t,o=e.explainStylesheet(e.publisherSubject(s)),m=[...o.tokens.entries()].map(([n,g])=>({name:n,value:g.value,source:`${g.sourceNamespace}/${g.sourceName}`,level:g.level})),p=o.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},c=new Map;for(let n of i){let g=n.namespace;g&&c.set(g,(c.get(g)??0)+1)}let h=[...c.entries()].map(([n,g])=>({namespace:n,resources:g})).sort((n,g)=>n.namespace.localeCompare(g.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:m,baseStylesheet:k,...o.look?{look:{sourceClass:`${o.look.sourceClass.publisher}/${o.look.sourceClass.package_}/${o.look.sourceClass.name}`}}:{}},catalog:h,warnings:[...r.warnings,...o.warnings.filter(n=>!r.warnings.includes(n))]}}function Ve(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function de(t){let e=Ve,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(c=>`<div class="warn">\u26A0 ${e(c)}</div>`).join(`
2
- `),i=t.renderStack.packages.map(c=>{let h=c.origin!=="missing"&&!c.resolvedButNotInCatalog,n=c.origin==="missing"?'<span class="bad">MISSING</span>':c.resolvedButNotInCatalog?`<span class="bad">${e(c.origin)} (not in catalog)</span>`:`<span class="good">${e(c.origin)}</span>`,g=c.reason?e(c.reason):e((c.versions??[]).join(", "));return`<tr class="${h?"":"row-bad"}"><td><code>${e(c.package_)}</code></td><td>${n}</td><td>${g}</td></tr>`}).join(`
3
- `),o=t.stylesheet.baseStylesheet,m=o.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(o.source??"")}</code> (${o.bytes} bytes, ${e(o.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${o.problem?` \u2014 ${e(o.problem)}`:""}${o.candidates.length>0?`<br>candidates considered: ${o.candidates.map(c=>`<code>${e(c)}</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(c=>`<tr><td><code>--kan-${e(c.name)}</code></td><td><code>${e(c.value)}</code></td><td><code>${e(c.source)}</code></td><td>${e(c.level)}</td></tr>`).join(`
4
- `),k=t.catalog.map(c=>`<tr><td><code>${e(c.namespace)}</code></td><td>${c.resources}</td></tr>`).join(`
1
+ import{c as Pe}from"../chunk-35A2VF5S.js";import{j as oe}from"../chunk-P36E2UV6.js";import"../chunk-QHABFCRC.js";import{a as be,d as X,f as Se,h as ee}from"../chunk-RLQFTA5D.js";import{e as ve,g as $e,m as U,n as Z}from"../chunk-W35FCNM7.js";import{a as ye}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as xe}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import{a as H,b as G}from"../chunk-M443OYKT.js";import{m as te}from"../chunk-V6KIDED2.js";import{a as O}from"../chunk-NJ3AZYQD.js";import{c as Re}from"../chunk-SVUMCLK5.js";import{c as we,s as re}from"../chunk-YW6P24RF.js";import"../chunk-FUUTGGJS.js";import{c as V,e as K,f as W,g as ke}from"../chunk-2ACBWC7K.js";import{readFileSync as de,writeFileSync as Ce,mkdirSync as Fe}from"fs";import{join as se}from"path";import Me from"js-yaml";var _e=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function q(t){return _e}function N(t){return`${t.publisher}/${t.package_}`}function z(t,e=[]){let c={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},r=[];for(let o of t)if(o.origin==="missing"){let s=N(o),m=c[s]??"whatever this package contributes to rendering is lost";r.push(`Render-stack package ${s} is MISSING (${o.reason??"unknown reason"}) \u2014 ${m}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${o.publisher}.`)}else o.resolvedButNotInCatalog&&r.push(`Render-stack package ${N(o)} resolved (${o.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);for(let o of e)r.push(`Import edge ${o.fromNamespace} \u2192 ${o.publisher}/${o.packageName} ${o.constraint} did NOT resolve (${o.reason==="no-compatible-version"?"no compatible version in the repository":"resolution threw"}) \u2014 every statement ${o.fromNamespace} authors against ${o.publisher}/${o.packageName} entities is dropped from the parse as an unresolved predicate (a look declaration loses its bands and pages render empty; see typescript#91). Fix: add a ${o.constraint}-compatible version of ${o.publisher}/${o.packageName} to the workspace or cache (kanonak install ${o.publisher}/${o.packageName}), or bump the import in ${o.fromNamespace}.`);return r}function ne(t){let{publisher:e,availablePublishers:c,catalog:r,lookRenderer:o,localNamespaces:s,rawByNsKey:m,renderStack:d,producers:f,lockSource:l,configSource:h}=t,a=new Map,g=new Map,S=new Map,v=new Set;for(let $ of r){if(!($ instanceof we))continue;let w=$.namespace||"";if(!s.has(w))continue;a.set(`${w}/${$.name}`,$);let P=w.split("/")[1]??"",[_,M]=P.split("@");if(!_||!M)continue;let D=ke(M);D&&(v.has(P)||(v.add(P),g.has(_)||g.set(_,[]),g.get(_).push({verStr:M,version:D})),$.name===_&&S.set(P,$))}for(let $ of g.values())$.sort((w,P)=>V(P.version,w.version));return{publisher:e,availablePublishers:c,catalog:r,lookRenderer:o,localNamespaces:s,rawByNsKey:m,bySubject:a,pkgVersions:g,pkgSelfByVer:S,renderStack:d,...f?{producers:f}:{},...l?{lockSource:l}:{},...h?{configSource:h}:{}}}async function pe(t,e={}){let c=new O,r=new ye(c),o=[],s=[];for(let i of ee(t)){let u;try{u=de(i,"utf-8")}catch{continue}let n;try{n=c.parse(u).metadata?.namespace_}catch{continue}if(!n?.version)continue;let p=n.version;s.push({publisher:n.publisher,package_:n.package_,verStr:K(p),version:p,source:u})}s.sort((i,u)=>V(u.version,i.version));for(let i of s)await r.saveDocumentAsync(c.parse(i.source),`${i.publisher}/${i.package_}@${i.verStr}`),o.push({publisher:i.publisher,package_:i.package_,verStr:i.verStr,source:i.source});let m=[...new Set(o.map(i=>i.publisher))].sort(),d=e.publisher;if(d){if(!m.includes(d))throw new Error(`Publisher "${d}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)d=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 f=new Set,l=new Map;for(let i of o)i.publisher===d&&(f.add(`${i.publisher}/${i.package_}@${i.verStr}`),l.set(`${i.package_}@${i.verStr}`,i.source));let h=X(),a=new be(h,!0,c),g={};e.httpCache&&(g.getFromCache=e.httpCache.getFromCache,g.onFetch=e.httpCache.onFetch),e.fetchFn&&(g.fetchFn=e.fetchFn);let S=e.repository??new Se(r,a,new Z(g)),v=e.log??(()=>{}),$=q(void 0),w=[],P=i=>i.map(u=>u.metadata.namespace_?.version).filter(u=>u!==void 0).sort((u,n)=>V(n,u)).map(K);if(!e.repository){v(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${h}`);let i=e.fetchFn?new U({fetchFn:e.fetchFn}):new U;for(let u of $){let n=N(u),p=await r.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(p.length>0){let y=P(p);w.push({...u,origin:"workspace",versions:y}),v(`[render-stack] ${n} \u2014 workspace (${y.join(", ")})`);continue}let k=await a.getDocumentsByNamespaceAsync(u.publisher,u.package_);if(k.length>0){let y=P(k);w.push({...u,origin:"cache",versions:y}),v(`[render-stack] ${n} \u2014 cache (${y.join(", ")})`);continue}try{let b=(await i.getLock(u.publisher))?.packages[`${u.publisher}/${u.package_}`];if(!b){let j=`publisher ${u.publisher} reachable but its lock does not pin ${u.package_}`;w.push({...u,origin:"missing",reason:j}),v(`[render-stack] ${n} \u2014 MISSING: ${j}`);continue}let C=b.version,T=b.resolved,Q=await(e.fetchFn?e.fetchFn(T,u.publisher):ve(T));if(!Q.ok){let j=`fetch ${T} failed: HTTP ${Q.status} ${Q.statusText}`;w.push({...u,origin:"missing",reason:j}),v(`[render-stack] ${n} \u2014 MISSING: ${j}`);continue}let fe=await Q.text();await r.saveDocumentAsync(c.parse(fe),`${u.publisher}/${u.package_}@${C}`);try{let j=se(h,u.publisher);Fe(j,{recursive:!0}),Ce(se(j,`${u.package_}@${C}.kan.yml`),fe,"utf-8"),w.push({...u,origin:"fetched",versions:[C]}),v(`[render-stack] ${n}@${C} \u2014 fetched from ${T}, installed to cache`)}catch(j){w.push({...u,origin:"fetched",versions:[C]}),v(`[render-stack] ${n}@${C} \u2014 fetched from ${T}, but cache ${h} is NOT WRITABLE (${j.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(y){let b=`fetch failed: ${y.message}`;w.push({...u,origin:"missing",reason:b}),v(`[render-stack] ${n} \u2014 MISSING: ${b}`)}}}let _=(await r.getAllDocumentsAsync()).filter(i=>i.metadata.namespace_?.publisher===d);for(let i of $)_.push(...await S.getDocumentsByNamespaceAsync(i.publisher,i.package_));let M=[],D=await H(_,S,{onUnresolvedEdge:i=>M.push(i)}),A=S;if(!e.repository){for(let i of $)D.add(N(i));A=new G(S,D)}let B=await new te(c).parseKanonaks(A),ce=new oe(B),le=(i,u)=>re(B,{publisher:i,package_:u,name:u}).length>0,I;if(e.repository){I=[];for(let i of $){let u=await S.getDocumentsByNamespaceAsync(i.publisher,i.package_);I.push(u.length>0?{...i,origin:"repository",versions:P(u)}:{...i,origin:"missing",reason:"not present in the caller-supplied repository"})}}else I=w.map(i=>i.origin==="missing"||le(i.publisher,i.package_)?i:{...i,resolvedButNotInCatalog:!0});let Y=z(I,M);for(let i of Y)v(`[render-stack] WARNING: ${i}`);let J={contractSource:"universal-default",cachePath:h,packages:I,warnings:Y},E;try{E=de(se(t,"kanonak.lock"),"utf-8")}catch{E=De(d,o,c)}let L;try{L=de(se(t,".well-known","kanonak.json"),"utf-8")}catch{L=void 0}return ne({publisher:d,availablePublishers:m,catalog:B,lookRenderer:ce,localNamespaces:f,rawByNsKey:l,renderStack:J,...E?{lockSource:E}:{},...L?{configSource:L}:{}})}function De(t,e,c){let r=new Map;for(let s of e)s.publisher===t&&(r.has(s.package_)||r.set(s.package_,{verStr:s.verStr,source:s.source}));if(r.size===0)return;let o={};for(let s of[...r.keys()].sort()){let{verStr:m,source:d}=r.get(s),f={},l;try{l=c.parse(d).metadata?.imports}catch{l=void 0}for(let a of l?.[t]??[]){let g=r.get(a.packageName);g&&(f[`${t}/${a.packageName}`]=g.verStr)}let h={};for(let a of Object.keys(f).sort())h[a]=f[a];o[`${t}/${s}`]={version:m,resolved:`https://${t}/${s}/${m}.kan.yml`,integrity:Pe(d),dependencies:h}}return Me.dump({version:"1",lastUpdated:"",packages:o},{lineWidth:-1,sortKeys:!1,quotingType:'"'})}import{existsSync as Ke,readFileSync as Ee,writeFileSync as Ve,mkdirSync as Ae}from"fs";import{join as je}from"path";async function ue(t,e={}){let c=new O,r=Re(t),o=r.kind==="resource"?r.uri.publisher:r.publisher,s=e.log??(()=>{}),m=e.cacheRoot??X(),d=(n,p,k)=>je(m,n,`${p}@${k}.kan.yml`),f=new Set,l=new Set,h=new Map,a=new Z({getFromCache:(n,p,k)=>{let y=d(n,p,k),b=Ke(y)?Ee(y,"utf-8"):null;return b!==null&&f.add(`${n}/${p}`),b},onFetch:(n,p,k,y)=>{l.add(`${n}/${p}`);try{let b=je(m,n);Ae(b,{recursive:!0}),Ve(d(n,p,k),y,"utf-8")}catch(b){h.set(`${n}/${p}`,b.message),s(`[render] fetched ${n}/${p}@${k} but cache ${m} is NOT WRITABLE (${b.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),g=new U(e.fetchFn?{fetchFn:e.fetchFn}:void 0),S;if(r.kind==="resource"){let n=r.uri.version;S=[n?{package_:r.uri.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let n=r.version;S=[n?{package_:r.package_,version:`${n.major}.${n.minor}.${n.patch}`}:{package_:r.package_}]}else S=((await g.getConfig(o)).featured_packages??[]).map(p=>({package_:p}));let v=async(n,p,k)=>{try{let y=k?c.buildImport(p,"=",k,n):c.buildImport(p,"*","0.0.0",n),b=await a.getHighestCompatibleVersionAsync(n,y);return b?{doc:b}:{doc:null,error:`${n} did not resolve ${p}${k?`@${k}`:""} (not in its index, or unreachable)`}}catch(y){return{doc:null,error:y.message}}},$=[],w=[];for(let n of S){let{doc:p,error:k}=await v(o,n.package_,n.version);p?$.push(p):k&&w.push(k)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${o}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let P=q(),_="universal-default",M=n=>n.map(p=>p.metadata.namespace_?.version).filter(p=>p!==void 0).sort((p,k)=>V(k,p)).map(K);s(`[render-stack] resolving ${P.length} ambient look-stack package(s) (contract: ${_}); cache: ${m}`);let D=[],A=[];for(let n of P){let p=N(n),{doc:k,error:y}=await v(n.publisher,n.package_,void 0);if(k){D.push(k);let b=M([k]),C=l.has(p)?"fetched":f.has(p)?"cache":"fetched";A.push({...n,origin:C,versions:b}),s(`[render-stack] ${p} \u2014 ${C} (${b.join(", ")})`+(h.has(p)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...n,origin:"missing",reason:y??"unresolved"}),s(`[render-stack] ${p} \u2014 MISSING: ${y??"unresolved"}`)}let B=[],ce=await H([...$,...D],a,{onUnresolvedEdge:n=>B.push(n)}),le=new G(a,ce),I=await new te(c).parseKanonaks(le),Y=new oe(I),J=A.map(n=>n.origin==="missing"||re(I,{publisher:n.publisher,package_:n.package_,name:n.package_}).length>0?n:{...n,resolvedButNotInCatalog:!0}),E=z(J,B);for(let n of E)s(`[render-stack] WARNING: ${n}`);let L={contractSource:_,cachePath:m,packages:J,warnings:E},i=new Set,u=new Map;for(let n of await a.getAllDocumentsAsync()){let p=n.metadata.namespace_;if(!p?.version||p.publisher!==o)continue;let k=K(p.version),y=`${p.publisher}/${p.package_}@${k}`;i.add(y);let b=await a.getDocumentContentAsync(y);b!==null&&u.set(`${p.package_}@${k}`,b)}return ne({publisher:o,availablePublishers:[o],catalog:I,lookRenderer:Y,localNamespaces:i,rawByNsKey:u,renderStack:L})}import{VersionOperator as ie}from"@kanonak-protocol/types/document/models/enums";function ae(t){let{lookRenderer:e,publisher:c,renderStack:r,catalog:o}=t,s=e.explainStylesheet(e.publisherSubject(c)),m=[...s.tokens.entries()].map(([a,g])=>({name:a,value:g.value,source:`${g.sourceNamespace}/${g.sourceName}`,level:g.level})),d=s.baseStylesheet,f={present:d.css!==void 0,...d.sourceNamespace!==void 0?{source:d.sourceNamespace}:{},...d.scope!==void 0?{scope:d.scope}:{},...d.css!==void 0?{bytes:d.css.length}:{},...d.problem!==void 0?{problem:d.problem}:{},candidates:d.candidates},l=new Map;for(let a of o){let g=a.namespace;g&&l.set(g,(l.get(g)??0)+1)}let h=[...l.entries()].map(([a,g])=>({namespace:a,resources:g})).sort((a,g)=>a.namespace.localeCompare(g.namespace));return{publisher:c,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(a=>({package_:N(a),origin:a.origin,...a.versions!==void 0?{versions:a.versions}:{},...a.reason!==void 0?{reason:a.reason}:{},...a.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:a.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:f,...s.look?{look:{sourceClass:`${s.look.sourceClass.publisher}/${s.look.sourceClass.package_}/${s.look.sourceClass.name}`}}:{}},catalog:h,warnings:[...r.warnings,...s.warnings.filter(a=>!r.warnings.includes(a))]}}function Be(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ge(t){let e=Be,c=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(l=>`<div class="warn">\u26A0 ${e(l)}</div>`).join(`
2
+ `),o=t.renderStack.packages.map(l=>{let h=l.origin!=="missing"&&!l.resolvedButNotInCatalog,a=l.origin==="missing"?'<span class="bad">MISSING</span>':l.resolvedButNotInCatalog?`<span class="bad">${e(l.origin)} (not in catalog)</span>`:`<span class="good">${e(l.origin)}</span>`,g=l.reason?e(l.reason):e((l.versions??[]).join(", "));return`<tr class="${h?"":"row-bad"}"><td><code>${e(l.package_)}</code></td><td>${a}</td><td>${g}</td></tr>`}).join(`
3
+ `),s=t.stylesheet.baseStylesheet,m=s.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(s.source??"")}</code> (${s.bytes} bytes, ${e(s.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${s.problem?` \u2014 ${e(s.problem)}`:""}${s.candidates.length>0?`<br>candidates considered: ${s.candidates.map(l=>`<code>${e(l)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,d=t.stylesheet.tokens.map(l=>`<tr><td><code>--kan-${e(l.name)}</code></td><td><code>${e(l.value)}</code></td><td><code>${e(l.source)}</code></td><td>${e(l.level)}</td></tr>`).join(`
4
+ `),f=t.catalog.map(l=>`<tr><td><code>${e(l.namespace)}</code></td><td>${l.resources}</td></tr>`).join(`
5
5
  `);return`<!doctype html>
6
6
  <html lang="en">
7
7
  <head>
@@ -21,12 +21,12 @@ import{c as we}from"../chunk-35A2VF5S.js";import{j as te}from"../chunk-4PY3JJH3.
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: ${s?"#ecfdf3":"#fef2f2"}; border: 1px solid ${s?"#0a7d33":"#b91c1c"}; }
24
+ background: ${c?"#ecfdf3":"#fef2f2"}; border: 1px solid ${c?"#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">${s?"\u2713 Healthy":`\u2717 ${t.warnings.length} problem(s) found`}</p>
29
+ <p class="status-banner">${c?"\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,7 +37,7 @@ ${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
- ${i}
40
+ ${o}
41
41
  </table>
42
42
 
43
43
  <h2>Base stylesheet</h2>
@@ -48,7 +48,7 @@ ${m}
48
48
  <p class="meta">Resolved for the publisher landing page. Each token shows which resource in the cascade supplied it.</p>
49
49
  ${t.stylesheet.tokens.length===0?'<p><span class="bad">\u2717 No tokens resolved</span></p>':`<table>
50
50
  <tr><th>Token</th><th>Value</th><th>Declared by</th><th>Cascade level</th></tr>
51
- ${p}
51
+ ${d}
52
52
  </table>`}
53
53
 
54
54
  <h2>Look (page body)</h2>
@@ -58,7 +58,7 @@ ${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
+ ${f}
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,s,r)=>({status:t,headers:{"Content-Type":e,...r||{}},body:s}),M=t=>P(404,x[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),Ae=t=>({status:301,headers:{Location:t},body:""}),Ee=t=>({status:302,headers:{Location:t},body:""});function Le(t){switch(t.kind){case"exact":return{operator:ae.Exact,version:H(t.major,t.minor,t.patch)};case"minor-pin":return{operator:ae.Compatible,version:H(t.major,t.minor,0)};case"major-pin":return{operator:ae.Major,version:H(t.major,0,0)};default:return{operator:ae.Any,version:H(0,0,0)}}}async function Be(t,e,s,r){if(!r)return null;let i=t.producers?.find(k=>k.canProduce(t.publisher,e));if(!i)return null;let o=await i.resolveVersion(t.publisher,e,Le(s));if(!o)return null;let m=D(o);if(s.kind!=="exact")return Ee(`/${e}/${m}.kan.yml`);let{source:p}=await i.produce(t.publisher,e,o);return P(200,x[".kan.yml"],p)}function Pe(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(i=>i.version.major===s.major)?.verStr??null;case"minor-pin":return r.find(i=>i.version.major===s.major&&i.version.minor===s.minor)?.verStr??null;case"exact":return r.find(i=>i.version.major===s.major&&i.version.minor===s.minor&&i.version.patch===s.patch)?.verStr??null;default:return null}}async function pe(t,e,s=""){let{lookRenderer:r,publisher:i}=t;if(e==="/.well-known/kanonak.json")return t.configSource?P(200,x[".json"],t.configSource):P(200,x[".json"],JSON.stringify(ye(),null,2));if(e==="/kanonak.lock")return t.lockSource?P(200,x[".kan.yml"],t.lockSource):M(e);if(e==="/.well-known/kanonak-render.json")return P(200,x[".json"],JSON.stringify(se(t),null,2));if(e==="/.well-known/kanonak-render")return P(200,x[".html"],de(se(t)));if(e==="/"||e==="/index.html"||e==="/index.css"){let n=r.publisherSubject(i);return e==="/index.css"?P(200,x[".css"],r.renderStylesheet(n)):P(200,x[".html"],await r.renderDocument(n,{rootIndex:!0}))}let o=".html",m=!1,p=e;for(let n of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(n)){o=n,m=!0,p=e.slice(0,-n.length);break}let k=!m&&/application\/yaml|text\/yaml/i.test(s),c=p.endsWith("/");c&&p!=="/"&&(p=p.slice(0,-1));let h=$e.parse(p,i);if(!h)return M(e);if(h.kind==="package"){let n=Pe(t,h.package_,h.versionSpec);if(!n)return await Be(t,h.package_,h.versionSpec,o===".kan.yml"||k)??M(e);if(o===".kan.yml"||k){let v=t.rawByNsKey.get(`${h.package_}@${n}`);return v!==void 0?P(200,x[".kan.yml"],v):M(e)}let g=t.pkgSelfByVer.get(`${h.package_}@${n}`);if(!g)return M(e);if(o===".css")return P(200,x[".css"],r.renderStylesheet(g));if(!c)return Ae(p+"/");let w=h.versionSpec.kind==="any";if(w&&!r.hasDeclaredView(g)){let v=(t.pkgVersions.get(h.package_)||[]).map($=>$.verStr);return P(200,x[".html"],r.renderPackageVersionList(h.package_,v,g))}return P(200,x[".html"],await r.renderDocument(g,w?{bareOverview:!0}:void 0))}if(h.kind==="resource"){let n=Pe(t,h.package_,h.versionSpec);if(!n)return M(e);let g=t.bySubject.get(`${i}/${h.package_}@${n}/${h.name}`);if(!g)return M(e);switch(o){case".css":return P(200,x[".css"],r.renderStylesheet(g));case".svg":return P(200,x[".svg"],await r.renderSvg(g));case".md":{let w=r.renderRawMarkdown(g);return w===void 0?M(e):P(200,x[".md"],w)}default:return P(200,x[".html"],await r.renderDocument(g))}}return M(e)}import{readFileSync as Oe}from"fs";var ue=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 O;for(let i of Z(this.options.root))try{let o=r.parse(Oe(i,"utf-8")).metadata?.namespace_;if(!o?.version)continue;let m=o.version;e.add(`${o.publisher}/${o.package_}@${m.major}.${m.minor}.${m.patch}`),s.add(`${o.publisher}/${o.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:s},this.workspaceIndex}async modelFor(e,s,r){let i=this.getWorkspaceIndex(),o={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},m=s?r?i.exact.has(`${e}/${s}@${r}`):i.pkgs.has(`${e}/${s}`):[...i.pkgs].some(n=>n.startsWith(`${e}/`)),p,k;if(m&&this.options.root!==void 0){let n=this.options.root;p=`ws:${e}`,k=()=>ce(n,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let n=s?r?`${e}/${s}@${r}`:`${e}/${s}`:e;p=`rm:${n}`,k=()=>le(n,o)}let c=this.models.get(p);if(c)return c;let h=await k();return h.lookRenderer.setLinkMode("open-world"),this.models.set(p,h),h}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:_e()};let i=r[0];if(!i.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 o=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),m=!o&&r.length>=2?r[1]:void 0,p=!o&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,k=await this.modelFor(i,m,p),c=e.endsWith("/")&&r.length>1?"/":"",h="/"+r.slice(1).join("/")+c,n=await pe(k,h,s);return n.headers.Location?{...n,headers:{...n.headers,Location:`/${i}${n.headers.Location}`}}:n}};function _e(){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{z as ClosureScopedRepository,ue as RequestRouter,Re as UNIVERSAL_RENDER_BASE,se as buildRenderDiagnostics,Y as buildRenderStackWarnings,q as deriveImportClosure,_e as landingPage,le as loadResourceModel,ce as loadServerModel,de as renderDiagnosticsHtml,F as renderRefKey,U as resolveRenderContract,pe as route};
64
+ </html>`}var R={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},x=(t,e,c,r)=>({status:t,headers:{"Content-Type":e,...r||{}},body:c}),F=t=>x(404,R[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${t}</p>`),Le=t=>({status:301,headers:{Location:t},body:""}),Oe=t=>({status:302,headers:{Location:t},body:""});function Te(t){switch(t.kind){case"exact":return{operator:ie.Exact,version:W(t.major,t.minor,t.patch)};case"minor-pin":return{operator:ie.Compatible,version:W(t.major,t.minor,0)};case"major-pin":return{operator:ie.Major,version:W(t.major,0,0)};default:return{operator:ie.Any,version:W(0,0,0)}}}async function We(t,e,c,r){if(!r)return null;let o=t.producers?.find(f=>f.canProduce(t.publisher,e));if(!o)return null;let s=await o.resolveVersion(t.publisher,e,Te(c));if(!s)return null;let m=K(s);if(c.kind!=="exact")return Oe(`/${e}/${m}.kan.yml`);let{source:d}=await o.produce(t.publisher,e,s);return x(200,R[".kan.yml"],d)}function Ne(t,e,c){let r=t.pkgVersions.get(e);if(!r||r.length===0)return null;switch(c.kind){case"any":return r[0].verStr;case"major-pin":return r.find(o=>o.version.major===c.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===c.major&&o.version.minor===c.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===c.major&&o.version.minor===c.minor&&o.version.patch===c.patch)?.verStr??null;default:return null}}async function he(t,e,c=""){let{lookRenderer:r,publisher:o}=t;if(e==="/.well-known/kanonak.json")return t.configSource?x(200,R[".json"],t.configSource):x(200,R[".json"],JSON.stringify($e(),null,2));if(e==="/kanonak.lock")return t.lockSource?x(200,R[".kan.yml"],t.lockSource):F(e);if(e==="/.well-known/kanonak-render.json")return x(200,R[".json"],JSON.stringify(ae(t),null,2));if(e==="/.well-known/kanonak-render")return x(200,R[".html"],ge(ae(t)));if(e==="/"||e==="/index.html"||e==="/index.css"){let a=r.publisherSubject(o);return e==="/index.css"?x(200,R[".css"],r.renderStylesheet(a)):x(200,R[".html"],await r.renderDocument(a,{rootIndex:!0}))}let s=".html",m=!1,d=e;for(let a of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(a)){s=a,m=!0,d=e.slice(0,-a.length);break}let f=!m&&/application\/yaml|text\/yaml/i.test(c),l=d.endsWith("/");l&&d!=="/"&&(d=d.slice(0,-1));let h=xe.parse(d,o);if(!h)return F(e);if(h.kind==="package"){let a=Ne(t,h.package_,h.versionSpec);if(!a)return await We(t,h.package_,h.versionSpec,s===".kan.yml"||f)??F(e);if(s===".kan.yml"||f){let v=t.rawByNsKey.get(`${h.package_}@${a}`);return v!==void 0?x(200,R[".kan.yml"],v):F(e)}let g=t.pkgSelfByVer.get(`${h.package_}@${a}`);if(!g)return F(e);if(s===".css")return x(200,R[".css"],r.renderStylesheet(g));if(!l)return Le(d+"/");let S=h.versionSpec.kind==="any";if(S&&!r.hasDeclaredView(g)){let v=(t.pkgVersions.get(h.package_)||[]).map($=>$.verStr);return x(200,R[".html"],r.renderPackageVersionList(h.package_,v,g))}return x(200,R[".html"],await r.renderDocument(g,S?{bareOverview:!0}:void 0))}if(h.kind==="resource"){let a=Ne(t,h.package_,h.versionSpec);if(!a)return F(e);let g=t.bySubject.get(`${o}/${h.package_}@${a}/${h.name}`);if(!g)return F(e);switch(s){case".css":return x(200,R[".css"],r.renderStylesheet(g));case".svg":return x(200,R[".svg"],await r.renderSvg(g));case".md":{let S=r.renderRawMarkdown(g);return S===void 0?F(e):x(200,R[".md"],S)}default:return x(200,R[".html"],await r.renderDocument(g))}}return F(e)}import{readFileSync as Ue}from"fs";var me=class{constructor(e={}){this.options=e}options;models=new Map;workspaceIndex;clearCache(){this.models.clear(),this.workspaceIndex=void 0}getWorkspaceIndex(){if(this.workspaceIndex)return this.workspaceIndex;let e=new Set,c=new Set;if(this.options.root!==void 0){let r=new O;for(let o of ee(this.options.root))try{let s=r.parse(Ue(o,"utf-8")).metadata?.namespace_;if(!s?.version)continue;let m=s.version;e.add(`${s.publisher}/${s.package_}@${m.major}.${m.minor}.${m.patch}`),c.add(`${s.publisher}/${s.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:c},this.workspaceIndex}async modelFor(e,c,r){let o=this.getWorkspaceIndex(),s={...this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},...this.options.log?{log:this.options.log}:{}},m=c?r?o.exact.has(`${e}/${c}@${r}`):o.pkgs.has(`${e}/${c}`):[...o.pkgs].some(a=>a.startsWith(`${e}/`)),d,f;if(m&&this.options.root!==void 0){let a=this.options.root;d=`ws:${e}`,f=()=>pe(a,{publisher:e,...this.options.log?{log:this.options.log}:{}})}else{let a=c?r?`${e}/${c}@${r}`:`${e}/${c}`:e;d=`rm:${a}`,f=()=>ue(a,s)}let l=this.models.get(d);if(l)return l;let h=await f();return h.lookRenderer.setLinkMode("open-world"),this.models.set(d,h),h}async handle(e,c=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:Ie()};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 s=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),m=!s&&r.length>=2?r[1]:void 0,d=!s&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(o,m,d),l=e.endsWith("/")&&r.length>1?"/":"",h="/"+r.slice(1).join("/")+l,a=await he(f,h,c);return a.headers.Location?{...a,headers:{...a.headers,Location:`/${o}${a.headers.Location}`}}:a}};function Ie(){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{G as ClosureScopedRepository,me as RequestRouter,_e as UNIVERSAL_RENDER_BASE,ae as buildRenderDiagnostics,z as buildRenderStackWarnings,H as deriveImportClosure,Ie as landingPage,ue as loadResourceModel,pe as loadServerModel,ge as renderDiagnosticsHtml,N as renderRefKey,q as resolveRenderContract,he as route};