@kanonak-protocol/sdk 4.4.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/{chunk-FSHQVKZ5.js → chunk-7GAOBCNZ.js} +1 -1
- package/dist/{chunk-SW4AJ6GD.js → chunk-BH5TB6XY.js} +1 -1
- package/dist/chunk-EP7CJSV2.js +1 -0
- package/dist/{chunk-YWUKDEZA.js → chunk-FFMZ7GQM.js} +1 -1
- package/dist/{chunk-2D3MZRJB.js → chunk-FXFZZCCD.js} +1 -1
- package/dist/{chunk-NG2YXSH7.js → chunk-G7XXA2JL.js} +1 -1
- package/dist/{chunk-P3MJIJSK.js → chunk-KARUKDEM.js} +1 -1
- package/dist/{chunk-YCV4H6H5.js → chunk-NNUV6K3C.js} +1 -1
- package/dist/{chunk-B73JY5G4.js → chunk-TC4MITSK.js} +1 -1
- package/dist/{chunk-WBRCKPEH.js → chunk-UV6CLM2Y.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/parsing/KanonakParser.d.ts +15 -3
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/search/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/transformations/index.js +1 -1
- package/dist/validation/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-ZYAABYDS.js +0 -1
package/dist/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as fe,b as ge,c as me,d as C,e as E,f as d,g as Ye}from"./chunk-
|
|
1
|
+
import{a as fe,b as ge,c as me,d as C,e as E,f as d,g as Ye}from"./chunk-FXFZZCCD.js";import{a as Qe}from"./chunk-G7XXA2JL.js";import"./chunk-QHABFCRC.js";import{b as L,c as W,d as F}from"./chunk-NNUV6K3C.js";import{a as H}from"./chunk-4NO7MHS7.js";import{a as Pe,b as we,c as he}from"./chunk-UV6CLM2Y.js";import{a as ke,b as be}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as Le,B as We,C as Fe,D as Ge,M as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,k as je,l as ve,m as _e,n as Ie,o as Ae,p as Te,q as Oe,r as Ve,s as $e,t as Ue,u as Me,v as ze,w as Ne,x as Je,y as He,z as qe}from"./chunk-KARUKDEM.js";import"./chunk-SHDHMKMJ.js";import{a as Y,c as le,i as pe}from"./chunk-7GAOBCNZ.js";import{a as q}from"./chunk-EP7CJSV2.js";import{a as ye}from"./chunk-UK2OIPAB.js";import"./chunk-PBNVHBS3.js";import{b as ue,c as de}from"./chunk-VKTFLHCW.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-T3JR2SV6.js";import{a as Z}from"./chunk-FUUTGGJS.js";import{c as O,d as V,e as $,f as U,g as M,h as z,i as N,j as J}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",Ze=1,g=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,Ze);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
|
|
2
2
|
Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await rr(t)),o&&(s.nonce=o),await er(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function er(n,r,e){let t=v(JSON.stringify(n)),o=v(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=D(s);return`${t}.${o}.${l}`}async function rr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return D(e)}function v(n){let r=new TextEncoder().encode(n);return D(r.buffer)}function D(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var tr=300*1e3,S=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new g,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=x(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let f=await k();a=f.keys,s=f.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let f=await this.registerClient(t.registrationEndpoint);if(!f)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=f.clientId,c=f.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=nr(),p=await or(m),R=sr(),A=ir(t.authorizationEndpoint,i,this.callbackUrl,R,p),y=await this.openAuthPopup(A,R);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==R)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let T={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,T),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await fetch(e);if(!t.ok)continue;let o=await t.json();return{issuer:w(o.issuer),authorizationEndpoint:w(o.authorization_endpoint),tokenEndpoint:w(o.token_endpoint),registrationEndpoint:w(o.registration_endpoint),revocationEndpoint:w(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},tr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await K(l,"POST",r));try{let m=await fetch(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function nr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function or(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function sr(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function ir(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Ne as AmbiguousReferenceRule,se as BooleanStatement,g as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,Me as DefinitionPropertyReferenceRule,ge as EdgeType,Y as EmbeddedKanonak,je as EmbeddedKanonakTypeRule,ae as EmbeddedStatement,me as GraphBuilder,F as HttpKanonakDocumentRepository,ve as ImportExistenceRule,H as InMemoryKanonakDocumentRepository,Ue as InstancePropertyReferenceRule,G as Kanonak,we as KanonakDocumentPositions,pe as KanonakObjectParser,Xe as KanonakObjectValidator,q as KanonakParser,Z as KanonakUri,ke as KanonakUriBuilder,ce as ListStatement,Ge as MarkdownLinkRule,le as MarkdownStatement,$e as NamespaceImportCycleRule,De as NamespacePrefixRule,fe as NodeType,oe as NumberStatement,He as ObjectPropertyImportRule,qe as ObjectPropertyValueValidationRule,Se as OntologyValidationError,Ke as OntologyValidationResult,Le as PropertyDomainRule,Ae as PropertyHierarchyCycleRule,Pe as PropertyMetadata,Je as PropertyRangeReferenceRule,Te as PropertyRangeRequiredRule,Ce as PropertyTypeSpecificityRule,We as PropertyValueTypeRule,L as PublisherConfigResolver,W as PublisherIndex,ee as ReferenceKanonak,ie as ReferenceStatement,Be as ResourceNamingRule,ue as ResourceResolver,ye as ResourceTypeClassifier,te as ScalarStatement,re as Statement,ne as StringStatement,Oe as SubClassOfReferenceRule,Ve as SubPropertyOfReferenceRule,Q as SubjectKanonak,Ee as SubjectKanonakTypeRequiredRule,de as TypeResolver,_e as UnresolvedReferenceRule,Re as ValidationContext,xe as ValidationSeverity,ze as XsdImportRule,x as browserServerSupportsDPoP,Ye as buildOntologyModel,O as compareVersions,K as createBrowserDPoPProof,U as createVersion,Qe as findDerivation,be as findInstancesByType,$ as formatVersion,k as generateBrowserDPoPKeyPair,_ as generateBrowserDPoPKeys,E as hasValidToken,b as importDPoPKeys,z as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,M as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U}from"./chunk-ZYAABYDS.js";import{b as F,c as V,i as E}from"./chunk-VKTFLHCW.js";import{a as B,b as _,c as x,d as k,g as $,h as T,i as C,j as K,k as w,l as j}from"./chunk-T3JR2SV6.js";import{j as L}from"./chunk-2ACBWC7K.js";var S=class extends _{name};var I=class extends B{value;carrier;lexical};var R=class extends ${links=[]};var W=n=>({publisher:"kanonak.org",package_:"core-xsd",name:n}),J=n=>({publisher:"kanonak.org",package_:"core-rdf",name:n}),Y=(p=>(p.Integer="integer",p.Decimal="decimal",p.Double="double",p.Float="float",p.Boolean="boolean",p.String="string",p.AnyUri="anyURI",p.LangString="langString",p.DateTime="dateTime",p.Date="date",p.Time="time",p.HexBinary="hexBinary",p.Base64Binary="base64Binary",p))(Y||{});function v(n){return`${n.publisher}/${n.package_}/${n.name}`}var Q=[["integer","integer"],["long","integer"],["int","integer"],["short","integer"],["byte","integer"],["unsignedLong","integer"],["unsignedInt","integer"],["unsignedShort","integer"],["unsignedByte","integer"],["nonNegativeInteger","integer"],["positiveInteger","integer"],["nonPositiveInteger","integer"],["negativeInteger","integer"],["decimal","decimal"],["double","double"],["float","float"],["boolean","boolean"],["string","string"],["normalizedString","string"],["token","string"],["anyURI","anyURI"],["dateTime","dateTime"],["date","date"],["time","time"],["hexBinary","hexBinary"],["base64Binary","base64Binary"]],ee=new Map(Q.map(([n,e])=>[v(W(n)),e])),ne=v(J("langString"));function M(n){let e=v(n);return e===ne?"langString":ee.get(e)}function te(n){let e=n.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`canonicalInteger: '${n}' is not a valid xsd:integer lexical`);return BigInt(e.replace(/^\+/,"")).toString()}function re(n){let e=n.trim(),t=/^([+-]?)(\d*)(?:\.(\d*))?$/.exec(e);if(!t||t[2]===""&&(t[3]??"")==="")throw new Error(`canonicalDecimal: '${n}' is not a valid xsd:decimal lexical`);let a=t[1]==="-"?"-":"",r=(t[2]??"").replace(/^0+/,"")||"0",i=(t[3]??"").replace(/0+$/,""),o=i.length>0?`${r}.${i}`:r;return o==="0"?"0":`${a}${o}`}function Z(n,e,t){let a=n.trim();if(a==="NaN")return"NaN";if(a==="INF")return"INF";if(a==="-INF")return"-INF";if(!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(a))throw new Error(`canonical${t}: '${n}' is not a valid xsd:${t.toLowerCase()} lexical`);let r=e(Number(a));if(!Number.isFinite(r))throw new Error(`canonical${t}: '${n}' is out of the finite range`);return Object.is(r,-0)?"0":String(r)}function ae(n){return Z(n,e=>e,"Double")}function oe(n){return Z(n,e=>Math.fround(e),"Float")}function ie(n){let e=n.trim();if(e==="true"||e==="1")return"true";if(e==="false"||e==="0")return"false";throw new Error(`canonicalBoolean: '${n}' is not a valid xsd:boolean lexical`)}function z(n){return n.normalize("NFC")}function se(n){return n.normalize("NFC")}function ce(n){let e=n.trim();if(!/^([0-9A-Fa-f]{2})*$/.test(e))throw new Error(`canonicalHexBinary: '${n}' is not a valid xsd:hexBinary lexical`);return e.toUpperCase()}function fe(n){let e=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)throw new Error(`canonicalBase64: '${n}' is not a valid xsd:base64Binary lexical`);return Buffer.from(e,"base64").toString("base64")}var D=n=>n<10?`0${n}`:`${n}`;function P(n){let e=n.startsWith("-"),t=(e?n.slice(1):n).replace(/^0+/,"")||"0",a=t.length<4?t.padStart(4,"0"):t;return`${e?"-":""}${a}`}function H(n){if(!n)return"";let e=n.replace(/^\./,"").replace(/0+$/,"");return e.length>0?`.${e}`:""}function X(n){return n?n==="Z"||n==="+00:00"||n==="-00:00"?"Z":n:""}function pe(n){return n==="Z"?0:(n[0]==="-"?-1:1)*(Number(n.slice(1,3))*60+Number(n.slice(4,6)))}var ue=/^(-?\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,le=/^(-?\d{4,})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,me=/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/;function de(n){let e=ue.exec(n.trim());if(!e)throw new Error(`canonicalDateTime: '${n}' is not a valid xsd:dateTime lexical`);let[,t,a,r,i,o,c,f,u]=e,d=H(f);if(!u)return`${P(t)}-${a}-${r}T${i}:${o}:${c}${d}`;let m=new Date(0);m.setUTCFullYear(Number(t),Number(a)-1,Number(r)),m.setUTCHours(Number(i),Number(o),Number(c),0);let s=new Date(m.getTime()-pe(u)*6e4);return`${P(String(s.getUTCFullYear()))}-${D(s.getUTCMonth()+1)}-${D(s.getUTCDate())}T${D(s.getUTCHours())}:${D(s.getUTCMinutes())}:${D(s.getUTCSeconds())}${d}Z`}function ge(n){let e=le.exec(n.trim());if(!e)throw new Error(`canonicalDate: '${n}' is not a valid xsd:date lexical`);let[,t,a,r,i]=e;return`${P(t)}-${a}-${r}${X(i)}`}function ye(n){let e=me.exec(n.trim());if(!e)throw new Error(`canonicalTime: '${n}' is not a valid xsd:time lexical`);let[,t,a,r,i,o]=e,c=H(i),f=t;return t==="24"&&a==="00"&&r==="00"&&c===""&&(f="00"),`${f}:${a}:${r}${c}${X(o)}`}function Re(n,e){switch(n){case"integer":return te(e);case"decimal":return re(e);case"double":return ae(e);case"float":return oe(e);case"boolean":return ie(e);case"string":return z(e);case"anyURI":return se(e);case"langString":return z(e);case"dateTime":return de(e);case"date":return ge(e);case"time":return ye(e);case"hexBinary":return ce(e);case"base64Binary":return fe(e)}}var ke=/\[\[([^\[\]\n]+)\]\]/g,be=/\[\[/g,G=/```[\s\S]*?```|`[^`\n]*`/g;function he(n){let e=[];for(let t of n.matchAll(G))e.push([t.index,t.index+t[0].length]);return e}function Te(n){if(!n||!n.includes("[["))return[];let e=he(n),t=i=>e.some(([o,c])=>i>=o&&i<c),a=new Set(A(n).map(i=>i.startOffset)),r=[];for(let i of n.matchAll(be)){let o=i.index;if(t(o)||a.has(o))continue;let c=n.slice(o,o+48).replace(/\s+/g," ").trim();r.push({startOffset:o,snippet:c})}return r}function A(n){if(!n||!n.includes("[["))return[];let e=[];for(let r of n.matchAll(G))e.push([r.index,r.index+r[0].length]);let t=r=>e.some(([i,o])=>r>=i&&r<o),a=[];for(let r of n.matchAll(ke)){let i=r.index;if(t(i))continue;let o=r[1],c=o.indexOf("|"),f=(c===-1?o:o.slice(0,c)).trim();if(f.length===0)continue;let u=c===-1?"":o.slice(c+1).trim(),d={reference:f,startOffset:i,endOffset:i+r[0].length};u.length>0&&(d.displayText=u),a.push(d)}return a}var q=class{constructor(e){}async parseKanonaks(e){let t=[],a=await e.getAllDocumentsAsync(),r=new F(e),i=new V(r);for(let s of a){let p=s.metadata.namespace_?.toString()??"";for(let[l,y]of Object.entries(s.body)){let g=new x,b=this.resolveCanonicalEntity(l,s,p);g.namespace=b.namespace,g.name=b.name,g.statement=[];let h=await this.parseStatements(y,s,r,i,e);g.statement.push(...h),t.push(g)}}let o=new Map,c=new Map,f=[];for(let s of t)if(s instanceof x){let p=`${s.namespace}/${s.name}`,l=o.get(p);if(l){let y=c.get(p);for(let g of s.statement){let b=O(g);y.has(b)||(y.add(b),l.statement.push(g))}}else{let y=new Set,g=[];for(let b of s.statement){let h=O(b);y.has(h)||(y.add(h),g.push(b))}s.statement=g,c.set(p,y),o.set(p,s),f.push(s)}}else f.push(s);let u=new Set;for(let s of f)if(s instanceof x){let p=s.namespace||"",l=p.indexOf("/"),y=l>=0?p.slice(0,l):"",g=l>=0?p.slice(l+1):"",b=g.indexOf("@"),h=b>=0?g.slice(0,b):g;u.add(`${y}/${h}/${s.name}`)}let d=s=>u.has(`${s.publisher}/${s.package_}/${s.name}`),m=new Map;for(let s of["core-rdf","core-owl","core-kanonak"]){let p=await e.getDocumentsByNamespaceAsync("kanonak.org",s);m.set(s,L(p).chosen?.metadata.namespace_?.version??void 0)}for(let s of f)s instanceof x&&this.canonicalizeStatementBuiltins(s.statement,d,m);return f}canonicalizeStatementBuiltins(e,t,a){for(let r of e){let i=r.predicate?.subject;if(E(i,t,a),r instanceof K)r.object instanceof k&&E(r.object.subject,t,a);else if(r instanceof w)r.object&&this.canonicalizeStatementBuiltins(r.object.statement,t,a);else if(r instanceof j)for(let o of r.object??[])o instanceof k?E(o.subject,t,a):o instanceof S&&this.canonicalizeStatementBuiltins(o.statement,t,a)}}resolveCanonicalEntity(e,t,a){if(!e.includes(".")||!t.metadata?.imports)return{namespace:a,name:e};let r=e.indexOf("."),i=e.substring(0,r),o=e.substring(r+1);for(let[c,f]of Object.entries(t.metadata.imports))for(let u of f)if((u.alias??u.packageName)===i){let m=u.version;return{namespace:`${c}/${u.packageName}@${m.major}.${m.minor}.${m.patch}`,name:o}}return{namespace:a,name:e}}async parseStatements(e,t,a,r,i){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[c,f]of Object.entries(e))try{let u=await this.getPropertyMetadata(c,t,a,i,r);if(!u)continue;let d=await this.parsePropertyValue(c,f,u,t,a,r,i);d&&o.push(d)}catch(u){throw new Error(`Failed to parse property '${c}': ${u.message}`,{cause:u})}return o}async getPropertyMetadata(e,t,a,r,i){let o=await a.resolveEntityAsync(e,t);if(!o)return;let c=o.entity,f=c.type?.toString()??"",u=f.includes(".")?f.substring(f.lastIndexOf(".")+1):f;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(u))return;let m=i.getPropertyTypeClassification(f),s=c.range?.toString(),p;if(m==="ObjectProperty")p="ObjectProperty";else if(m==="DatatypeProperty")p="DatatypeProperty";else{let g=s&&s.includes(".")?s.substring(s.lastIndexOf(".")+1):s??"";(s?i.isKnownXsdDatatypeName(s):!1)||g==="Literal"?p="DatatypeProperty":p="ObjectProperty"}let l;if(s){let g=t;if(o.isImported&&o.definedInNamespace){if(typeof r.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${e}': the parse repository cannot fetch defining document '${o.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let h=await r.getDocumentAsync(o.definedInNamespace);if(!h)throw new Error(`Cannot resolve the range of imported property '${e}': defining document '${o.definedInNamespace}' was not found in the repository.`);g=h}l=(await a.resolveEntityAsync(s,g))?.uri}return{propertyUri:o.uri.toString(),propertyType:p,range:s,rangeUri:l,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,a,r,i,o,c){let f=a.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(f,t,a,r,i,o,c);if(a.propertyType==="DatatypeProperty")return this.parseDatatypeValue(f,t,a,r,i,o);if(a.propertyType==="ObjectProperty")return this.parseObjectValue(f,t,a,r,i,o,c)}}async parseDatatypeValue(e,t,a,r,i,o){let c;if(typeof t=="string"){if(o.isSubstitutableDatatype(a.rangeUri))return await this.parseSubstitutableValue(e,t,r,i);c=t}else if(typeof t=="number"||typeof t=="boolean")c=String(t);else return;return this.typedScalarStatement(e,c,a)}typedScalarStatement(e,t,a){let r=k.parse(e),i=a.rangeUri?M(a.rangeUri):void 0;if(i==="boolean"){let c=new C;return c.predicate=r,c.object=t==="true"||t==="1",c.carrier=i,c.lexical=t,c}if(i==="integer"||i==="decimal"||i==="double"||i==="float"){let c=new T;return c.predicate=r,c.object=Number(t),c.carrier=i,c.lexical=t,c}let o=$.parse(e,t);return i&&(o.carrier=i,o.lexical=t),o}typedListLiteral(e,t){let a=new I,r=t.rangeUri?M(t.rangeUri):void 0;return r==="boolean"?a.value=e==="true"||e==="1":r==="integer"||r==="decimal"||r==="double"||r==="float"?a.value=Number(e):a.value=e,r&&(a.carrier=r,a.lexical=e),a}async parseSubstitutableValue(e,t,a,r){let i=new R;i.predicate=k.parse(e),i.object=t;for(let o of A(t)){let c=await r.resolveEntityAsync(o.reference,a),f;c&&(f=new k,f.subject=c.uri);let u={reference:o.reference,startOffset:o.startOffset,endOffset:o.endOffset};o.displayText!==void 0&&(u.displayText=o.displayText),f!==void 0&&(u.target=f),i.links.push(u)}return i}async parseObjectValue(e,t,a,r,i,o,c){if(typeof t=="string"){let f=await this.resolveReference(t,r,i);if(!f)return;let u=new K;return u.predicate=k.parse(e),u.object=f,u}if(typeof t=="object"&&!Array.isArray(t)){let f=new S;if(f.statement=await this.parseStatements(t,r,i,o,c),f.statement.length>0){let m=new w;return m.predicate=k.parse(e),m.object=f,m}let u=[];for(let[m,s]of Object.entries(t))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let p=new S;p.name=m,p.statement=await this.parseStatements(s,r,i,o,c),u.push(p)}else if(typeof s=="string"){let p=await this.resolveReference(s,r,i);p&&u.push(p)}if(u.length>0){let m=new j;return m.predicate=k.parse(e),m.object=u,m}let d=new w;return d.predicate=k.parse(e),d.object=f,d}}async parseListValue(e,t,a,r,i,o,c){let f=[],u=a.propertyType==="DatatypeProperty",d=a.rangeUri?.publisher==="kanonak.org"&&a.rangeUri?.package_==="core-rdf"&&a.rangeUri?.name==="List"||!a.rangeUri&&(a.range?.includes(".")?a.range.substring(a.range.lastIndexOf(".")+1):a.range)==="List";for(let s of t){let p=typeof s=="string"||typeof s=="number"||typeof s=="boolean";if(u&&p){let l=typeof s=="string"?s:String(s);f.push(this.typedListLiteral(l,a));continue}if(d&&p){if(typeof s=="string"){let l=await i.resolveEntityAsync(s,r);if(l){let y=new k;y.subject=l.uri,f.push(y)}else{let y=new I;y.value=s,f.push(y)}}else{let l=new I;l.value=s,f.push(l)}continue}if(typeof s=="string"){let l=await this.resolveReference(s,r,i);l&&f.push(l)}else if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let l=new S;l.statement=await this.parseStatements(s,r,i,o,c),f.push(l)}}let m=new j;return m.predicate=k.parse(e),m.object=f,m}async resolveReference(e,t,a){let r=await a.resolveEntityAsync(e,t);if(r){let o=new k;return o.subject=r.uri,o}let i=t.metadata?.namespace_;if(i){let{KanonakUri:o}=await import("./KanonakUri-4VJGV3FN.js"),c=i.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let u=e.indexOf("."),d=e.substring(0,u),m=e.substring(u+1);if(t.metadata?.imports){for(let[s,p]of Object.entries(t.metadata.imports))for(let l of p)if((l.alias??l.packageName)===d){let g=new k;return g.subject=new o(s,l.packageName,m,l.version),g}}}let f=new k;return f.subject=new o(i.publisher,i.package_,e,c),f}return null}async saveKanonaks(e,t){let a=new Map;for(let r of e)r instanceof x&&r.namespace&&(a.has(r.namespace)||a.set(r.namespace,[]),a.get(r.namespace).push(r));for(let[r,i]of a){let o=await this.convertKanonaksToDocument(r,i),c=`${r.split("@")[0]}.yml`;await t.saveDocumentAsync(o,c)}}async serializeToYaml(e,t){let a=e.filter(o=>o instanceof x&&o.namespace===t);if(a.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let r=await this.convertKanonaksToDocument(t,a);return new U().save(r)}async convertKanonaksToDocument(e,t){let r={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let c of Object.values(this.imports))o.push(...c);return o}},body:{}},i=new Map;for(let o of t){let c={};for(let f of o.statement){let[u,d]=this.convertStatementToProperty(f);u&&d!==null&&d!==void 0&&(c[u]=d),this.collectImportsFromStatement(f,e,i)}r.body[o.name]=c}return r}convertStatementToProperty(e){if(e instanceof $)return[e.predicate.subject.name,e.object];if(e instanceof T)return[e.predicate.subject.name,e.object];if(e instanceof C)return[e.predicate.subject.name,e.object];if(e instanceof K)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof j){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let a of e)a instanceof k?t.push(a.subject.name):a instanceof S&&t.push(this.convertEmbeddedKanonakToValue(a));return t}convertEmbeddedKanonakToValue(e){let t={};for(let a of e.statement){let[r,i]=this.convertStatementToProperty(a);r&&i!==null&&i!==void 0&&(t[r]=i)}return t}collectImportsFromStatement(e,t,a){}};function O(n){let e=n.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+Se(n)}function Se(n){return n instanceof R?"m:"+String(n.object):n instanceof $?"s:"+String(n.object):n instanceof T?"n:"+String(n.object):n instanceof C?"b:"+String(n.object):n instanceof K?"r:"+N(n.object):n instanceof w?"e:"+N(n.object):n instanceof j?"l:["+(n.object??[]).map(N).join("|")+"]":"x"}function N(n){if(!n)return"";if(n instanceof k){let e=n.subject;return"R("+(e?`${e.publisher}/${e.package_}/${e.name}`:"")+")"}return n instanceof S?"E("+(n.statement??[]).map(O).join(";")+")":n instanceof I?"L("+String(n.value)+")":"N"}export{S as a,I as b,R as c,Y as d,M as e,Re as f,Te as g,A as h,q as i};
|
|
1
|
+
import{a as U}from"./chunk-EP7CJSV2.js";import{b as F,c as V,i as P}from"./chunk-VKTFLHCW.js";import{a as B,b as _,c as x,d as k,g as $,h as T,i as E,j as K,k as w,l as j}from"./chunk-T3JR2SV6.js";import{j as L}from"./chunk-2ACBWC7K.js";var S=class extends _{name};var I=class extends B{value;carrier;lexical};var R=class extends ${links=[]};var W=n=>({publisher:"kanonak.org",package_:"core-xsd",name:n}),J=n=>({publisher:"kanonak.org",package_:"core-rdf",name:n}),Y=(p=>(p.Integer="integer",p.Decimal="decimal",p.Double="double",p.Float="float",p.Boolean="boolean",p.String="string",p.AnyUri="anyURI",p.LangString="langString",p.DateTime="dateTime",p.Date="date",p.Time="time",p.HexBinary="hexBinary",p.Base64Binary="base64Binary",p))(Y||{});function v(n){return`${n.publisher}/${n.package_}/${n.name}`}var Q=[["integer","integer"],["long","integer"],["int","integer"],["short","integer"],["byte","integer"],["unsignedLong","integer"],["unsignedInt","integer"],["unsignedShort","integer"],["unsignedByte","integer"],["nonNegativeInteger","integer"],["positiveInteger","integer"],["nonPositiveInteger","integer"],["negativeInteger","integer"],["decimal","decimal"],["double","double"],["float","float"],["boolean","boolean"],["string","string"],["normalizedString","string"],["token","string"],["anyURI","anyURI"],["dateTime","dateTime"],["date","date"],["time","time"],["hexBinary","hexBinary"],["base64Binary","base64Binary"]],ee=new Map(Q.map(([n,e])=>[v(W(n)),e])),ne=v(J("langString"));function M(n){let e=v(n);return e===ne?"langString":ee.get(e)}function te(n){let e=n.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`canonicalInteger: '${n}' is not a valid xsd:integer lexical`);return BigInt(e.replace(/^\+/,"")).toString()}function re(n){let e=n.trim(),t=/^([+-]?)(\d*)(?:\.(\d*))?$/.exec(e);if(!t||t[2]===""&&(t[3]??"")==="")throw new Error(`canonicalDecimal: '${n}' is not a valid xsd:decimal lexical`);let a=t[1]==="-"?"-":"",r=(t[2]??"").replace(/^0+/,"")||"0",i=(t[3]??"").replace(/0+$/,""),o=i.length>0?`${r}.${i}`:r;return o==="0"?"0":`${a}${o}`}function Z(n,e,t){let a=n.trim();if(a==="NaN")return"NaN";if(a==="INF")return"INF";if(a==="-INF")return"-INF";if(!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(a))throw new Error(`canonical${t}: '${n}' is not a valid xsd:${t.toLowerCase()} lexical`);let r=e(Number(a));if(!Number.isFinite(r))throw new Error(`canonical${t}: '${n}' is out of the finite range`);return Object.is(r,-0)?"0":String(r)}function ae(n){return Z(n,e=>e,"Double")}function oe(n){return Z(n,e=>Math.fround(e),"Float")}function ie(n){let e=n.trim();if(e==="true"||e==="1")return"true";if(e==="false"||e==="0")return"false";throw new Error(`canonicalBoolean: '${n}' is not a valid xsd:boolean lexical`)}function z(n){return n.normalize("NFC")}function se(n){return n.normalize("NFC")}function ce(n){let e=n.trim();if(!/^([0-9A-Fa-f]{2})*$/.test(e))throw new Error(`canonicalHexBinary: '${n}' is not a valid xsd:hexBinary lexical`);return e.toUpperCase()}function fe(n){let e=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)throw new Error(`canonicalBase64: '${n}' is not a valid xsd:base64Binary lexical`);return Buffer.from(e,"base64").toString("base64")}var D=n=>n<10?`0${n}`:`${n}`;function C(n){let e=n.startsWith("-"),t=(e?n.slice(1):n).replace(/^0+/,"")||"0",a=t.length<4?t.padStart(4,"0"):t;return`${e?"-":""}${a}`}function H(n){if(!n)return"";let e=n.replace(/^\./,"").replace(/0+$/,"");return e.length>0?`.${e}`:""}function X(n){return n?n==="Z"||n==="+00:00"||n==="-00:00"?"Z":n:""}function pe(n){return n==="Z"?0:(n[0]==="-"?-1:1)*(Number(n.slice(1,3))*60+Number(n.slice(4,6)))}var ue=/^(-?\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,le=/^(-?\d{4,})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,me=/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/;function de(n){let e=ue.exec(n.trim());if(!e)throw new Error(`canonicalDateTime: '${n}' is not a valid xsd:dateTime lexical`);let[,t,a,r,i,o,c,f,u]=e,d=H(f);if(!u)return`${C(t)}-${a}-${r}T${i}:${o}:${c}${d}`;let l=new Date(0);l.setUTCFullYear(Number(t),Number(a)-1,Number(r)),l.setUTCHours(Number(i),Number(o),Number(c),0);let s=new Date(l.getTime()-pe(u)*6e4);return`${C(String(s.getUTCFullYear()))}-${D(s.getUTCMonth()+1)}-${D(s.getUTCDate())}T${D(s.getUTCHours())}:${D(s.getUTCMinutes())}:${D(s.getUTCSeconds())}${d}Z`}function ge(n){let e=le.exec(n.trim());if(!e)throw new Error(`canonicalDate: '${n}' is not a valid xsd:date lexical`);let[,t,a,r,i]=e;return`${C(t)}-${a}-${r}${X(i)}`}function ye(n){let e=me.exec(n.trim());if(!e)throw new Error(`canonicalTime: '${n}' is not a valid xsd:time lexical`);let[,t,a,r,i,o]=e,c=H(i),f=t;return t==="24"&&a==="00"&&r==="00"&&c===""&&(f="00"),`${f}:${a}:${r}${c}${X(o)}`}function Re(n,e){switch(n){case"integer":return te(e);case"decimal":return re(e);case"double":return ae(e);case"float":return oe(e);case"boolean":return ie(e);case"string":return z(e);case"anyURI":return se(e);case"langString":return z(e);case"dateTime":return de(e);case"date":return ge(e);case"time":return ye(e);case"hexBinary":return ce(e);case"base64Binary":return fe(e)}}var ke=/\[\[([^\[\]\n]+)\]\]/g,be=/\[\[/g,G=/```[\s\S]*?```|`[^`\n]*`/g;function he(n){let e=[];for(let t of n.matchAll(G))e.push([t.index,t.index+t[0].length]);return e}function Te(n){if(!n||!n.includes("[["))return[];let e=he(n),t=i=>e.some(([o,c])=>i>=o&&i<c),a=new Set(A(n).map(i=>i.startOffset)),r=[];for(let i of n.matchAll(be)){let o=i.index;if(t(o)||a.has(o))continue;let c=n.slice(o,o+48).replace(/\s+/g," ").trim();r.push({startOffset:o,snippet:c})}return r}function A(n){if(!n||!n.includes("[["))return[];let e=[];for(let r of n.matchAll(G))e.push([r.index,r.index+r[0].length]);let t=r=>e.some(([i,o])=>r>=i&&r<o),a=[];for(let r of n.matchAll(ke)){let i=r.index;if(t(i))continue;let o=r[1],c=o.indexOf("|"),f=(c===-1?o:o.slice(0,c)).trim();if(f.length===0)continue;let u=c===-1?"":o.slice(c+1).trim(),d={reference:f,startOffset:i,endOffset:i+r[0].length};u.length>0&&(d.displayText=u),a.push(d)}return a}var q=class{constructor(e){}async parseKanonaks(e){let t=[],a=await e.getAllDocumentsAsync(),r=new F(e),i=new V(r);for(let s of a){let p=s.metadata.namespace_?.toString()??"";for(let[m,g]of Object.entries(s.body)){let y=new x,b=this.resolveCanonicalEntity(m,s,p);y.namespace=b.namespace,y.name=b.name,y.statement=[];let h=await this.parseStatements(g,s,r,i,e);y.statement.push(...h),t.push(y)}}let o=new Map,c=new Map,f=[];for(let s of t)if(s instanceof x){let p=`${s.namespace}/${s.name}`,m=o.get(p);if(m){let g=c.get(p);for(let y of s.statement){let b=O(y);g.has(b)||(g.add(b),m.statement.push(y))}}else{let g=new Set,y=[];for(let b of s.statement){let h=O(b);g.has(h)||(g.add(h),y.push(b))}s.statement=y,c.set(p,g),o.set(p,s),f.push(s)}}else f.push(s);let u=new Set;for(let s of f)if(s instanceof x){let p=s.namespace||"",m=p.indexOf("/"),g=m>=0?p.slice(0,m):"",y=m>=0?p.slice(m+1):"",b=y.indexOf("@"),h=b>=0?y.slice(0,b):y;u.add(`${g}/${h}/${s.name}`)}let d=s=>u.has(`${s.publisher}/${s.package_}/${s.name}`),l=new Map;for(let s of["core-rdf","core-owl","core-kanonak"]){let p=await e.getDocumentsByNamespaceAsync("kanonak.org",s);l.set(s,L(p).chosen?.metadata.namespace_?.version??void 0)}for(let s of f)s instanceof x&&this.canonicalizeStatementBuiltins(s.statement,d,l);return f}canonicalizeStatementBuiltins(e,t,a){for(let r of e){let i=r.predicate?.subject;if(P(i,t,a),r instanceof K)r.object instanceof k&&P(r.object.subject,t,a);else if(r instanceof w)r.object&&this.canonicalizeStatementBuiltins(r.object.statement,t,a);else if(r instanceof j)for(let o of r.object??[])o instanceof k?P(o.subject,t,a):o instanceof S&&this.canonicalizeStatementBuiltins(o.statement,t,a)}}resolveCanonicalEntity(e,t,a){if(!e.includes(".")||!t.metadata?.imports)return{namespace:a,name:e};let r=e.indexOf("."),i=e.substring(0,r),o=e.substring(r+1);for(let[c,f]of Object.entries(t.metadata.imports))for(let u of f)if((u.alias??u.packageName)===i){let l=u.version;return{namespace:`${c}/${u.packageName}@${l.major}.${l.minor}.${l.patch}`,name:o}}return{namespace:a,name:e}}async parseStatements(e,t,a,r,i){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[c,f]of Object.entries(e))try{let u=await this.getPropertyMetadata(c,t,a,i,r);if(!u)continue;let d=await this.parsePropertyValue(c,f,u,t,a,r,i);d&&o.push(d)}catch(u){throw new Error(`Failed to parse property '${c}': ${u.message}`,{cause:u})}return o}async getPropertyMetadata(e,t,a,r,i){let o=await a.resolveEntityAsync(e,t);if(!o)return;let c=o.entity,f=c.type?.toString()??"",u=f.includes(".")?f.substring(f.lastIndexOf(".")+1):f;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(u))return;let l=i.getPropertyTypeClassification(f),s=c.range?.toString(),p;if(l==="ObjectProperty")p="ObjectProperty";else if(l==="DatatypeProperty")p="DatatypeProperty";else{let y=s&&s.includes(".")?s.substring(s.lastIndexOf(".")+1):s??"";(s?i.isKnownXsdDatatypeName(s):!1)||y==="Literal"?p="DatatypeProperty":p="ObjectProperty"}let m;if(s){let y=t;if(o.isImported&&o.definedInNamespace){if(typeof r.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${e}': the parse repository cannot fetch defining document '${o.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let h=await r.getDocumentAsync(o.definedInNamespace);if(!h)throw new Error(`Cannot resolve the range of imported property '${e}': defining document '${o.definedInNamespace}' was not found in the repository.`);y=h}m=(await a.resolveEntityAsync(s,y))?.uri}return{propertyUri:o.uri.toString(),propertyType:p,range:s,rangeUri:m,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,a,r,i,o,c){let f=a.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(f,t,a,r,i,o,c);if(a.propertyType==="DatatypeProperty")return this.parseDatatypeValue(f,t,a,r,i,o);if(a.propertyType==="ObjectProperty")return this.parseObjectValue(f,t,a,r,i,o,c)}}async parseDatatypeValue(e,t,a,r,i,o){let c;if(typeof t=="string"){if(o.isSubstitutableDatatype(a.rangeUri))return await this.parseSubstitutableValue(e,t,r,i);c=t}else if(typeof t=="number"||typeof t=="boolean")c=String(t);else return;return this.typedScalarStatement(e,c,a)}typedScalarStatement(e,t,a){let r=k.parse(e),i=a.rangeUri?M(a.rangeUri):void 0;if(i==="boolean"){let c=new E;return c.predicate=r,c.object=t==="true"||t==="1",c.carrier=i,c.lexical=t,c}if(i==="integer"||i==="decimal"||i==="double"||i==="float"){let c=new T;return c.predicate=r,c.object=Number(t),c.carrier=i,c.lexical=t,c}let o=$.parse(e,t);return i&&(o.carrier=i,o.lexical=t),o}typedListLiteral(e,t){let a=new I,r=t.rangeUri?M(t.rangeUri):void 0;return r==="boolean"?a.value=e==="true"||e==="1":r==="integer"||r==="decimal"||r==="double"||r==="float"?a.value=Number(e):a.value=e,r&&(a.carrier=r,a.lexical=e),a}async parseSubstitutableValue(e,t,a,r){let i=new R;i.predicate=k.parse(e),i.object=t;for(let o of A(t)){let c=await r.resolveEntityAsync(o.reference,a),f;c&&(f=new k,f.subject=c.uri);let u={reference:o.reference,startOffset:o.startOffset,endOffset:o.endOffset};o.displayText!==void 0&&(u.displayText=o.displayText),f!==void 0&&(u.target=f),i.links.push(u)}return i}async parseObjectValue(e,t,a,r,i,o,c){if(typeof t=="string"){let f=await this.resolveReference(t,r,i);if(!f)return;let u=new K;return u.predicate=k.parse(e),u.object=f,u}if(typeof t=="object"&&!Array.isArray(t)){let f=new S;if(f.statement=await this.parseStatements(t,r,i,o,c),f.statement.length>0){let l=new w;return l.predicate=k.parse(e),l.object=f,l}let u=[];for(let[l,s]of Object.entries(t))if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let p=new S;p.name=l,p.statement=await this.parseStatements(s,r,i,o,c),u.push(p)}else if(typeof s=="string"){let p=await this.resolveReference(s,r,i);p&&u.push(p)}if(u.length>0){let l=new j;return l.predicate=k.parse(e),l.object=u,l}let d=new w;return d.predicate=k.parse(e),d.object=f,d}}async parseListValue(e,t,a,r,i,o,c){let f=[],u=a.propertyType==="DatatypeProperty",d=a.rangeUri?.publisher==="kanonak.org"&&a.rangeUri?.package_==="core-rdf"&&a.rangeUri?.name==="List"||!a.rangeUri&&(a.range?.includes(".")?a.range.substring(a.range.lastIndexOf(".")+1):a.range)==="List";for(let s of t){let p=typeof s=="string"||typeof s=="number"||typeof s=="boolean";if(u&&p){let m=typeof s=="string"?s:String(s);f.push(this.typedListLiteral(m,a));continue}if(d&&p){if(typeof s=="string"){let m=await i.resolveEntityAsync(s,r);if(m){let g=new k;g.subject=m.uri,f.push(g)}else{let g=new I;g.value=s,f.push(g)}}else{let m=new I;m.value=s,f.push(m)}continue}if(typeof s=="string"){let m=await this.resolveReference(s,r,i);m&&f.push(m)}else if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let m=new S;m.statement=await this.parseStatements(s,r,i,o,c),f.push(m)}}let l=new j;return l.predicate=k.parse(e),l.object=f,l}async resolveReference(e,t,a){let r=await a.resolveEntityAsync(e,t);if(r){let o=new k;return o.subject=r.uri,o}let i=t.metadata?.namespace_;if(i){let{KanonakUri:o}=await import("./KanonakUri-4VJGV3FN.js");if(e.includes(".")){let f=e.indexOf("."),u=e.substring(0,f),d=e.substring(f+1);if(t.metadata?.imports){for(let[l,s]of Object.entries(t.metadata.imports))for(let p of s)if((p.alias??p.packageName)===u){let g=new k;return g.subject=new o(l,p.packageName,d,p.version),g}}}let c=new k;return c.subject=new o(i.publisher,i.package_,e,i.version??void 0),c}return null}async saveKanonaks(e,t){let a=new Map;for(let r of e)r instanceof x&&r.namespace&&(a.has(r.namespace)||a.set(r.namespace,[]),a.get(r.namespace).push(r));for(let[r,i]of a){let o=await this.convertKanonaksToDocument(r,i),c=`${r.split("@")[0]}.yml`;await t.saveDocumentAsync(o,c)}}async serializeToYaml(e,t){let a=e.filter(o=>o instanceof x&&o.namespace===t);if(a.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let r=await this.convertKanonaksToDocument(t,a);return new U().save(r)}async convertKanonaksToDocument(e,t){let r={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let c of Object.values(this.imports))o.push(...c);return o}},body:{}},i=new Map;for(let o of t){let c={};for(let f of o.statement){let[u,d]=this.convertStatementToProperty(f);u&&d!==null&&d!==void 0&&(c[u]=d),this.collectImportsFromStatement(f,e,i)}r.body[o.name]=c}return r}convertStatementToProperty(e){if(e instanceof $)return[e.predicate.subject.name,e.object];if(e instanceof T)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof K)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof j){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let a of e)a instanceof k?t.push(a.subject.name):a instanceof S&&t.push(this.convertEmbeddedKanonakToValue(a));return t}convertEmbeddedKanonakToValue(e){let t={};for(let a of e.statement){let[r,i]=this.convertStatementToProperty(a);r&&i!==null&&i!==void 0&&(t[r]=i)}return t}collectImportsFromStatement(e,t,a){}};function O(n){let e=n.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+Se(n)}function Se(n){return n instanceof R?"m:"+String(n.object):n instanceof $?"s:"+String(n.object):n instanceof T?"n:"+String(n.object):n instanceof E?"b:"+String(n.object):n instanceof K?"r:"+N(n.object):n instanceof w?"e:"+N(n.object):n instanceof j?"l:["+(n.object??[]).map(N).join("|")+"]":"x"}function N(n){if(!n)return"";if(n instanceof k){let e=n.subject;return"R("+(e?`${e.publisher}/${e.package_}/${e.name}`:"")+")"}return n instanceof S?"E("+(n.statement??[]).map(O).join(";")+")":n instanceof I?"L("+String(n.value)+")":"N"}export{S as a,I as b,R as c,Y as d,M as e,Re as f,Te as g,A as h,q as i};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Fn}from"./chunk-4NO7MHS7.js";import{a as Mn}from"./chunk-PEJALHXK.js";import{d as u}from"./chunk-SHDHMKMJ.js";import{a as x,c as xe,i as An}from"./chunk-
|
|
1
|
+
import{a as Fn}from"./chunk-4NO7MHS7.js";import{a as Mn}from"./chunk-PEJALHXK.js";import{d as u}from"./chunk-SHDHMKMJ.js";import{a as x,c as xe,i as An}from"./chunk-7GAOBCNZ.js";import{a as Vn}from"./chunk-EP7CJSV2.js";import{a as pn,b as ue,c as xn,d as w,f as Pe,g as ke,j as gn,k as qe,m as Pn,n as Nn}from"./chunk-PBNVHBS3.js";import{b as Oe,c as G,d as E,g as X,h as me,i as re,j as T,k as H,l as V}from"./chunk-T3JR2SV6.js";import{a as Tn}from"./chunk-FUUTGGJS.js";import{c as en,g as $e}from"./chunk-2ACBWC7K.js";var Ve="kanonak.org",zn="look",We="core-rdf",Kt={publisher:Ve,package_:zn,name:"displayLabel"},Rt={publisher:Ve,package_:zn,name:"displaySummary"},Lt={publisher:Ve,package_:We,name:"type"},Ot={publisher:Ve,package_:We,name:"subClassOf"},Ut={publisher:Ve,package_:We,name:"label"},It={publisher:Ve,package_:We,name:"comment"},Dn=new Tn(Ve,We,"Resource");function D(r,e){let n=Bn(r,e,Kt)??Ut,t=Bn(r,e,Rt)??It,a=gn(e,n)??e.name,s=gn(e,t);return{label:a,summary:s}}function Bn(r,e,n){let t=qe(e,n);if(t)return t;let a=new Set,s=Hn(e,Lt);for(;s.length>0;){let o=s.shift(),i=pn(o);if(a.has(i))continue;a.add(i);let c=Pe(r,o);if(!c)continue;let l=qe(c,n);if(l)return l;s.push(...Hn(c,Ot))}if(!a.has(pn(Dn))){let o=Pe(r,Dn);if(o){let i=qe(o,n);if(i)return i}}}function Hn(r,e){let n=qe(r,e);if(n)return[n];let t=[];for(let a of Pn(r,e))a instanceof E&&t.push(a.subject);return t}function Ye(r,e={}){let n=r.replace(/\r\n/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`),t=[],a=0;for(;a<n.length;){let s=n[a];if(s.trim()===""){a++;continue}let o=/^(\s*)```(\S*)\s*$/.exec(s);if(o){let l=o[2],d=[];for(a++;a<n.length&&!/^(\s*)```\s*$/.test(n[a]);)d.push(n[a]),a++;a++;let f=d.join(`
|
|
4
4
|
`),g=l&&e.highlight?e.highlight(l,f):De(f),m=l?` class="language-${qn(l)}"`:"";t.push(`<pre class="kan-code"><code${m}>${g}</code></pre>`);continue}let i=/^(#{1,6})\s+(.*)$/.exec(s);if(i){let l=i[1].length,d=Ne(i[2].trim());t.push(`<h${l}>${d}</h${l}>`),a++;continue}if(s.includes("|")&&a+1<n.length&&Gn(n[a+1])){let l=mn(s),d=Ct(n[a+1]);a+=2;let f=[];for(;a<n.length&&n[a].trim()!==""&&n[a].includes("|");)f.push(mn(n[a])),a++;t.push(Ft(l,d,f));continue}if(/^\s*[-*]\s+/.test(s)){let l=[];for(;a<n.length&&/^\s*[-*]\s+/.test(n[a]);){let d=[n[a].replace(/^\s*[-*]\s+/,"")];for(a++;a<n.length&&n[a].trim()!==""&&!/^\s*[-*]\s+/.test(n[a])&&!/^\s*\d+\.\s+/.test(n[a]);)d.push(n[a]),a++;a<n.length&&n[a].trim()===""&&a++,l.push(`<li>${Ne(d.join(" ").trim())}</li>`)}t.push(`<ul>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as u,b as l}from"./chunk-2ACBWC7K.js";import*as c from"js-yaml";var g=new Set(["Package","EphemeralPackage"]);function d(m){return typeof m=="string"&&g.has(m)}var h=class{parse(e){let r=this.parseWithErrors(e);if(!r.isValid){let n=r.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return r.document}parseWithErrors(e){let r=[],n;try{e=e.replace(/^\uFEFF/,"");let a=c.load(e,{schema:c.FAILSAFE_SCHEMA});if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:r,isValid:!0};let t=this.extractMetadata(a),s=this.extractBody(a,t);return n={metadata:t,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:r,isValid:!0}}catch(a){let t=a,s={message:t.message||"Unknown parse error",line:t.mark?.line??0,column:t.mark?.column??0,errorType:t.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${t.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${t.mark?.line??0}: ${t.message||"Unknown parse error"}`};return r.push(s),{document:void 0,errors:r,isValid:!1}}}save(e){let r={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),r[n.package_]=a}return Object.assign(r,e.body),c.dump(r,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let r=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!r)return[];let n=[];for(let a of Object.values(r))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,r,n){return{major:e,minor:r,patch:n,toString:()=>`${e}.${r}.${n}`,equals:t=>!t||typeof t!="object"?!1:t.major===e&&t.minor===r&&t.patch===n,getHashCode:()=>e<<20|r<<10|n,compareTo:t=>e!==t.major?e-t.major:r!==t.minor?r-t.minor:n-t.patch}}extractMetadata(e){let r=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&d(a.type)){r.type_=a.type;let t=n,s=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return s&&t&&(r.namespace_={publisher:s,package_:t,version:i,toString:function(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}`:`${this.publisher}/${this.package_}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===s&&o.package_===t&&(!i||!o.version||i.equals(o.version)),getHashCode:()=>{let o=0;for(let p=0;p<s.length;p++)o=(o<<5)-o+s.charCodeAt(p);for(let p=0;p<t.length;p++)o=(o<<5)-o+t.charCodeAt(p);return o|0}}),a.imports&&Array.isArray(a.imports)&&(r.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(r)}return r}extractBody(e,r){let n={};for(let[a,t]of Object.entries(e))if(!(a==="kanonak"||a==="namespace"||a==="imports"))if(t&&typeof t=="object"&&d(t.type)){let s={};for(let[i,o]of Object.entries(t))i==="publisher"||i==="version"||i==="imports"||(s[i]=o);n[a]=s}else n[a]=t;return n}parseVersion(e){if(typeof e=="string"){let r=e.split(".").map(Number);return this.createVersion(r[0]||0,r[1]||0,r[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let r={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");r[a]||(r[a]=[]);for(let t of n.packages){if(!t||typeof t!="object")continue;let s=this.parseImportFromEmbeddedObject(t,a);r[a].push(s)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),t=a.publisher||"";r[t]||(r[t]=[]),r[t].push(a)}return r}parseImportFromEmbeddedObject(e,r){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let t=e.version;if(!t)throw new Error("Import requires 'version' property");return this.makeImport(n,a,t,r,e.alias)}makeImport(e,r,n,a,t){let s=this.parseVersion(n),i=this.parseVersionOperator(r),o=this.calculateMaxVersion(r,s);return{package_:`${e} ${r} ${s.toString()}`,publisher:a,packageName:e,versionOperator:i,version:s,alias:t,minVersion:s,maxVersion:o,toEmbeddedObject:()=>{let p={package:e,match:r,version:s.toString()};return t&&(p.alias=t),p},toString:()=>t?`${e} ${r} ${s.toString()} as ${t}`:`${e} ${r} ${s.toString()}`}}buildImport(e,r,n,a){return this.makeImport(e,r,n,a)}parseVersionOperator(e){return u(e)}calculateMaxVersion(e,r){switch(e){case"~":return this.createVersion(r.major,r.minor+1,0);case"^":return r.major===0?this.createVersion(0,r.minor+1,0):this.createVersion(r.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let r=[];for(let[n,a]of Object.entries(e)){let t={publisher:n,packages:a.map(s=>{let i=l(s.versionOperator),o={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(o.alias=s.alias),o})};r.push(t)}return r}};export{h as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as v}from"./chunk-YCV4H6H5.js";import{a as A}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-ZYAABYDS.js";import{c as w,d as I,h as R,i as F}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return I(r,t.version);case P.Compatible:return R(r,t.version);case P.Major:return F(r,t.version);case P.Any:return w(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return w(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],p=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,p)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=b(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return b(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as d from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(t)||d.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as N}from"path";function g(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||N(_(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??g(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=g(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{readFileSync as B,readdirSync as H}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function K(u,e=[]){for(let t of H(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||K(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new A(e);for(let m of K(u))try{let l=e.parse(B(m,"utf-8")),h=l.metadata?.namespace_,p=h?.version;h&&p&&await n.saveDocumentAsync(l,`${h.publisher}/${h.package_}@${p.major}.${p.minor}.${p.patch}`)}catch{}let o=new y(g(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,h)=>s.get(`${m}|${l}|${h}`)??null,onFetch:(m,l,h,p)=>{s.set(`${m}|${l}|${h}`,p)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,S as b,k as c,g as d,C as e,D as f,K as g,j as h};
|
|
1
|
+
import{d as v}from"./chunk-NNUV6K3C.js";import{a as A}from"./chunk-4NO7MHS7.js";import{a as f}from"./chunk-EP7CJSV2.js";import{c as w,d as I,h as R,i as F}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return I(r,t.version);case P.Compatible:return R(r,t.version);case P.Major:return F(r,t.version);case P.Any:return w(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return w(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],p=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,p)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=b(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return b(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as d from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(t)||d.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as N}from"path";function g(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||N(_(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??g(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=g(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{readFileSync as B,readdirSync as H}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function K(u,e=[]){for(let t of H(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||K(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new A(e);for(let m of K(u))try{let l=e.parse(B(m,"utf-8")),h=l.metadata?.namespace_,p=h?.version;h&&p&&await n.saveDocumentAsync(l,`${h.publisher}/${h.package_}@${p.major}.${p.minor}.${p.patch}`)}catch{}let o=new y(g(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,h)=>s.get(`${m}|${l}|${h}`)??null,onFetch:(m,l,h,p)=>{s.set(`${m}|${l}|${h}`,p)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,S as b,k as c,g as d,C as e,D as f,K as g,j as h};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{J as W,K as X}from"./chunk-
|
|
1
|
+
import{J as W,K as X}from"./chunk-KARUKDEM.js";import{b as B,c as V,i as w}from"./chunk-7GAOBCNZ.js";import{a as b,d as K,e as q,f as z}from"./chunk-UK2OIPAB.js";import{a as D,f as E,h as F,j as N,k as Y,m as v}from"./chunk-PBNVHBS3.js";import{c as G,d as x}from"./chunk-T3JR2SV6.js";import{a as L}from"./chunk-FUUTGGJS.js";import{d as U}from"./chunk-2ACBWC7K.js";var Q=(t=>(t.Class="Class",t.DatatypeProperty="DatatypeProperty",t.ObjectProperty="ObjectProperty",t.AnnotationProperty="AnnotationProperty",t.Instance="Instance",t.Datatype="Datatype",t.Unknown="Unknown",t))(Q||{}),Z=(p=>(p.InstanceOf="instanceOf",p.SubClassOf="subClassOf",p.Domain="domain",p.Range="range",p.ObjectRelationship="objectRelationship",p.SubPropertyOf="subPropertyOf",p.PropertyValue="propertyValue",p.EmbeddedLink="embeddedLink",p))(Z||{}),I=class{static async buildFromRepository(e){let a=await new w().parseKanonaks(e),o=await e.getAllDocumentsAsync(),s=[],i=[],t=new Set,p=new Set,g=new Map;for(let u of a){let l=u;l.name&&(b.isClassType(l)&&t.add(l.name),(b.isObjectPropertyType(l)||b.isGenericPropertyType(l))&&p.add(l.name))}for(let u of o)for(let[l,f]of Object.entries(u.body))p.has(l)&&f?.range&&typeof f.range=="string"&&g.set(l,f.range);let y=new Map;for(let u of a){let l=u;l.name&&y.set(l.name,l)}for(let u of o){let l=u.metadata.namespace_,f=l?`${l.publisher}/${l.package_}`:"",c=l?.version?`${l.version.major}.${l.version.minor}.${l.version.patch}`:"",d=H(u);for(let[k,m]of Object.entries(u.body)){if(!m||typeof m!="object")continue;let P=y.get(k),h="Unknown";if(P){let T=P;b.isClassType(T)?h="Class":b.isObjectPropertyType(T)?h="ObjectProperty":b.isDatatypePropertyType(T)?h="DatatypeProperty":b.isAnnotationPropertyType(T)?h="AnnotationProperty":b.isDatatypeType(T)?h="Datatype":b.isGenericPropertyType(T)?h="ObjectProperty":b.isInstanceOfKnownClass(T,t)&&(h="Instance")}let j=f&&c?`${f}/${k}@${c}`:k,A={};for(let[T,$]of Object.entries(m))T!=="type"&&(typeof $!="object"||$===null)&&(A[T]=$);s.push({id:j,label:m.label??k,type:h,namespace:f,properties:A}),J(j,m,h,t,p,i,f,c,d),_(j,m,p,g,s,i,f,c,d),ue(j,P,i)}}return{nodes:s,edges:i}}static buildFromDocument(e){let r=[],a=[],o=e.metadata.namespace_,s=o?.version?`${o.version.major}.${o.version.minor}.${o.version.patch}`:"",i=o?`${o.publisher}/${o.package_}`:"",t=new Set,p=new Set,g=new Map,y=H(e);for(let[f,c]of Object.entries(e.body)){let d=c?.type;d&&(pe(d,y)&&t.add(f),ce(d,y)&&(p.add(f),c.range&&typeof c.range=="string"&&g.set(f,c.range)))}for(let[f,c]of Object.entries(e.body)){if(!c||typeof c!="object")continue;let d=c.type,k=le(d,f,t,y),m=i&&s?`${i}/${f}@${s}`:f,P={};for(let[h,j]of Object.entries(c))h!=="type"&&(typeof j!="object"||j===null)&&(P[h]=j);r.push({id:m,label:c.label??f,type:k,namespace:i,properties:P}),J(m,c,k,t,p,a,i,s,y),_(m,c,p,g,r,a,i,s,y)}let u=new Set(r.map(f=>f.id)),l=a.filter(f=>u.has(f.source)&&u.has(f.target));return{nodes:r,edges:l}}};function H(n,e){let r=new Map;if(n.metadata?.imports)for(let[a,o]of Object.entries(n.metadata.imports))for(let s of o){let i=s.alias??s.packageName,t=s.version,p=`${t.major}.${t.minor}.${t.patch}`;r.set(i,{publisher:a,package_:s.packageName,version:p})}return r}var ee={"kanonak.org/core-rdf/Class":"Class","kanonak.org/core-owl/Class":"Class","kanonak.org/core-rdfs/Class":"Class","kanonak.org/core-owl/ObjectProperty":"ObjectProperty","kanonak.org/core-owl/DatatypeProperty":"DatatypeProperty","kanonak.org/core-owl/AnnotationProperty":"AnnotationProperty","kanonak.org/core-rdf/Property":"ObjectProperty","kanonak.org/core-rdfs/Datatype":"Datatype"},ie=new Set(["kanonak.org/core-owl/ObjectProperty","kanonak.org/core-owl/DatatypeProperty","kanonak.org/core-owl/AnnotationProperty","kanonak.org/core-rdf/Property"]);function M(n,e){if(n.includes(".")){let r=n.indexOf("."),a=n.substring(0,r),o=n.substring(r+1),s=e.get(a);if(s)return`${s.publisher}/${s.package_}/${o}`}return null}function pe(n,e){let r=M(n,e);return r?ee[r]==="Class":!1}function ce(n,e){let r=M(n,e);return r?ie.has(r):!1}function le(n,e,r,a){if(!n||n==="Package")return"Unknown";let o=M(n,a);if(o){let i=ee[o];if(i)return i;let t=o.split("/").pop()?.split("@")[0]??"";return r.has(t)?"Instance":"Unknown"}let s=n.split(".").pop()??n;return r.has(s)?"Instance":"Unknown"}var ne=new Set(["type","label","comment","version","publisher","imports","license","match","alias","package"]);function J(n,e,r,a,o,s,i,t,p){let g=e.type,y=e.subClassOf;if(y){let c=Array.isArray(y)?y:[y];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subClassOf",label:"subClassOf"})}let u=e.subPropertyOf;if(u){let c=Array.isArray(u)?u:[u];for(let d of c)typeof d=="string"&&s.push({source:n,target:O(d,i,t,p),type:"subPropertyOf",label:"subPropertyOf"})}if(r==="Instance"&&g){let c=g.split(".").pop()??g;s.push({source:n,target:O(c,i,t,p),type:"instanceOf",label:"type"})}if(r==="Instance")for(let[c,d]of Object.entries(e)){if(ne.has(c)||!o.has(c))continue;let k=Array.isArray(d)?d:[d];for(let m of k)typeof m=="string"&&fe(m)&&s.push({source:n,target:O(m,i,t,p),type:"propertyValue",label:c,propertyId:O(c,i,t,p)})}let l=r==="ObjectProperty"||r==="DatatypeProperty",f=e.domain&&e.range;if((l||f)&&e.domain&&e.range){let c=typeof e.domain=="string"?e.domain:null,d=typeof e.range=="string"?e.range:null;c&&d&&s.push({source:O(c,i,t,p),target:O(d,i,t,p),type:"objectRelationship",label:e.label??n.split("/").pop()??"",propertyId:n})}}function _(n,e,r,a,o,s,i,t,p){for(let[g,y]of Object.entries(e)){if(ne.has(g)||typeof y!="object"||y===null||Array.isArray(y))continue;let u=y,l=`${n}/${g}`,f=a.get(g),c=f?f.split(".").pop()??f:"Unknown",d={};for(let[m,P]of Object.entries(u))(typeof P!="object"||P===null)&&(d[m]=P);o.push({id:l,label:`${c} (embedded)`,type:"Instance",namespace:i,properties:d});let k=i&&t?`${i}/${g}@${t}`:g;s.push({source:n,target:l,type:"propertyValue",label:g,propertyId:r.has(g)?k:void 0}),f&&s.push({source:l,target:O(c,i,t,p),type:"instanceOf",label:"type (inferred)"}),_(l,u,r,a,o,s,i,t,p)}}function ue(n,e,r){let a=e?.statement;if(Array.isArray(a))for(let o of a){if(!(o instanceof V))continue;let s=o.predicate?.subject?.name??"";for(let i of o.links){let t=i.target?.subject;if(!t)continue;let p=t.version,g=p&&typeof p.major=="number"?`@${p.major}.${p.minor}.${p.patch}`:"";r.push({source:n,target:`${t.publisher}/${t.package_}/${t.name}${g}`,type:"embeddedLink",label:s})}}}function fe(n){return!(!n||n.includes(" ")||n.includes(`
|
|
2
2
|
`)||n.startsWith("http://")||n.startsWith("https://")||/^\d{4}-\d{2}/.test(n)||/^\d+(\.\d+)?$/.test(n))}function O(n,e,r,a){if(n.includes("@")&&n.includes("/"))return n;if(n.includes(".")){let o=n.indexOf("."),s=n.substring(0,o),i=n.substring(o+1);if(a){let t=a.get(s);if(t)return`${t.publisher}/${t.package_}/${i}@${t.version}`}return e&&r?`${e}/${i}@${r}`:i}return e&&r?`${e}/${n}@${r}`:n}function de(n){if(!n.expiresAt)return!1;let e=new Date(n.expiresAt),r=300*1e3;return e.getTime()<=Date.now()+r}function Re(n){return!!n.accessToken&&!de(n)}function Se(n){let e=n.replace(/^https?:\/\//,"").replace(/^git:\/\//,"").replace(/\/+$/,"").trim();if(!e)throw new Error("Publisher host cannot be empty");return e}var C="kanonak.org",S="core-rdf",re="core-xsd",te={publisher:C,package_:S,name:"subClassOf"},oe={publisher:C,package_:S,name:"label"},ye={publisher:C,package_:S,name:"comment"},se={publisher:C,package_:"core-owl",name:"oneOf"},ae=n=>n;function ge(n){let e=Y(n,te);if(e)return[e];let r=[];for(let a of v(n,te))a instanceof x&&r.push(a.subject);return r}function me(n,e,r){if(e.publisher===C&&e.package_===S&&e.name==="Literal")return{kind:"datatype",uri:e};let o=E(n,e);if(o){let s=ae(o);if(b.isDatatypeType(s))return{kind:"datatype",uri:e};if(b.isClassType(s))return{kind:"class",uri:K(o)??e,localName:o.name}}return e.publisher===C&&e.package_===re?{kind:"datatype",uri:e}:r==="datatype"?{kind:"datatype",uri:e}:{kind:"class",uri:e,localName:e.name}}function be(n,e,r){if(!e.range)throw new Error(`Property ${e.uri.publisher}/${e.uri.package_}/${e.uri.name} has no rdfs.range; every property must declare a range. Validate the ontology before introspecting it.`);let a=me(n,e.range,e.kind),o=e.kind==="object"?"object":e.kind==="datatype"?"datatype":a.kind==="class"?"object":"datatype";return{uri:e.uri,localName:e.uri.name,kind:o,range:a,...e.label!==void 0?{label:e.label}:{},...e.comment!==void 0?{comment:e.comment}:{},...r??{}}}var R=n=>new L(C,re,n);function ke(n){return typeof n=="boolean"?R("boolean"):typeof n=="number"?Number.isInteger(n)?R("integer"):R("decimal"):R("string")}function he(n,e){let r=[];for(let a of v(e,se))if(a instanceof x){let o=E(n,a.subject),s=(o?K(o):void 0)??a.subject,i=o?N(o,oe):void 0;r.push({kind:"individual",uri:s,localName:s.name,...i!==void 0?{label:i}:{}})}else a instanceof B&&r.push({kind:"literal",value:a.value,datatype:ke(a.value)});return r}function Pe(n,e,r,a){let o=q(n,e),s=D(e);return z(n,e).filter(t=>r?!0:t.domains.some(p=>D(p)===s)).map(t=>be(n,t,X(a,o,t.uri)))}async function Te(n,e,r){let a=n.metadata?.namespace_;if(!a)throw new Error("buildOntologyModel: document has no namespace (publisher/package/version).");let o=r?.includeInherited??!1,s=await new w().parseKanonaks(e),i=W(s),t=[],p=[],g=new Set;for(let y of s){if(!(y instanceof G)||!b.isClassType(ae(y)))continue;let u=K(y);if(!u||u.publisher!==a.publisher||u.package_!==a.package_||u.version&&a.version&&!U(u.version,a.version))continue;let l=D(u);if(g.has(l))continue;g.add(l);let f=ge(y).map(k=>({uri:k,localName:k.name})),c=N(y,oe),d=N(y,ye);t.push({uri:u,localName:u.name,superClasses:f,properties:Pe(s,u,o,i),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}}),F(y,se)&&p.push({uri:u,localName:u.name,members:he(s,y),...c!==void 0?{label:c}:{},...d!==void 0?{comment:d}:{}})}return{classes:t,enums:p}}export{Q as a,Z as b,I as c,de as d,Re as e,Se as f,Te as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as D}from"./chunk-
|
|
1
|
+
import{a as D}from"./chunk-7GAOBCNZ.js";import{c as j,d as m,g as R,j as p,k as K,l as k}from"./chunk-T3JR2SV6.js";import{c as b,g as u}from"./chunk-2ACBWC7K.js";function F(a,e,n,t){let i=g(a);if(i.length>0){let s=v(i,e,n);return s?{transformation:s.transformation,source:"instance"}:void 0}let r=new Set,o=O(a);for(;o.length>0;){let s=o.shift(),f=_(s.subject);if(r.has(f))continue;r.add(f);let l=S(t,s.subject);if(l.length===0)continue;let U=l.flatMap(g),h=v(U,e,n);if(h)return{transformation:h.transformation,source:{publisher:s.subject.publisher,package_:s.subject.package_,name:s.subject.name}};for(let T of l)for(let P of $(T))o.push(P)}let c={publisher:"kanonak.org",package_:"core-rdf",name:"Resource"};if(!r.has(_(c))){let s=S(t,c).flatMap(g),f=v(s,e,n);if(f)return{transformation:f.transformation,source:c}}}function g(a){let e=[];for(let n of a.statement)if(n instanceof k&&d(n,"kanonak.org","derivation","derivations"))for(let t of n.object??[]){if(!(t instanceof D))continue;let i=x(t);i&&e.push(i)}return e}function v(a,e,n){let t=a.filter(o=>E(o.format,e)&&E(o.variant,n));if(t.length<=1)return t[0];let i=t[0].transformation,r=t[0];for(let o of t){let c=o.transformation;if(c.publisher!==i.publisher||c.package_!==i.package_||c.name!==i.name)continue;let s=u(r.transformation.version),f=u(c.version);s&&f&&b(f,s)>0&&(r=o)}return r}function x(a){let e,n,t;for(let i of a.statement)i instanceof p?d(i,"kanonak.org","derivation","format")?e=y(i):d(i,"kanonak.org","derivation","variant")&&(n=y(i)):i instanceof K&&d(i,"kanonak.org","derivation","transformation")&&(t=C(i.object));if(!(!e||!t))return n||(n={publisher:"kanonak.org",package_:"derivation",name:"default"}),{format:e,variant:n,transformation:t}}function C(a){let e,n,t,i;for(let r of a.statement){if(!(r instanceof R))continue;let o=r.predicate?.subject?.name;o==="publisher"?e=r.object:o==="package"?n=r.object:o==="version"?t=r.object:o==="name"&&(i=r.object)}if(!(!e||!n||!t||!i))return{publisher:e,package_:n,version:t,name:i}}function O(a){let e=[];for(let n of a.statement)n instanceof p&&n.predicate?.subject?.name==="type"&&n.object instanceof m&&e.push(n.object);return e}function $(a){let e=[];for(let n of a.statement)if(n instanceof p){if(n.predicate?.subject?.name!=="subClassOf")continue;n.object instanceof m&&e.push(n.object)}else if(n instanceof k){if(n.predicate?.subject?.name!=="subClassOf")continue;for(let t of n.object??[])t instanceof m&&e.push(t)}return e}function S(a,e){let n=[];for(let t of a){if(!(t instanceof j)||t.name!==e.name)continue;(t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`)&&n.push(t)}return n.sort((t,i)=>{let r=u((t.namespace||"").split("@")[1]??""),o=u((i.namespace||"").split("@")[1]??"");return!r||!o?0:b(o,r)}),n}function d(a,e,n,t){let i=a.predicate?.subject;return i?i.publisher===e&&i.package_===n&&i.name===t:!1}function y(a){let e=a.object.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}function E(a,e){return a.publisher===e.publisher&&a.package_===e.package_&&a.name===e.name}function _(a){return`${a.publisher}/${a.package_}/${a.name}`}export{F as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as _}from"./chunk-SHDHMKMJ.js";import{a as D,b as Ne,c as Ye,g as Ze,i as A}from"./chunk-FSHQVKZ5.js";import{a as Fe}from"./chunk-ZYAABYDS.js";import{a as B,d as W,e as Je,f as Qe,g as T,h as et}from"./chunk-UK2OIPAB.js";import{a as C,d as E,f as x,h as Te,i as w,j as L,k as V,l as O,m as S,n as M}from"./chunk-PBNVHBS3.js";import{a as N,b as U,c as Ge}from"./chunk-VKTFLHCW.js";import{c as I,d as H,k as qe,l as ze}from"./chunk-T3JR2SV6.js";import{a as Xe}from"./chunk-FUUTGGJS.js";import{e as P}from"./chunk-2ACBWC7K.js";var q=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(n=>(n.Warning="Warning",n.Error="Error",n))(b||{});var g=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 Ue=class y{resolvedDocuments=[];currentEntityPath;withPath(e){let n=new y;return n.resolvedDocuments=this.resolvedDocuments,n.currentEntityPath=e,n}};var Se=class{constructor(e){this.underlying=e;this.repository=new Me(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new A().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let n=this.importClosureCache.get(e);return n||(n=this.computeImportClosure(e),this.importClosureCache.set(e,n),n)}async getClassDeclarations(e){let n=this.classDeclarationsCache.get(e);return n||(n=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,n),n)}async getPropertyNames(e){let n=this.propertyNamesCache.get(e);return n||(n=this.computePropertyNames(e),this.propertyNamesCache.set(e,n),n)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let n=new Set([e]),t=[e],o=await this.buildDocsByIdIndex();for(;t.length>0;){let a=t.shift(),r=o.get(a);if(r?.metadata.imports)for(let[i,s]of Object.entries(r.metadata.imports))for(let c of s){let p=await this.repository.getHighestCompatibleVersionAsync(i,c);if(!p)continue;let l=Le(p);!l||n.has(l)||(n.add(l),t.push(l))}}return n}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),n=new Map;for(let t of e){let o=Le(t);o&&n.set(o,t)}return n}async computeClassDeclarations(e){let n=await this.findDocById(e),t=new Map;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let r=a,i=nt(r,"type");if(i==="Class"||i?.endsWith(".Class")){let s=dt(r);t.set(o,s)}}return t}async computePropertyNames(e){let n=await this.findDocById(e),t=new Set;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let i=nt(a,"type");(i==="ObjectProperty"||i?.endsWith(".ObjectProperty")||i==="DatatypeProperty"||i?.endsWith(".DatatypeProperty")||i==="AnnotationProperty"||i?.endsWith(".AnnotationProperty")||i==="Property"||i?.endsWith(".Property"))&&t.add(o)}return t}async findDocById(e){let n=await this.getAllDocuments();for(let t of n)if(Le(t)===e)return t}};function Le(y){let e=y.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${P(e.version)}`}function tt(y){return typeof y=="object"&&y!==null&&!Array.isArray(y)}function nt(y,e){if(e in y)return ot(y[e]);for(let n of Object.keys(y))if(n.endsWith(`.${e}`))return ot(y[n])}function ot(y){return Array.isArray(y)?y.length>0?String(y[0]):void 0:y==null?void 0:String(y)}function dt(y){let e=y.subClassOf;if(e===void 0){for(let n of Object.keys(y))if(n.endsWith(".subClassOf")){e=y[n];break}}return N(e)}var Me=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,n){let t=`${e}/${n}`,o=this.byNamespaceCache.get(t);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,n),this.byNamespaceCache.set(t,o),o)}getHighestCompatibleVersionAsync(e,n){let t=n.version,o=t?`${t.major}.${t.minor}.${t.patch}`:"",a=`${e}/${n.packageName}@${n.versionOperator}:${o}`,r=this.highestVersionCache.get(a);return r||(r=this.inner.getHighestCompatibleVersionAsync(e,n),this.highestVersionCache.set(a,r),r)}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)}};var z=class y{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 n=[];for(let[t,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(t,o,n);return n}validateEntity(e,n,t){for(let[o,a]of Object.entries(n)){let r=a?.toString()??"";if(r&&y.NAMESPACE_PREFIX_PATTERN.test(r)){let i=this.getSuggestionForPrefixedValue(r),s=e.split(".")[0],c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=s,c.propertyName=e,c.actualValue=o,c.expectedValue=i,c.message=`Invalid namespace prefix '${r}'. Use '${i}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,t)}}getSuggestionForPrefixedValue(e){let n=e.toLowerCase();if(n==="rdfs:class"||n==="owl:class")return"Class";if(n==="rdfs:property"||n==="rdf:property")return"DatatypeProperty or ObjectProperty";if(n.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var Y=class y{static RESERVED_WORDS=new Set(["kanonak","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 n=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let r=y.VALID_AUGMENTATION_PATTERN.test(o);if(!r&&!t&&y.RESERVED_WORDS.has(o.toLowerCase())){let i=new g;i.ruleType=this.ruleName,i.severity="Error",i.entityName=o,i.message=`Entity name '${o}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",n.push(i);continue}if(!r&&!y.VALID_NAME_PATTERN.test(o)){let i;/^\d/.test(o)?i="Entity names must start with a letter, not a number.":o.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 g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.message=`Invalid entity name '${o}'. ${i}`,s.suggestion=i,n.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,n)}return n}validatePropertyNames(e,n,t){for(let o of Object.keys(n))if(!y.VALID_PROPERTIES.has(o)&&!y.VALID_PROPERTY_NAME_PATTERN.test(o)){let a=new g;a.ruleType=this.ruleName,a.severity="Warning",a.entityName=e,a.propertyName=o,a.message=`Property name '${o}' in entity '${e}' doesn't follow naming conventions.`,a.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(a)}}};var G=class y{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 n=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return n;let t=this.isPropertyDefinedAsClass(e);for(let[o,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let r=a,i=r.type;if(i){let s=[];if(Array.isArray(i))for(let c of i){let p=c?.toString();p&&p==="Property"&&!t&&s.push(p)}else{let c=i?.toString();c&&c==="Property"&&!t&&s.push(c)}for(let c of s){let p=this.getPropertyValue(r,"range"),l=this.determinePropertyType(p),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=o,m.propertyName="type",m.actualValue=c,m.expectedValue=l,m.message=`Invalid property type '${c}'. Use '${l}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",n.push(m)}}}return n}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":y.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,n){let t=e[n];return t?t.toString():null}isPropertyDefinedAsClass(e){let n=e.body.Property;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=n.type;if(o){let a=o.toString();return a==="Class"||a.endsWith(".Class")}}return!1}};var Z=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let n=[];for(let[t,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||t.includes("."))continue;let a=o,r="type"in a,i=a.type?.toString().trim();if(!r||!i){let s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=t,s.propertyName="type",s.message=`Subject Kanonak '${t}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
|
|
1
|
+
import{d as _}from"./chunk-SHDHMKMJ.js";import{a as D,b as Ne,c as Ye,g as Ze,i as A}from"./chunk-7GAOBCNZ.js";import{a as Fe}from"./chunk-EP7CJSV2.js";import{a as B,d as W,e as Je,f as Qe,g as T,h as et}from"./chunk-UK2OIPAB.js";import{a as C,d as E,f as x,h as Te,i as w,j as L,k as V,l as O,m as S,n as M}from"./chunk-PBNVHBS3.js";import{a as N,b as U,c as Ge}from"./chunk-VKTFLHCW.js";import{c as I,d as H,k as qe,l as ze}from"./chunk-T3JR2SV6.js";import{a as Xe}from"./chunk-FUUTGGJS.js";import{e as P}from"./chunk-2ACBWC7K.js";var q=class{isValid=!1;errors=[];warnings=[];get totalIssues(){return this.errors.length+this.warnings.length}};var b=(n=>(n.Warning="Warning",n.Error="Error",n))(b||{});var g=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 Ue=class y{resolvedDocuments=[];currentEntityPath;withPath(e){let n=new y;return n.resolvedDocuments=this.resolvedDocuments,n.currentEntityPath=e,n}};var Se=class{constructor(e){this.underlying=e;this.repository=new Me(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new A().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let n=this.importClosureCache.get(e);return n||(n=this.computeImportClosure(e),this.importClosureCache.set(e,n),n)}async getClassDeclarations(e){let n=this.classDeclarationsCache.get(e);return n||(n=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,n),n)}async getPropertyNames(e){let n=this.propertyNamesCache.get(e);return n||(n=this.computePropertyNames(e),this.propertyNamesCache.set(e,n),n)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let n=new Set([e]),t=[e],o=await this.buildDocsByIdIndex();for(;t.length>0;){let a=t.shift(),r=o.get(a);if(r?.metadata.imports)for(let[i,s]of Object.entries(r.metadata.imports))for(let c of s){let p=await this.repository.getHighestCompatibleVersionAsync(i,c);if(!p)continue;let l=Le(p);!l||n.has(l)||(n.add(l),t.push(l))}}return n}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),n=new Map;for(let t of e){let o=Le(t);o&&n.set(o,t)}return n}async computeClassDeclarations(e){let n=await this.findDocById(e),t=new Map;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let r=a,i=nt(r,"type");if(i==="Class"||i?.endsWith(".Class")){let s=dt(r);t.set(o,s)}}return t}async computePropertyNames(e){let n=await this.findDocById(e),t=new Set;if(!n)return t;for(let[o,a]of Object.entries(n.body)){if(!tt(a))continue;let i=nt(a,"type");(i==="ObjectProperty"||i?.endsWith(".ObjectProperty")||i==="DatatypeProperty"||i?.endsWith(".DatatypeProperty")||i==="AnnotationProperty"||i?.endsWith(".AnnotationProperty")||i==="Property"||i?.endsWith(".Property"))&&t.add(o)}return t}async findDocById(e){let n=await this.getAllDocuments();for(let t of n)if(Le(t)===e)return t}};function Le(y){let e=y.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${P(e.version)}`}function tt(y){return typeof y=="object"&&y!==null&&!Array.isArray(y)}function nt(y,e){if(e in y)return ot(y[e]);for(let n of Object.keys(y))if(n.endsWith(`.${e}`))return ot(y[n])}function ot(y){return Array.isArray(y)?y.length>0?String(y[0]):void 0:y==null?void 0:String(y)}function dt(y){let e=y.subClassOf;if(e===void 0){for(let n of Object.keys(y))if(n.endsWith(".subClassOf")){e=y[n];break}}return N(e)}var Me=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,n){let t=`${e}/${n}`,o=this.byNamespaceCache.get(t);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,n),this.byNamespaceCache.set(t,o),o)}getHighestCompatibleVersionAsync(e,n){let t=n.version,o=t?`${t.major}.${t.minor}.${t.patch}`:"",a=`${e}/${n.packageName}@${n.versionOperator}:${o}`,r=this.highestVersionCache.get(a);return r||(r=this.inner.getHighestCompatibleVersionAsync(e,n),this.highestVersionCache.set(a,r),r)}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)}};var z=class y{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 n=[];for(let[t,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(t,o,n);return n}validateEntity(e,n,t){for(let[o,a]of Object.entries(n)){let r=a?.toString()??"";if(r&&y.NAMESPACE_PREFIX_PATTERN.test(r)){let i=this.getSuggestionForPrefixedValue(r),s=e.split(".")[0],c=new g;c.ruleType=this.ruleName,c.severity="Error",c.entityName=s,c.propertyName=e,c.actualValue=o,c.expectedValue=i,c.message=`Invalid namespace prefix '${r}'. Use '${i}' without prefix.`,c.suggestion="Kanonak YAML uses simple type names. Namespace resolution is handled through imports.",t.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,t)}}getSuggestionForPrefixedValue(e){let n=e.toLowerCase();if(n==="rdfs:class"||n==="owl:class")return"Class";if(n==="rdfs:property"||n==="rdf:property")return"DatatypeProperty or ObjectProperty";if(n.startsWith("xsd:"))return e.substring(4);let t=e.indexOf(":");return t>=0?e.substring(t+1):e}};var Y=class y{static RESERVED_WORDS=new Set(["kanonak","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 n=[],t=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let r=y.VALID_AUGMENTATION_PATTERN.test(o);if(!r&&!t&&y.RESERVED_WORDS.has(o.toLowerCase())){let i=new g;i.ruleType=this.ruleName,i.severity="Error",i.entityName=o,i.message=`Entity name '${o}' is a reserved word and cannot be used.`,i.suggestion="Choose a different name that doesn't conflict with Kanonak reserved words.",n.push(i);continue}if(!r&&!y.VALID_NAME_PATTERN.test(o)){let i;/^\d/.test(o)?i="Entity names must start with a letter, not a number.":o.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 g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=o,s.message=`Invalid entity name '${o}'. ${i}`,s.suggestion=i,n.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,n)}return n}validatePropertyNames(e,n,t){for(let o of Object.keys(n))if(!y.VALID_PROPERTIES.has(o)&&!y.VALID_PROPERTY_NAME_PATTERN.test(o)){let a=new g;a.ruleType=this.ruleName,a.severity="Warning",a.entityName=e,a.propertyName=o,a.message=`Property name '${o}' in entity '${e}' doesn't follow naming conventions.`,a.suggestion="Property names should start with a letter and contain only letters, numbers, and underscores.",t.push(a)}}};var G=class y{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 n=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return n;let t=this.isPropertyDefinedAsClass(e);for(let[o,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let r=a,i=r.type;if(i){let s=[];if(Array.isArray(i))for(let c of i){let p=c?.toString();p&&p==="Property"&&!t&&s.push(p)}else{let c=i?.toString();c&&c==="Property"&&!t&&s.push(c)}for(let c of s){let p=this.getPropertyValue(r,"range"),l=this.determinePropertyType(p),m=new g;m.ruleType=this.ruleName,m.severity="Error",m.entityName=o,m.propertyName="type",m.actualValue=c,m.expectedValue=l,m.message=`Invalid property type '${c}'. Use '${l}' instead.`,m.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",n.push(m)}}}return n}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":y.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,n){let t=e[n];return t?t.toString():null}isPropertyDefinedAsClass(e){let n=e.body.Property;if(n&&typeof n=="object"&&!Array.isArray(n)){let o=n.type;if(o){let a=o.toString();return a==="Class"||a.endsWith(".Class")}}return!1}};var Z=class{get ruleName(){return"SubjectKanonakTypeRequired"}validate(e){let n=[];for(let[t,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||t.includes("."))continue;let a=o,r="type"in a,i=a.type?.toString().trim();if(!r||!i){let s=new g;s.ruleType=this.ruleName,s.severity="Error",s.entityName=t,s.propertyName="type",s.message=`Subject Kanonak '${t}' 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.)",n.push(s)}}return n}};var gt=new Set(["EphemeralPackage"]),J=class{get ruleName(){return"PackageHeader"}validate(e){let n=e.metadata;if(!n.type_)return[];let t=[],o=this.packageKey(e,n.type_);return n.namespace_?(!gt.has(n.type_)&&!n.namespace_.version&&t.push(this.error(o,"version",`Package resource '${o}' requires a 'version' property \u2014 packages are addressed by name@version.`,`Add a version, e.g.:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as u}from"./chunk-SC5M74NM.js";import{a as y}from"./chunk-
|
|
1
|
+
import{a as u}from"./chunk-SC5M74NM.js";import{a as y}from"./chunk-EP7CJSV2.js";import{e as v}from"./chunk-2ACBWC7K.js";var x="https://{publisher}/index.txt",P="https://{publisher}/{package}/{version}.kan.yml",k={version:1};function A(c){return{version:1,index:x.replaceAll("{publisher}",c),package:P.replaceAll("{publisher}",c),auth:"none"}}var f=class{cache=new Map;getConfig(t){let n=this.cache.get(t);return n||(n=this.fetchConfig(t),this.cache.set(t,n),n.catch(()=>{this.cache.get(t)===n&&this.cache.delete(t)})),n}async fetchConfig(t){let n=`https://${t}/.well-known/kanonak.json`,r;try{r=await fetch(n)}catch{return k}if(r.status===404)return k;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${n} (${r.status} ${r.statusText})`);let e=await r.json();if(typeof e.version!="number")throw new Error(`Invalid publisher config at ${n}: missing or invalid "version" field`);let s={version:e.version};return typeof e.index=="string"&&(s.index=e.index),typeof e.package=="string"&&(s.package=e.package),(e.auth==="none"||e.auth==="oauth"||e.auth==="bearer")&&(s.auth=e.auth),Array.isArray(e.render)&&e.render.every(i=>typeof i=="string")&&(s.render=e.render),typeof e.resolveByRedirect=="boolean"&&(s.resolveByRedirect=e.resolveByRedirect),s}resolveIndexUrl(t,n){let r=n.index??x;return w(r,{publisher:t})}resolvePackageUrl(t,n,r,e){let s=e.package??P;return w(s,{publisher:t,package:n,version:r})}};function w(c,t){let n=c;for(let[e,s]of Object.entries(t))n=n.replaceAll(`{${e}}`,s);let r=n.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${c}`);return n}import{VersionOperator as m}from"@kanonak-protocol/types/document/models/enums";var l=class c{indexCache=new Map;configResolver;fetchFn;constructor(t){this.configResolver=t?.configResolver??new f,this.fetchFn=t?.fetchFn}async resolveVersion(t,n){let r=await this.getPackageVersions(t,n.packageName);if(r.length===0)return null;let e=r.filter(s=>this.isVersionCompatible(s,n.version,n.versionOperator));return e.length===0?null:(e.sort((s,i)=>this.compareVersionStrings(i,s)),e[0])}async getHighestVersion(t,n){let r=await this.getPackageVersions(t,n);return r.length===0?null:[...r].sort((s,i)=>this.compareVersionStrings(i,s))[0]}async listLatestPackages(t){let n=await this.getIndex(t),r=[];for(let[e,s]of n){if(s.length===0)continue;let i=[...s].sort((o,a)=>this.compareVersionStrings(a,o));r.push({packageName:e,version:i[0]})}return r.sort((e,s)=>e.packageName.localeCompare(s.packageName)),r}async getPackageUrl(t,n,r){let e=await this.configResolver.getConfig(t);return this.configResolver.resolvePackageUrl(t,n,r,e)}getConfig(t){return this.configResolver.getConfig(t)}async getPackageVersions(t,n){return(await this.getIndex(t)).get(n)??[]}getIndex(t){let n=this.indexCache.get(t);return n||(n=this.fetchIndex(t),this.indexCache.set(t,n),n.catch(()=>{this.indexCache.get(t)===n&&this.indexCache.delete(t)})),n}async fetchIndex(t){let n=await this.configResolver.getConfig(t),r=this.configResolver.resolveIndexUrl(t,n),e=this.fetchFn?await this.fetchFn(r,t):await fetch(r);if(!e.ok)throw new Error(`Failed to fetch publisher index: ${r} (${e.status} ${e.statusText})`);let s=await e.text();return c.parseIndex(s)}static parseIndex(t){let n=new Map;for(let r of t.split(`
|
|
2
2
|
`)){let e=r.trim();if(!e||e.startsWith("#"))continue;let s=e.indexOf("/");if(s===-1)continue;let i=e.substring(0,s),o=e.substring(s+1);if(!i||!o)continue;let a=n.get(i);a?a.push(o):n.set(i,[o])}return n}isVersionCompatible(t,n,r){let e=c.parseVersion(t);if(!e)return!1;switch(r){case m.Any:return!0;case m.Exact:return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch;case m.Compatible:return e.major===n.major&&e.minor===n.minor&&e.patch>=n.patch;case m.Major:return e.major!==n.major?!1:e.minor>n.minor?!0:e.minor===n.minor?e.patch>=n.patch:!1;default:return!1}}static parseVersion(t){let n=t.split(".");if(n.length<2)return null;let r=parseInt(n[0],10),e=parseInt(n[1],10),s=n.length>=3?parseInt(n[2],10):0;return isNaN(r)||isNaN(e)||isNaN(s)?null:{major:r,minor:e,patch:s}}compareVersionStrings(t,n){let r=c.parseVersion(t),e=c.parseVersion(n);return!r&&!e?0:r?e?r.major!==e.major?r.major-e.major:r.minor!==e.minor?r.minor-e.minor:r.patch-e.patch:1:-1}};import{VersionOperator as C}from"@kanonak-protocol/types/document/models/enums";var F=class{parser=new y;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(t){this.onFetch=t?.onFetch,this.getFromCache=t?.getFromCache,this.fetchFn=t?.fetchFn,this.publisherIndex=t?.fetchFn?new l({fetchFn:t.fetchFn}):new l}async getHighestCompatibleVersionAsync(t,n){if((await this.publisherIndex.getConfig(t)).resolveByRedirect)return this.resolveByRedirect(t,n);let e=await this.publisherIndex.resolveVersion(t,n);if(!e)return null;let s=`${t}/${n.packageName}@${e}`,i=this.documents.get(s);if(i)return i;if(this.getFromCache){let p=this.getFromCache(t,n.packageName,e);if(p){let d=this.parser.parse(p);return u(d,t,n.packageName,e),this.documents.set(s,d),this.contentCache.set(s,p),d}}let o=await this.publisherIndex.getPackageUrl(t,n.packageName,e),a=this.fetchFn?await this.fetchFn(o,t):await fetch(o);if(!a.ok)throw new Error(`Failed to fetch Kanonak package: ${o} (${a.status} ${a.statusText})`);let g=await a.text(),h=this.parser.parse(g);return u(h,t,n.packageName,e),this.onFetch&&this.onFetch(t,n.packageName,e,g),this.documents.set(s,h),this.contentCache.set(s,g),h}async resolveByRedirect(t,n){let r=n.packageName,s=n.versionOperator===C.Exact?await this.publisherIndex.getPackageUrl(t,r,v(n.version)):`https://${t}/${r}.kan.yml`,i=await this.fetchFollowing(s,t);if(!i)return null;let o=this.parser.parse(i.content),a=o.metadata.namespace_;if(!a||!a.version)throw new Error(`Producer origin returned a package with no namespace/version for ${t}/${r}`);let g=v(a.version);u(o,t,r,g);let h=`${t}/${r}@${g}`;return this.onFetch&&this.onFetch(t,r,g,i.content),this.documents.set(h,o),this.contentCache.set(h,i.content),o}async fetchFollowing(t,n,r=4){let e=t;for(let s=0;s<r;s++){let i=this.fetchFn?await this.fetchFn(e,n):await fetch(e,{redirect:"manual"});if(i.status===301||i.status===302){let o=i.headers.get("location");if(!o)throw new Error(`Redirect with no Location header from ${e}`);e=new URL(o,e).toString();continue}if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${e} (${i.status} ${i.statusText})`);return{url:e,content:await i.text()}}throw new Error(`Too many redirects resolving ${t}`)}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(t){return this.documents.get(t)??null}async getDocumentsByNamespaceAsync(t,n){return Array.from(this.documents.values()).filter(r=>{let e=r.metadata.namespace_;return e&&e.publisher===t&&e.package_===n})}async saveDocumentAsync(t,n){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(t){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(t,n){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(t){return this.contentCache.get(t)??null}async getDocumentUriAsync(t){let n=t.match(/^(.+?)\/(.+?)@(.+)$/);if(!n)return null;let[,r,e,s]=n;return this.publisherIndex.getPackageUrl(r,e,s)}};export{A as a,f as b,l as c,F as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as j,b as x,i as _}from"./chunk-
|
|
1
|
+
import{a as j,b as x,i as _}from"./chunk-7GAOBCNZ.js";import{d as l,e as u,f as b,g as $,h as s,j as h}from"./chunk-VKTFLHCW.js";import{c as S,d as O,g as I,h as T,i as g,j as v,k as L,l as q}from"./chunk-T3JR2SV6.js";var d=class{all=new Set;byPIdx=new Map;bySPIdx=new Map;byPOIdx=new Map;tripleList=[];add(e){let t=b(e);return this.all.has(t)?!1:(this.all.add(t),this.tripleList.push(e),P(this.byPIdx,e.p,e),P(this.bySPIdx,`${e.s}|${e.p}`,e),e.o.kind==="uri"&&P(this.byPOIdx,`${e.p}|${e.o.key}`,e),!0)}has(e){return this.all.has(b(e))}size(){return this.tripleList.length}snapshot(){return this.tripleList.slice()}byPredicate(e){let t=this.byPIdx.get(e);return t?t.slice():[]}bySubjectPredicate(e,t){let r=this.bySPIdx.get(`${e}|${t}`);return r?r.slice():[]}byPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);return r?r.slice():[]}subjectsWithPredicateObject(e,t){let r=this.byPOIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let a of r)n.add(a.s);return Array.from(n)}uriObjectsOf(e,t){let r=this.bySPIdx.get(`${e}|${t}`);if(!r)return[];let n=new Set;for(let a of r)a.o.kind==="uri"&&n.add(a.o.key);return Array.from(n)}hasUri(e,t,r){return this.all.has(`${e}|${t}|u:${r}`)}hasTriple(e,t,r){return this.all.has(`${e}|${t}|${$(r)}`)}};function P(o,e,t){let r=o.get(e);r?r.push(t):o.set(e,[t])}var w={name:"rdfs2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.domain)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},C={name:"rdfs3",apply(o,e){let t=!1;for(let r of o.byPredicate(e.range)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,e.type,a))&&(t=!0)}return t}},A={name:"rdfs5",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subPropertyOf))i.o.kind==="uri"&&o.add(s(n,e.subPropertyOf,i.o.key))&&(t=!0)}return t}},V={name:"rdfs7",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subPropertyOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n)){let f={s:i.s,p:a,o:i.o};o.add(f)&&(t=!0)}}return t}},W={name:"rdfs9",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},F={name:"rdfs11",apply(o,e){let t=!1;for(let r of o.byPredicate(e.subClassOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.bySubjectPredicate(a,e.subClassOf))i.o.kind==="uri"&&o.add(s(n,e.subClassOf,i.o.key))&&(t=!0)}return t}},k=[w,C,A,V,W,F];var N={name:"prp-trp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.transitiveProperty);for(let n of r){let a=o.byPredicate(n);for(let i of a){if(i.o.kind!=="uri")continue;let f=i.o.key;for(let c of o.bySubjectPredicate(f,n))c.o.kind==="uri"&&i.s!==c.o.key&&o.add(s(i.s,n,c.o.key))&&(t=!0)}}return t}},D={name:"prp-symp",apply(o,e){let t=!1,r=o.subjectsWithPredicateObject(e.type,e.symmetricProperty);for(let n of r)for(let a of o.byPredicate(n))a.o.kind==="uri"&&o.add(s(a.o.key,n,a.s))&&(t=!0);return t}},z={name:"prp-inv1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(n))i.o.kind==="uri"&&o.add(s(i.o.key,a,i.s))&&(t=!0)}return t}},B={name:"prp-inv2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.inverseOf)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;for(let i of o.byPredicate(a))i.o.kind==="uri"&&o.add(s(i.o.key,n,i.s))&&(t=!0)}return t}},M={name:"prp-eqp1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(n))o.add({s:i.s,p:a,o:i.o})&&(t=!0)}return t}},G={name:"prp-eqp2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentProperty)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicate(a))o.add({s:i.s,p:n,o:i.o})&&(t=!0)}return t}},H={name:"cax-eqc1",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,n))o.add(s(i.s,e.type,a))&&(t=!0)}return t}},J={name:"cax-eqc2",apply(o,e){let t=!1;for(let r of o.byPredicate(e.equivalentClass)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.byPredicateObject(e.type,a))o.add(s(i.s,e.type,n))&&(t=!0)}return t}},Q={name:"eq-rep-s",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a){for(let i of o.snapshot())i.s===n&&o.add({s:a,p:i.p,o:i.o})&&(t=!0);for(let i of o.snapshot())i.s===a&&o.add({s:n,p:i.p,o:i.o})&&(t=!0)}}return t}},X={name:"eq-rep-o",apply(o,e){let t=!1;for(let r of o.byPredicate(e.sameAs)){if(r.o.kind!=="uri")continue;let n=r.s,a=r.o.key;if(n!==a)for(let i of o.snapshot())i.o.kind==="uri"&&(i.o.key===n?o.add(s(i.s,i.p,a))&&(t=!0):i.o.key===a&&o.add(s(i.s,i.p,n))&&(t=!0))}return t}},K=[N,D,z,B,M,G,H,J,Q,X];var y=class{constructor(e,t){this.store=e;this.vocabulary=t}store;vocabulary;getInstancesOfClass(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.type,t)}getSubclasses(e){let t=p(e);return this.store.subjectsWithPredicateObject(this.vocabulary.subClassOf,t).filter(n=>n!==t)}getSuperclasses(e){let t=p(e);return this.store.uriObjectsOf(t,this.vocabulary.subClassOf).filter(r=>r!==t)}getTypesOfIndividual(e){return this.store.uriObjectsOf(p(e),this.vocabulary.type)}isInstanceOf(e,t){return this.store.hasUri(p(e),this.vocabulary.type,p(t))}triples(){return this.store.snapshot()}size(){return this.store.size()}};function p(o){return typeof o=="string"?o:u(o.publisher,o.package_,o.name)}var R=class{vocabulary;profile;maxIterations;constructor(e={}){this.vocabulary=e.vocabulary??new h,this.profile=e.profile??"owl-rl-classification",this.maxIterations=e.maxIterations??100}async reason(e){let t=new d,n=await new _().parseKanonaks(e),a=new U;for(let c of n)if(c instanceof S){let m=Y(c);if(!m)continue;for(let E of c.statement)this.emitStatement(m,E,t,a)}let i=[...k];this.profile==="owl-rl-classification"&&i.push(...K);let f=0;for(;f<this.maxIterations;){let c=!1;for(let m of i)m.apply(t,this.vocabulary)&&(c=!0);if(!c)break;f++}return new y(t,this.vocabulary)}emitStatement(e,t,r,n){let a=Z(t);if(a){if(t instanceof I){r.add({s:e,p:a,o:{kind:"literal",lexical:t.object,datatype:"string"}});return}if(t instanceof T){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"number"}});return}if(t instanceof g){r.add({s:e,p:a,o:{kind:"literal",lexical:String(t.object),datatype:"boolean"}});return}if(t instanceof v){let i=l(t.object.subject);r.add(s(e,a,i));return}if(t instanceof L){let i=n.next();r.add({s:e,p:a,o:{kind:"blank",id:i}}),this.emitEmbedded(i,t.object,r,n);return}if(t instanceof q){for(let i of t.object??[])this.emitListItem(e,a,i,r,n);return}}}emitListItem(e,t,r,n,a){if(r instanceof O)n.add(s(e,t,l(r.subject)));else if(r instanceof j){let i=a.next();n.add({s:e,p:t,o:{kind:"blank",id:i}}),this.emitEmbedded(i,r,n,a)}else if(r instanceof x){let i=typeof r.value=="number"?"number":typeof r.value=="boolean"?"boolean":"string";n.add({s:e,p:t,o:{kind:"literal",lexical:String(r.value),datatype:i}})}}emitEmbedded(e,t,r,n){let a=`_:${e}`;for(let i of t.statement)this.emitStatement(a,i,r,n)}},U=class{counter=0;next(){return`b${this.counter++}`}};function Y(o){let e=o.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),n=r.indexOf("/");if(n===-1)return null;let a=r.substring(0,n),i=r.substring(n+1);return!a||!i||!o.name?null:u(a,i,o.name)}function Z(o){let e=o.predicate;return e?.subject?l(e.subject):null}export{d as a,k as b,K as c,y as d,R as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as V}from"./chunk-
|
|
1
|
+
import{h as V}from"./chunk-7GAOBCNZ.js";import{a as E}from"./chunk-EP7CJSV2.js";var L=class{propertyUri;propertyType;range;rangeUri;isImported;definedInNamespace};import{parseDocument as O,LineCounter as R,isMap as h,isPair as f,isScalar as g,isSeq as I}from"yaml";var K=class i{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;nestedKeys=new Map;nestedValues=new Map;static fromContent(e){let t=new i,n=new R,r=O(e,{lineCounter:n});if(r.errors.length>0||!h(r.contents))return t;N(r.contents,[],n,t);for(let o of r.contents.items){if(!f(o)||!g(o.key))continue;let a=String(o.key.value),u=o.key.range;if(!u)continue;t.entities.set(a,d(u,n));let s=o.value,c=s&&typeof s=="object"&&"range"in s?s.range:void 0;if(c?t.entityBlocks.set(a,d([u[0],u[1],c[2]],n)):t.entityBlocks.set(a,d(u,n)),h(o.value)){let k=new Map,m=new Map,l=new Map;for(let P of o.value.items){if(!f(P)||!g(P.key))continue;let b=String(P.key.value),p=P.key.range;p&&k.set(b,d(p,n));let S=P.value;if(S&&typeof S=="object"&&"range"in S&&Array.isArray(S.range)){let v=S.range;m.set(b,d(v,n))}if(I(S)){let v=[];for(let M of S.items)M&&typeof M=="object"&&"range"in M&&Array.isArray(M.range)&&v.push(d(M.range,n));v.length>0&&l.set(b,v)}}k.size>0&&t.properties.set(a,k),m.size>0&&t.propertyValues.set(a,m),l.size>0&&t.valueListItems.set(a,l);let y=j(o.value,n);y.length>0&&t.importPackages.set(a,y)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[n,r]of this.entityBlocks)if(w(r,e,t))return n}findPropertyAtPosition(e,t){let n=this.findEntityAtPosition(e,t);if(!n)return;let r=this.properties.get(n),o=this.propertyValues.get(n);if(!r&&!o)return{entityName:n};let a,u;if(o)for(let[s,c]of o)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);if(r)for(let[s,c]of r)w(c,e,t)&&(!u||C(c,u))&&(a=s,u=c);return a?{entityName:n,propertyName:a}:{entityName:n}}getPropertyPosition(e,t){return this.properties.get(e)?.get(t)}getPropertyValuePosition(e,t){return this.propertyValues.get(e)?.get(t)}getImportPackages(e){return this.importPackages.get(e)??[]}getAllImportPackages(){let e=[];for(let[t,n]of this.importPackages)for(let r of n)e.push({entityName:t,entry:r});return e}findPropertySourceName(e,t){let n=this.properties.get(e);if(n){if(n.has(t))return t;for(let r of n.keys()){let o=r.lastIndexOf(".");if((o===-1?r:r.substring(o+1))===t)return r}}}getListItemPosition(e,t,n){let r=this.valueListItems.get(e)?.get(t);if(!(!r||n<0||n>=r.length))return r[n]}getNodeKeyPosition(e){return this.nestedKeys.get(JSON.stringify(e))}getNodeValuePosition(e){return this.nestedValues.get(JSON.stringify(e))}setNestedKeyPosition(e,t){this.nestedKeys.set(e,t)}setNestedValuePosition(e,t){this.nestedValues.set(e,t)}getMostSpecificPosition(e,t,n){if(e){if(t!==void 0){if(n!==void 0){let a=this.getListItemPosition(e,t,n);if(a)return a}let r=this.getPropertyValuePosition(e,t);if(r)return r;let o=this.getPropertyPosition(e,t);if(o)return o}return this.getEntityPosition(e)}}};function j(i,e){let t=[];if(!h(i))return t;let n=i.items.find(r=>f(r)&&g(r.key)&&String(r.key.value)==="imports");if(!n||!f(n)||!I(n.value))return t;for(let r of n.value.items){if(!h(r))continue;let o=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="publisher");if(!o||!f(o)||!g(o.value))continue;let a=String(o.value.value),u=r.items.find(s=>f(s)&&g(s.key)&&String(s.key.value)==="packages");if(!(!u||!f(u)||!I(u.value)))for(let s of u.value.items){if(!h(s))continue;let c=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="package");if(!c||!f(c)||!g(c.value)||!c.value.range)continue;let k=String(c.value.value),m=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="version"),l=m&&f(m)&&g(m.value)?String(m.value.value):"",y=s.items.find(p=>f(p)&&g(p.key)&&String(p.key.value)==="alias"),P=y&&f(y)&&g(y.value)?String(y.value.value):void 0,b=P!==void 0?{publisher:a,package_:k,version:l,alias:P,position:d(c.value.range,e)}:{publisher:a,package_:k,version:l,position:d(c.value.range,e)};t.push(b)}}return t}function w(i,e,t){return!(e<i.line||e>i.endLine||e===i.line&&t<i.column||e===i.endLine&&t>i.endColumn)}function C(i,e){let t=i.endLine-i.line,n=e.endLine-e.line;if(t!==n)return t<n;let r=i.endLine===i.line?i.endColumn-i.column:Number.MAX_SAFE_INTEGER,o=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return r<o}function N(i,e,t,n){if(h(i)){for(let r of i.items){if(!f(r)||!g(r.key))continue;let o=String(r.key.value),a=[...e,o],u=JSON.stringify(a);r.key.range&&n.setNestedKeyPosition(u,d(r.key.range,t));let s=r.value,c=D(s);c&&n.setNestedValuePosition(u,d(c,t)),N(s,a,t,n)}return}if(I(i)){for(let r=0;r<i.items.length;r++){let o=i.items[r],a=[...e,r],u=JSON.stringify(a),s=D(o);s&&n.setNestedValuePosition(u,d(s,t)),N(o,a,t,n)}return}}function D(i){if(!i||typeof i!="object"||!("range"in i))return;let e=i.range;return Array.isArray(e)&&e.length>=3?e:void 0}function d(i,e){let t=e.linePos(i[0]),n=e.linePos(i[2]);return{line:t.line-1,column:t.col-1,endLine:n.line-1,endColumn:n.col-1}}function x(i,e){let n=(e??new E).parse(i),r=K.fromContent(i);return{document:n,positions:r}}function W(i,e,t,n,r){if(e<n.line||e>n.endLine||e===n.line&&t<n.column||e===n.endLine&&t>=n.endColumn)return;let o=A(r,n.line,n.column),a=A(r,n.endLine,n.endColumn);if(o<0||a<0)return;let u=r.substring(o,a),s=V(u);if(s.length!==i.links.length)return;let c=e-n.line,k=e===n.line?t-n.column:t,m=A(u,c,k);if(!(m<0))for(let l=0;l<s.length;l++){let y=s[l];if(m>=y.startOffset&&m<y.endOffset)return i.links[l]}}function A(i,e,t){let n=0,r=0;for(let o=0;o<i.length;o++){if(n===e)return Math.min(r+t,i.length);i[o]===`
|
|
2
2
|
`&&(n++,r=o+1)}return n===e?Math.min(r+t,i.length):-1}export{L as a,K as b,x as c,W as d};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as bn,b as Pn,c as wn,d as Sn,e as be}from"./chunk-
|
|
1
|
+
import{a as bn,b as Pn,c as wn,d as Sn,e as be}from"./chunk-TC4MITSK.js";import{a as fr,c as Ce,e as He,h as ze,i as We,j as yr}from"./chunk-BH5TB6XY.js";import{a as gn,b as hn,c as kn,d as W,e as G,f as l,g as gr}from"./chunk-FXFZZCCD.js";import{a as mr}from"./chunk-G7XXA2JL.js";import"./chunk-QHABFCRC.js";import{a as zt,b as Wt,c as Gt,d as Jt,e as qt,f as en,g as tn,h as nn}from"./chunk-FFMZ7GQM.js";import{b as Yt,c as Zt,d as Qt}from"./chunk-NNUV6K3C.js";import{a as Ht}from"./chunk-4NO7MHS7.js";import{a as Rn,b as En,c as xn,d as In}from"./chunk-UV6CLM2Y.js";import{a as vn,b as On}from"./chunk-PEUTCG3B.js";import{a as $n}from"./chunk-PEJALHXK.js";import{a as Xt}from"./chunk-SC5M74NM.js";import{A as cr,B as lr,C as ur,D as pr,M as dr,a as Dn,b as Nn,c as Tn,d as _n,e as Ln,f as Un,g as Fn,h as Mn,i as Hn,j as zn,k as Wn,l as Gn,m as Jn,n as qn,o as Yn,p as Zn,q as Xn,r as Qn,s as er,t as tr,u as nr,v as rr,w as or,x as ar,y as ir,z as sr}from"./chunk-KARUKDEM.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as C,c as an,d as Fe,e as v,f as ke,g as mn,h as fn,i as $}from"./chunk-7GAOBCNZ.js";import{a as S}from"./chunk-EP7CJSV2.js";import{a as yn,b as Pe,c as Kn,d as h,e as jn,f as Vn,g as An,h as Bn}from"./chunk-UK2OIPAB.js";import{f as z,k as j,l as we,m as Se,n as Me}from"./chunk-PBNVHBS3.js";import{b as sn,c as cn,d as K,e as ln,f as un,h as pn,j as dn}from"./chunk-VKTFLHCW.js";import{a as rn,b as fe,c as f,d as p,e as on,f as ye,g as R,h as ge,i as he,j as E,k as x,l as I}from"./chunk-T3JR2SV6.js";import{a as H}from"./chunk-FUUTGGJS.js";import{a as Nt,b as me,c as M,d as Tt,e as k,f as _t,g as Lt,h as Ut,i as Ft,j as Mt}from"./chunk-2ACBWC7K.js";import{a as Cn}from"./chunk-ODIECDN7.js";import{VersionOperator as Di}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Br,readFileSync as Or}from"fs";import{homedir as Dr}from"os";import{join as Nr}from"path";import{execFile as hr}from"child_process";import{promisify as kr}from"util";var J=kr(hr),q="kanonak",Y="/usr/bin/security",V=class{async get(e){let t=l(e);try{let{stdout:r}=await J(Y,["find-generic-password","-s",q,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(r.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
|
|
2
2
|
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(r){if(Ge(r,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${Z(r)}
|
|
3
3
|
The Keychain may be locked or inaccessible.
|
|
4
4
|
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let r=l(e),o=JSON.stringify(t);try{await J(Y,["add-generic-password","-s",q,"-a",r,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${r}': ${Z(a)}
|
|
@@ -9,11 +9,24 @@ export declare class KanonakParser implements IKanonakParser {
|
|
|
9
9
|
private createVersion;
|
|
10
10
|
private extractMetadata;
|
|
11
11
|
private extractBody;
|
|
12
|
-
private parseNamespace;
|
|
13
12
|
private parseVersion;
|
|
14
13
|
private parseImportsV3;
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Parse one authored import object (`{ package, match, version, alias? }`)
|
|
16
|
+
* into an {@link Import}. Validates the required fields — a missing
|
|
17
|
+
* `package`/`match`/`version` is an error (never a fabricated default), then
|
|
18
|
+
* delegates to the single {@link makeImport} builder.
|
|
19
|
+
*/
|
|
16
20
|
private parseImportFromEmbeddedObject;
|
|
21
|
+
/**
|
|
22
|
+
* THE single {@link Import} constructor — every import, whether parsed from a
|
|
23
|
+
* document or built by parts ({@link buildImport}), is produced here, so the
|
|
24
|
+
* operator/version/min-max/identity fields are computed one way. `operator`
|
|
25
|
+
* is the character form (`= ~ ^ *`); `version` is a `major.minor.patch`
|
|
26
|
+
* string. No fabricated defaults: callers supply the operator and version
|
|
27
|
+
* (the parser rejects an authored import that omits them).
|
|
28
|
+
*/
|
|
29
|
+
private makeImport;
|
|
17
30
|
/**
|
|
18
31
|
* Build a single {@link Import} from its parts — the canonical way to
|
|
19
32
|
* construct one OUTSIDE parsing a document (e.g. to request a seed package
|
|
@@ -23,7 +36,6 @@ export declare class KanonakParser implements IKanonakParser {
|
|
|
23
36
|
* the character form (`= ~ ^ *`); `version` is a `major.minor.patch` string.
|
|
24
37
|
*/
|
|
25
38
|
buildImport(packageName: string, operator: string, version: string, publisher?: string): Import;
|
|
26
|
-
private parseImport;
|
|
27
39
|
private parseVersionOperator;
|
|
28
40
|
private calculateMaxVersion;
|
|
29
41
|
private serializeImports;
|
package/dist/parsing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c,b as d,c as e,d as f}from"../chunk-
|
|
1
|
+
import{a as c,b as d,c as e,d as f}from"../chunk-UV6CLM2Y.js";import{i as b}from"../chunk-7GAOBCNZ.js";import{a}from"../chunk-EP7CJSV2.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{d as KanonakDocumentPositions,b as KanonakObjectParser,a as KanonakParser,c as PropertyMetadata,f as findMarkdownLinkAt,e as parseWithPositions};
|
package/dist/reasoning/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as g,b as h,c as i,d as j,e as k}from"../chunk-
|
|
1
|
+
import{a as g,b as h,c as i,d as j,e as k}from"../chunk-TC4MITSK.js";import"../chunk-7GAOBCNZ.js";import"../chunk-EP7CJSV2.js";import{d as a,e as b,f as c,h as d,i as e,j as f}from"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{f as KanonakVocabulary,i as OWL_RL_CLASSIFICATION_RULES,h as RDFS_RULES,k as Reasoner,j as ReasoningResult,g as TripleStore,e as canonicalizeBuiltinUri,b as makeUriKey,c as tripleKey,a as uriKey,d as uriTriple};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e,c as r,d as n}from"../chunk-
|
|
1
|
+
import{b as e,c as r,d as n}from"../chunk-NNUV6K3C.js";import{a as o}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-EP7CJSV2.js";import"../chunk-2ACBWC7K.js";export{n as HttpKanonakDocumentRepository,o as InMemoryKanonakDocumentRepository,e as PublisherConfigResolver,r as PublisherIndex};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-
|
|
1
|
+
import{a as b,b as c,c as d,d as e,e as f,f as k,g as l,h as m}from"../chunk-FFMZ7GQM.js";import{a as g,b as h,c as i,d as j}from"../chunk-NNUV6K3C.js";import{a}from"../chunk-4NO7MHS7.js";import"../chunk-SC5M74NM.js";import"../chunk-EP7CJSV2.js";import"../chunk-2ACBWC7K.js";export{d as CompositeKanonakDocumentRepository,c as DocumentLocation,b as FileSystemKanonakDocumentRepository,j as HttpKanonakDocumentRepository,a as InMemoryKanonakDocumentRepository,k as LocalFirstRepository,h as PublisherConfigResolver,i as PublisherIndex,f as RepositoryFactory,m as buildLocalFirstRepository,l as collectKanonakFiles,g as defaultPublisherConfig,e as getGlobalCachePath};
|
package/dist/search/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as g}from"../chunk-
|
|
1
|
+
import{a as g}from"../chunk-BH5TB6XY.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-7GAOBCNZ.js";import"../chunk-EP7CJSV2.js";import{d as m,h as S}from"../chunk-UK2OIPAB.js";import{a as p,f as E}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as v}from"../chunk-T3JR2SV6.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+`
|
package/dist/server/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as E}from"../chunk-
|
|
1
|
+
import{j as E}from"../chunk-BH5TB6XY.js";import"../chunk-QHABFCRC.js";import{a as Z,d as A,f as te,g as N}from"../chunk-FFMZ7GQM.js";import{a as ee,b as re,c as V,d as I}from"../chunk-NNUV6K3C.js";import{a as X}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as oe}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as L}from"../chunk-7GAOBCNZ.js";import{a as D}from"../chunk-EP7CJSV2.js";import{b as O}from"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{c as ne}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{c as F,e as z,f as K,g as Q}from"../chunk-2ACBWC7K.js";import{readFileSync as ue,existsSync as de,readdirSync as me,writeFileSync as ge,mkdirSync as fe}from"fs";import{join as q}from"path";function se(n){let e=n.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function M(n,e){let t=new Set,r=[...n];for(;r.length>0;){let o=r.shift(),i=se(o);if(!i||t.has(i))continue;t.add(i);let d=o.metadata?.imports;if(d)for(let[c,f]of Object.entries(d))for(let g of f)try{let l=await e.getHighestCompatibleVersionAsync(c,g);l&&r.push(l)}catch{}}return t}var j=class{constructor(e,t){this.inner=e;this.scope=t}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(t=>{let r=se(t);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){return this.inner.getDocumentsByNamespaceAsync(e,t)}getHighestCompatibleVersionAsync(e,t){return this.inner.getHighestCompatibleVersionAsync(e,t)}saveDocumentAsync(e,t){return this.inner.saveDocumentAsync(e,t)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,t){return this.inner.clearNamespaceAsync(e,t)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var ae=[{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 C(n){let e=n?.render;if(e&&e.length>0){let t=[];for(let r of e)try{let o=O(r);o.kind==="package"?t.push({publisher:o.publisher,package_:o.package_}):o.kind==="resource"&&t.push({publisher:o.uri.publisher,package_:o.uri.package_})}catch{}if(t.length>0)return t}return ae}function H(n){return`${n.publisher}/${n.package_}`}function B(n){let{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,producers:c}=n,f=new Map,g=new Map,l=new Map,a=new Set;for(let m of r){if(!(m instanceof ne))continue;let y=m.namespace||"";if(!i.has(y))continue;f.set(`${y}/${m.name}`,m);let v=y.split("/")[1]??"",[x,p]=v.split("@");if(!x||!p)continue;let b=Q(p);b&&(a.has(v)||(a.add(v),g.has(x)||g.set(x,[]),g.get(x).push({verStr:p,version:b})),m.name===x&&l.set(v,m))}for(let m of g.values())m.sort((y,v)=>F(v.version,y.version));return{publisher:e,availablePublishers:t,catalog:r,lookRenderer:o,localNamespaces:i,rawByNsKey:d,bySubject:f,pkgVersions:g,pkgSelfByVer:l,...c?{producers:c}:{}}}async function T(n,e={}){let t=new D,r=new X(t),o=[],i=[];for(let p of N(n)){let b;try{b=ue(p,"utf-8")}catch{continue}let w;try{w=t.parse(b).metadata?.namespace_}catch{continue}if(!w?.version)continue;let $=w.version;i.push({publisher:w.publisher,package_:w.package_,verStr:`${$.major}.${$.minor}.${$.patch}`,version:$,source:b})}i.sort((p,b)=>F(b.version,p.version));for(let p of i)await r.saveDocumentAsync(t.parse(p.source),`${p.publisher}/${p.package_}@${p.verStr}`),o.push({publisher:p.publisher,package_:p.package_,verStr:p.verStr,source:p.source});let d=[...new Set(o.map(p=>p.publisher))].sort(),c=e.publisher;if(c){if(!d.includes(c))throw new Error(`Publisher "${c}" not found in workspace. Available: ${d.join(", ")||"(none)"}`)}else if(d.length===1)c=d[0];else throw d.length===0?new Error(`No Kanonak packages found under ${n}`):new Error(`Workspace has multiple publishers (${d.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let f=new Set,g=new Map;for(let p of o)p.publisher===c&&(f.add(`${p.publisher}/${p.package_}@${p.verStr}`),g.set(`${p.package_}@${p.verStr}`,p.source));let l=new Z(A(),!0,t),a=e.repository??new te(r,l,new I(e.httpCache?{getFromCache:e.httpCache.getFromCache,onFetch:e.httpCache.onFetch}:void 0)),m=C(void 0);if(!e.repository){let p=A(),b=s=>{let h=q(p,s);return de(h)?new Set(me(h).filter(k=>k.endsWith(".kan.yml")).map(k=>k.split("@")[0])):new Set},w=(s,h)=>o.some(k=>k.publisher===s&&k.package_===h),$=new V,u=new Map;for(let s of m)if(u.has(s.publisher)||u.set(s.publisher,b(s.publisher)),!(u.get(s.publisher).has(s.package_)||w(s.publisher,s.package_)))try{let h=await $.getHighestVersion(s.publisher,s.package_);if(!h)continue;let k=await $.getPackageUrl(s.publisher,s.package_,h),_=await fetch(k);if(!_.ok)continue;let le=await _.text(),J=q(p,s.publisher);fe(J,{recursive:!0}),ge(q(J,`${s.package_}@${h}.kan.yml`),le,"utf-8")}catch{}}let y=a;if(!e.repository){let p=(await r.getAllDocumentsAsync()).filter(w=>w.metadata.namespace_?.publisher===c),b=await M(p,a);for(let w of m)b.add(H(w));y=new j(a,b)}let v=await new L(t).parseKanonaks(y),x=new E(v);return B({publisher:c,availablePublishers:d,catalog:v,lookRenderer:x,localNamespaces:f,rawByNsKey:g})}import{existsSync as he,readFileSync as ke,writeFileSync as ye,mkdirSync as ve}from"fs";import{join as ie}from"path";async function U(n,e={}){let t=new D,r=O(n),o=r.kind==="resource"?r.uri.publisher:r.publisher,i=e.cacheRoot??A(),d=(u,s,h)=>ie(i,u,`${s}@${h}.kan.yml`),c=new I({getFromCache:(u,s,h)=>{let k=d(u,s,h);return he(k)?ke(k,"utf-8"):null},onFetch:(u,s,h,k)=>{let _=ie(i,u);ve(_,{recursive:!0}),ye(d(u,s,h),k,"utf-8")},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),f=new V(e.fetchFn?{fetchFn:e.fetchFn}:void 0),g;if(r.kind==="resource"){let u=r.uri.version;g=[u?{package_:r.uri.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let u=r.version;g=[u?{package_:r.package_,version:`${u.major}.${u.minor}.${u.patch}`}:{package_:r.package_}]}else g=(await f.listLatestPackages(o)).map(s=>({package_:s.packageName}));let l=async(u,s,h)=>{try{let k=h?t.buildImport(s,"=",h,u):t.buildImport(s,"*","0.0.0",u);return await c.getHighestCompatibleVersionAsync(u,k)}catch{return null}},a=[];for(let u of g){let s=await l(o,u.package_,u.version);s&&a.push(s)}if(a.length===0)throw new Error(`Could not fetch any package for address "${n}" from publisher "${o}".`);let m=await new re().getConfig(o).catch(()=>{}),y=[];for(let u of C(m)){let s=await l(u.publisher,u.package_,void 0);s&&y.push(s)}let v=await M([...a,...y],c),x=new j(c,v),p=await new L(t).parseKanonaks(x),b=new E(p),w=new Set,$=new Map;for(let u of await c.getAllDocumentsAsync()){let s=u.metadata.namespace_;if(!s||s.publisher!==o)continue;let h=`${s.version.major}.${s.version.minor}.${s.version.patch}`,k=`${s.publisher}/${s.package_}@${h}`;w.add(k);let _=await c.getDocumentContentAsync(k);_!==null&&$.set(`${s.package_}@${h}`,_)}return B({publisher:o,availablePublishers:[o],catalog:p,lookRenderer:b,localNamespaces:w,rawByNsKey:$})}import{VersionOperator as W}from"@kanonak-protocol/types/document/models/enums";var S={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".md":"text/markdown; charset=utf-8",".kan.yml":"application/yaml; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8"},R=(n,e,t,r)=>({status:n,headers:{"Content-Type":e,...r||{}},body:t}),P=n=>R(404,S[".html"],`<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Not found: ${n}</p>`),be=n=>({status:301,headers:{Location:n},body:""}),we=n=>({status:302,headers:{Location:n},body:""});function Se(n){switch(n.kind){case"exact":return{operator:W.Exact,version:K(n.major,n.minor,n.patch)};case"minor-pin":return{operator:W.Compatible,version:K(n.major,n.minor,0)};case"major-pin":return{operator:W.Major,version:K(n.major,0,0)};default:return{operator:W.Any,version:K(0,0,0)}}}async function Re(n,e,t,r){if(!r)return null;let o=n.producers?.find(f=>f.canProduce(n.publisher,e));if(!o)return null;let i=await o.resolveVersion(n.publisher,e,Se(t));if(!i)return null;let d=z(i);if(t.kind!=="exact")return we(`/${e}/${d}.kan.yml`);let{source:c}=await o.produce(n.publisher,e,i);return R(200,S[".kan.yml"],c)}function ce(n,e,t){let r=n.pkgVersions.get(e);if(!r||r.length===0)return null;switch(t.kind){case"any":return r[0].verStr;case"major-pin":return r.find(o=>o.version.major===t.major)?.verStr??null;case"minor-pin":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor)?.verStr??null;case"exact":return r.find(o=>o.version.major===t.major&&o.version.minor===t.minor&&o.version.patch===t.patch)?.verStr??null;default:return null}}async function G(n,e,t=""){let{lookRenderer:r,publisher:o}=n;if(e==="/.well-known/kanonak.json"){let a=ee(o);return n.producers&&n.producers.length>0&&(a.resolveByRedirect=!0),R(200,S[".json"],JSON.stringify(a,null,2))}if(e==="/index.txt"){let a=[...n.localNamespaces].map(m=>m.split("/")[1].replace("@","/")).sort();return R(200,S[".txt"],a.join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`)}if(e==="/"||e==="/index.html"||e==="/index.css"){let a=r.publisherSubject(o);return e==="/index.css"?R(200,S[".css"],r.renderStylesheet(a)):R(200,S[".html"],await r.renderDocument(a,{rootIndex:!0}))}let i=".html",d=!1,c=e;for(let a of[".kan.yml",".css",".svg",".md",".html"])if(e.endsWith(a)){i=a,d=!0,c=e.slice(0,-a.length);break}let f=!d&&/application\/yaml|text\/yaml/i.test(t),g=c.endsWith("/");g&&c!=="/"&&(c=c.slice(0,-1));let l=oe.parse(c,o);if(!l)return P(e);if(l.kind==="package"){let a=ce(n,l.package_,l.versionSpec);if(!a)return await Re(n,l.package_,l.versionSpec,i===".kan.yml"||f)??P(e);if(i===".kan.yml"||f){let v=n.rawByNsKey.get(`${l.package_}@${a}`);return v!==void 0?R(200,S[".kan.yml"],v):P(e)}let m=n.pkgSelfByVer.get(`${l.package_}@${a}`);if(!m)return P(e);if(i===".css")return R(200,S[".css"],r.renderStylesheet(m));if(!g)return be(c+"/");let y=l.versionSpec.kind==="any";if(y&&!r.hasDeclaredView(m)){let v=(n.pkgVersions.get(l.package_)||[]).map(x=>x.verStr);return R(200,S[".html"],r.renderPackageVersionList(l.package_,v,m))}return R(200,S[".html"],await r.renderDocument(m,y?{bareOverview:!0}:void 0))}if(l.kind==="resource"){let a=ce(n,l.package_,l.versionSpec);if(!a)return P(e);let m=n.bySubject.get(`${o}/${l.package_}@${a}/${l.name}`);if(!m)return P(e);switch(i){case".css":return R(200,S[".css"],r.renderStylesheet(m));case".svg":return R(200,S[".svg"],await r.renderSvg(m));case".md":{let y=r.renderRawMarkdown(m);return y===void 0?P(e):R(200,S[".md"],y)}default:return R(200,S[".html"],await r.renderDocument(m))}}return P(e)}import{readFileSync as xe}from"fs";var Y=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,t=new Set;if(this.options.root!==void 0){let r=new D;for(let o of N(this.options.root))try{let i=r.parse(xe(o,"utf-8")).metadata?.namespace_;if(!i?.version)continue;let d=i.version;e.add(`${i.publisher}/${i.package_}@${d.major}.${d.minor}.${d.patch}`),t.add(`${i.publisher}/${i.package_}`)}catch{}}return this.workspaceIndex={exact:e,pkgs:t},this.workspaceIndex}async modelFor(e,t,r){let o=this.getWorkspaceIndex(),i=this.options.fetchFn?{fetchFn:this.options.fetchFn}:{},d=t?r?o.exact.has(`${e}/${t}@${r}`):o.pkgs.has(`${e}/${t}`):[...o.pkgs].some(a=>a.startsWith(`${e}/`)),c,f;if(d&&this.options.root!==void 0){let a=this.options.root;c=`ws:${e}`,f=()=>T(a,{publisher:e})}else{let a=t?r?`${e}/${t}@${r}`:`${e}/${t}`:e;c=`rm:${a}`,f=()=>U(a,i)}let g=this.models.get(c);if(g)return g;let l=await f();return l.lookRenderer.setLinkMode("open-world"),this.models.set(c,l),l}async handle(e,t=""){let r=e.split("/").filter(Boolean);if(r.length===0)return{status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:pe()};let o=r[0];if(!o.includes("."))return{status:404,headers:{"Content-Type":"text/html; charset=utf-8"},body:"<!doctype html><meta charset=utf-8><title>404</title><h1>404</h1><p>Expected a publisher domain as the first path segment: <code>/{publisher}/{package}/{version}/{resource}</code></p>"};let i=r.length>=2&&(r[1]==="index.html"||r[1]==="index.css"||r[1]==="index.txt"||r[1]===".well-known"),d=!i&&r.length>=2?r[1]:void 0,c=!i&&r.length>=3&&/^\d+\.\d+\.\d+$/.test(r[2])?r[2]:void 0,f=await this.modelFor(o,d,c),g=e.endsWith("/")&&r.length>1?"/":"",l="/"+r.slice(1).join("/")+g,a=await G(f,l,t);return a.headers.Location?{...a,headers:{...a.headers,Location:`/${o}${a.headers.Location}`}}:a}};function pe(){return'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kanonak origin</title></head><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>Kanonak request-driven origin</h1><p>Open a resource by its address:</p><p><code>/{publisher}/{package}/{version}/{resource}</code></p><p>e.g. <code>/kanonak.org/capabilities/2.0.0/Capability</code></p></body></html>'}export{j as ClosureScopedRepository,Y as RequestRouter,ae as UNIVERSAL_RENDER_BASE,M as deriveImportClosure,pe as landingPage,U as loadResourceModel,T as loadServerModel,H as renderRefKey,C as resolveRenderContract,G as route};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-
|
|
1
|
+
import{b as Y,c as An,d as Sn,e as ce,f as Te,g as O,h as wn,i as X,j as q}from"../chunk-BH5TB6XY.js";import{a as se}from"../chunk-G7XXA2JL.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-UV6CLM2Y.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{i as ie}from"../chunk-7GAOBCNZ.js";import{a as ae}from"../chunk-EP7CJSV2.js";import{b as L,c as A,f as S}from"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import{b as N,c as D,d as K,g as M,h as P,i as F,j as W,l as H}from"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import{g as oe}from"../chunk-2ACBWC7K.js";var $e="kanonak.org",Ue="document-ast",i=e=>({publisher:$e,package_:Ue,name:e}),m={Document:i("Document"),Block:i("Block"),Inline:i("Inline"),StructuredValue:i("StructuredValue"),Heading:i("Heading"),Paragraph:i("Paragraph"),RawBlock:i("RawBlock"),Text:i("Text"),StructuredMap:i("StructuredMap"),StructuredEntry:i("StructuredEntry"),StructuredList:i("StructuredList"),StringScalar:i("StringScalar"),IntegerScalar:i("IntegerScalar"),EscapeHint:i("EscapeHint"),MediaType:i("MediaType"),metadata:i("metadata"),children:i("children"),level:i("level"),inlines:i("inlines"),text:i("text"),entries:i("entries"),key:i("key"),value:i("value"),escapeHint:i("escapeHint"),items:i("items"),stringValue:i("stringValue"),integerValue:i("integerValue"),rawContent:i("rawContent"),mediaType:i("mediaType"),mimeType:i("mimeType"),ESC_RAW:i("esc-raw"),ESC_YAML_SAFE:i("esc-yaml-safe"),ESC_TOML_STRING:i("esc-toml-string"),ESC_TOML_MULTILINE:i("esc-toml-multiline"),ESC_JSON:i("esc-json"),ESC_DYNAMODB_BOOL:i("esc-dynamodb-bool"),ESC_DYNAMODB_NUMBER:i("esc-dynamodb-number"),ESC_DYNAMODB_NULL:i("esc-dynamodb-null"),TEXT_PLAIN:i("text-plain"),TEXT_MARKDOWN:i("text-markdown"),TEXT_HTML:i("text-html"),TEXT_CSS:i("text-css"),APPLICATION_JSON:i("application-json"),TEXT_YAML:i("text-yaml"),IMAGE_SVG_XML:i("image-svg-xml"),ResourceLink:i("ResourceLink"),target:i("target"),linkLabel:i("linkLabel"),PropertyList:i("PropertyList"),propertyEntries:i("propertyEntries"),PropertyEntry:i("PropertyEntry"),propertyKey:i("propertyKey"),propertyValue:i("propertyValue"),Table:i("Table"),tableColumnLabels:i("tableColumnLabels"),tableRows:i("tableRows"),TableRow:i("TableRow"),tableCells:i("tableCells")};function ue(e,n){return e.publisher===n.publisher&&e.package_===n.package_&&e.name===n.name}var j=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(n,t){let r=xe(n.metadata,t),o=Le(n.children),s=["---",...r,"---","",o].join(`
|
|
2
2
|
`);return t?.trailingNewline&&(s.endsWith(`
|
|
3
3
|
`)||(s+=`
|
|
4
4
|
`)),s}};function xe(e,n){if(!e)return[];let t=new Map;for(let c of e.entries)t.set(I(c.key),c);let r=new Map;if(n?.metadataRenames)for(let[c,u]of n.metadataRenames)r.set(I(c),u);let a=(n?.metadataKeys??e.entries.map(c=>c.key)).map(I),s=[];for(let c of a){let u=t.get(c);if(!u)continue;let f=r.get(c),l=I(f??c),d=me(u.value,u.escapeHint);d!==void 0&&s.push(`${l}: ${d}`)}return s}function I(e){let n=e.lastIndexOf(".");return n===-1?e:e.substring(n+1)||e}function me(e,n){switch(e.kind){case"StringScalar":return Ve(e.stringValue,n);case"IntegerScalar":return String(e.integerValue);case"StructuredList":{let t=[];for(let r of e.items){let o=me(r,n);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function Ve(e,n){return!n||ue(n,m.ESC_RAW)?e:ue(n,m.ESC_YAML_SAFE)?ve(e):e}function ve(e){return e.includes(`
|
package/dist/validation/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,C,D,E,F,G,H,I,L as J,M as K,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-
|
|
1
|
+
import{A,B,C,D,E,F,G,H,I,L as J,M as K,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"../chunk-KARUKDEM.js";import"../chunk-SHDHMKMJ.js";import"../chunk-7GAOBCNZ.js";import"../chunk-EP7CJSV2.js";import"../chunk-UK2OIPAB.js";import"../chunk-PBNVHBS3.js";import"../chunk-VKTFLHCW.js";import"../chunk-T3JR2SV6.js";import"../chunk-FUUTGGJS.js";import"../chunk-2ACBWC7K.js";export{w as AmbiguousReferenceRule,C as ClassDefinitionRule,n as ClassHierarchyCycleRule,u as DefinitionPropertyReferenceRule,J as DiamondNameClashRule,E as DisplayLensScopeRule,k as EmbeddedKanonakTypeRule,l as ImportExistenceRule,t as InstancePropertyReferenceRule,K as KanonakObjectValidator,F as LookSemanticSvgPathRule,D as MarkdownLinkRule,s as NamespaceImportCycleRule,f as NamespacePrefixRule,y as ObjectPropertyImportRule,z as ObjectPropertyValueValidationRule,c as OntologyValidationError,a as OntologyValidationResult,I as OwlOneOfRule,j as PackageHeaderRule,A as PropertyDomainRule,o as PropertyHierarchyCycleRule,x as PropertyRangeReferenceRule,p as PropertyRangeRequiredRule,h as PropertyTypeSpecificityRule,B as PropertyValueTypeRule,g as ResourceNamingRule,H as ShaclShapeRule,q as SubClassOfReferenceRule,r as SubPropertyOfReferenceRule,i as SubjectKanonakTypeRequiredRule,G as TxExpressionPathRule,m as UnresolvedReferenceRule,e as ValidationCache,d as ValidationContext,b as ValidationSeverity,v as XsdImportRule};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/sdk",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.5.0",
|
|
4
4
|
"description": "TypeScript SDK for the Kanonak Protocol — parse, resolve, validate, reason over, and render .kan.yml packages.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -125,7 +125,7 @@
|
|
|
125
125
|
"yaml-parser"
|
|
126
126
|
],
|
|
127
127
|
"dependencies": {
|
|
128
|
-
"@kanonak-protocol/types": "^4.
|
|
128
|
+
"@kanonak-protocol/types": "^4.5.0",
|
|
129
129
|
"ignore": "^7.0.5",
|
|
130
130
|
"js-yaml": "^4.1.0",
|
|
131
131
|
"yaml": "^2.7.0"
|
package/dist/chunk-ZYAABYDS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as k,b as f}from"./chunk-2ACBWC7K.js";import*as h from"js-yaml";var b=new Set(["Package","EphemeralPackage"]);function v(d){return typeof d=="string"&&b.has(d)}var $=class{parse(r){let t=this.parseWithErrors(r);if(!t.isValid){let a=t.errors[0];throw new Error(`YAML parse error at line ${a.line}, column ${a.column}: ${a.message}`)}return t.document}parseWithErrors(r){let t=[],a;try{r=r.replace(/^\uFEFF/,"");let s=h.load(r,{schema:h.FAILSAFE_SCHEMA});if(!s||typeof s!="object")return a={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:a,errors:t,isValid:!0};let e=this.extractMetadata(s),n=this.extractBody(s,e);return a={metadata:e,body:n,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:a,errors:t,isValid:!0}}catch(s){let e=s,n={message:e.message||"Unknown parse error",line:e.mark?.line??0,column:e.mark?.column??0,errorType:e.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${e.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${e.mark?.line??0}: ${e.message||"Unknown parse error"}`};return t.push(n),{document:void 0,errors:t,isValid:!1}}}save(r){let t={};if(r.metadata.namespace_){let a=r.metadata.namespace_,s={type:"Package",publisher:a.publisher};a.version&&(s.version=`${a.version.major}.${a.version.minor}.${a.version.patch}`),r.metadata.imports&&(s.imports=this.serializeImports(r.metadata.imports)),t[a.package_]=s}return Object.assign(t,r.body),h.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(r){let t=r.imports;return Object.defineProperty(r,"allImports",{get:function(){if(!t)return[];let a=[];for(let s of Object.values(t))a.push(...s);return a},enumerable:!0,configurable:!0}),r}createVersion(r,t,a){return{major:r,minor:t,patch:a,toString:()=>`${r}.${t}.${a}`,equals:e=>!e||typeof e!="object"?!1:e.major===r&&e.minor===t&&e.patch===a,getHashCode:()=>r<<20|t<<10|a,compareTo:e=>r!==e.major?r-e.major:t!==e.minor?t-e.minor:a-e.patch}}extractMetadata(r){let t=this.createEmptyMetadata();for(let[a,s]of Object.entries(r))if(s&&typeof s=="object"&&v(s.type)){t.type_=s.type;let e=a,n=s.publisher,i=s.version?this.parseVersion(s.version):void 0;return n&&e&&(t.namespace_={publisher:n,package_:e,version:i,toString:function(){return this.version?`${this.publisher}/${this.package_}@${this.version.major}.${this.version.minor}.${this.version.patch}`:`${this.publisher}/${this.package_}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===n&&o.package_===e&&(!i||!o.version||i.equals(o.version)),getHashCode:()=>{let o=0;for(let c=0;c<n.length;c++)o=(o<<5)-o+n.charCodeAt(c);for(let c=0;c<e.length;c++)o=(o<<5)-o+e.charCodeAt(c);return o|0}}),s.imports&&Array.isArray(s.imports)&&(t.imports=this.parseImportsV3(s.imports)),this.addAllImportsGetter(t)}if(r.kanonak&&typeof r.kanonak=="object"){let a=r.kanonak;return(a.publisher||a.package||a.version)&&(t.namespace_=this.parseNamespace(a)),a.imports&&typeof a.imports=="object"&&(t.imports=this.parseImportsLegacy(a.imports)),this.addAllImportsGetter(t)}return t}extractBody(r,t){let a={};for(let[s,e]of Object.entries(r))if(!(s==="kanonak"||s==="namespace"||s==="imports"))if(e&&typeof e=="object"&&v(e.type)){let n={};for(let[i,o]of Object.entries(e))i==="publisher"||i==="version"||i==="imports"||(n[i]=o);a[s]=n}else a[s]=e;return a}parseNamespace(r){if(typeof r=="string"){let e=r.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(e){let n=e[3]?this.parseVersion(e[3]):this.createVersion(1,0,0);return{publisher:e[1],package_:e[2],version:n,toString:()=>r,equals:i=>!i||typeof i!="object"?!1:i.publisher===e[1]&&i.package_===e[2]&&(!n||!i.version||n.equals(i.version)),getHashCode:()=>{let i=0;for(let o=0;o<e[1].length;o++)i=(i<<5)-i+e[1].charCodeAt(o);for(let o=0;o<e[2].length;o++)i=(i<<5)-i+e[2].charCodeAt(o);return i|0}}}}let t=r.publisher||"",a=r.package||"",s=r.version?this.parseVersion(r.version):this.createVersion(1,0,0);return{publisher:t,package_:a,version:s,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:e=>!e||typeof e!="object"?!1:e.publisher===t&&e.package_===a&&(!s||!e.version||s.equals(e.version)),getHashCode:()=>{let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n);for(let n=0;n<a.length;n++)e=(e<<5)-e+a.charCodeAt(n);return e|0}}}parseVersion(r){if(typeof r=="string"){let t=r.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(r.major||0,r.minor||0,r.patch||0)}parseImportsV3(r){let t={};for(let a of r)if(!(!a||typeof a!="object"))if(a.packages&&Array.isArray(a.packages)){let s=a.publisher;if(!s)throw new Error("PublisherImport requires 'publisher' property");t[s]||(t[s]=[]);for(let e of a.packages){if(!e||typeof e!="object")continue;let n=this.parseImportFromEmbeddedObject(e,s);t[s].push(n)}}else{let s=this.parseImportFromEmbeddedObject(a,a.publisher),e=s.publisher||"";t[e]||(t[e]=[]),t[e].push(s)}return t}parseImportsLegacy(r){let t={};for(let[a,s]of Object.entries(r))Array.isArray(s)&&(t[a]=s.map(e=>this.parseImport(e,a)));return t}parseImportFromEmbeddedObject(r,t){let a=r.package;if(!a)throw new Error("Import requires 'package' property");let s=r.match;if(!s)throw new Error("Import requires 'match' property");let e=r.version;if(!e)throw new Error("Import requires 'version' property");let n=this.parseVersion(e),i=this.parseVersionOperator(s),o=this.calculateMaxVersion(s,n),c=r.alias;return{package_:`${a} ${s} ${n.toString()}`,publisher:t,packageName:a,versionOperator:i,version:n,alias:c,minVersion:n,maxVersion:o,toEmbeddedObject:()=>{let m={package:a,match:s,version:n.toString()};return c&&(m.alias=c),m},toString:()=>c?`${a} ${s} ${n.toString()} as ${c}`:`${a} ${s} ${n.toString()}`}}buildImport(r,t,a,s){return this.parseImport({packageName:r,operator:t,version:a},s)}parseImport(r,t){if(typeof r=="string"){let o=r.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(o){let m=o[1].trim(),u=o[2],p=this.parseVersion(o[3].trim()),l=o[4].trim(),g=this.parseVersionOperator(u),V=this.calculateMaxVersion(u,p);return{package_:r,publisher:t,packageName:m,versionOperator:g,version:p,alias:l,minVersion:p,maxVersion:V,toEmbeddedObject:()=>{let y={package:m,match:u,version:p.toString()};return l&&(y.alias=l),y},toString:()=>`${m} ${u} ${p.toString()} as ${l}`}}let c=r.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let m=c[1].trim(),u=c[2],p=this.parseVersion(c[3].trim()),l=this.parseVersionOperator(u),g=this.calculateMaxVersion(u,p);return{package_:r,publisher:t,packageName:m,versionOperator:l,version:p,alias:void 0,minVersion:p,maxVersion:g,toEmbeddedObject:()=>({package:m,match:u,version:p.toString()}),toString:()=>`${m} ${u} ${p.toString()}`}}}let a=this.parseVersionOperator(r.operator||"~"),s=this.parseVersion(r.version||"1.0.0"),e=r.packageName||r.package||"",n=f(a),i=this.calculateMaxVersion(r.operator||"~",s);return{package_:r.package||"",publisher:t,packageName:e,versionOperator:a,version:s,alias:r.alias,minVersion:s,maxVersion:i,toEmbeddedObject:()=>{let o={package:e,match:n,version:s.toString()};return r.alias&&(o.alias=r.alias),o},toString:()=>`${e} ${n} ${s.toString()}`}}parseVersionOperator(r){return k(r)}calculateMaxVersion(r,t){switch(r){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(r){let t=[];for(let[a,s]of Object.entries(r)){let e={publisher:a,packages:s.map(n=>{let i=f(n.versionOperator),o={package:n.packageName,match:i,version:`${n.version.major}.${n.version.minor}.${n.version.patch}`};return n.alias&&(o.alias=n.alias),o})};t.push(e)}return t}};export{$ as a};
|