@kanonak-protocol/sdk 4.11.0 → 4.12.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/canonical/CanonicalHash.d.ts +13 -17
- package/dist/canonical/Datatypes.d.ts +19 -93
- package/dist/canonical/InputModel.d.ts +9 -46
- package/dist/chunk-BKVPSPG4.js +1 -0
- package/dist/{chunk-QIMJSVIM.js → chunk-CR55WXIN.js} +1 -1
- package/dist/{chunk-MMJ7GO7J.js → chunk-RGOBWOBB.js} +1 -1
- package/dist/{chunk-WED776KZ.js → chunk-U7LVFPEO.js} +1 -1
- package/dist/{chunk-55DXTCGV.js → chunk-UBBZWWRB.js} +1 -1
- package/dist/{chunk-E2FCKRB4.js → chunk-V72IVYR4.js} +1 -1
- package/dist/{chunk-47RLRYV2.js → chunk-VWS25JH4.js} +1 -1
- package/dist/index.js +26 -26
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/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 +3 -2
- package/dist/chunk-MFNVQSBW.js +0 -1
package/dist/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as we,b as ke,c as he,d as E,e as _,f as d,g as tr}from"./chunk-
|
|
1
|
+
import{a as we,b as ke,c as he,d as E,e as _,f as d,g as tr}from"./chunk-U7LVFPEO.js";import{a as rr}from"./chunk-VWS25JH4.js";import"./chunk-QHABFCRC.js";import{a as F,b as W,c as G,d as w,f as X,g as Q,h as Y}from"./chunk-JYBKSBB5.js";import{a as q}from"./chunk-4NO7MHS7.js";import{a as Ke,b as be,c as xe}from"./chunk-RGOBWOBB.js";import{a as Se,b as Re}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as Xe,B as Qe,C as Ye,D as Ze,M as er,a as De,b as Be,c as Ce,d as Ee,f as _e,g as je,h as ve,i as Ae,k as Te,l as Ie,m as Oe,n as Ue,o as Ve,p as $e,q as Me,r as Ne,s as ze,t as Je,u as He,v as qe,w as Le,x as Fe,y as We,z as Ge}from"./chunk-UBBZWWRB.js";import"./chunk-SHDHMKMJ.js";import{a as te,c as ye,h as me}from"./chunk-BKVPSPG4.js";import{a as L}from"./chunk-NJ3AZYQD.js";import{a as Pe}from"./chunk-IEOSSSB5.js";import"./chunk-7TKJHKC2.js";import{b as ge,c as fe}from"./chunk-7HRKWTBB.js";import{a as Z,b as ee,c as re,d as oe,e as se,f as ie,g as ae,h as ce,i as le,j as ue,k as de,l as pe}from"./chunk-4UT2CLAT.js";import{a as ne}from"./chunk-FUUTGGJS.js";import{c as U,d as V,e as $,f as M,g as N,h as z,i as J,j as H}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",nr=1,f=class{async get(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readonly"),i=s.objectStore(u).get(e);i.onsuccess=()=>o(i.result??null),i.onerror=()=>a(new Error(`IndexedDB read failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async store(r,e){let t=d(r),o=await h();return new Promise((a,s)=>{let l=o.transaction(u,"readwrite"),c=l.objectStore(u).put(e,t);c.onsuccess=()=>a(),c.onerror=()=>s(new Error(`IndexedDB write failed for '${t}': ${c.error?.message}`)),l.oncomplete=()=>o.close()})}async remove(r){let e=d(r),t=await h();return new Promise((o,a)=>{let s=t.transaction(u,"readwrite"),i=s.objectStore(u).delete(e);i.onsuccess=()=>o(),i.onerror=()=>a(new Error(`IndexedDB delete failed for '${e}': ${i.error?.message}`)),s.oncomplete=()=>t.close()})}async list(){let r=await h();return new Promise((e,t)=>{let o=r.transaction(u,"readonly"),s=o.objectStore(u).getAllKeys();s.onsuccess=()=>e(s.result??[]),s.onerror=()=>t(new Error(`IndexedDB list failed: ${s.error?.message}`)),o.oncomplete=()=>r.close()})}};function h(){return new Promise((n,r)=>{let e=indexedDB.open(j,nr);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 A(){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 x(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 sr(t)),o&&(s.nonce=o),await or(a,s,n.signingKey)}function S(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function or(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=B(s);return`${t}.${o}.${l}`}async function sr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function v(n){let r=new TextEncoder().encode(n);return B(r.buffer)}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(/=+$/,"")}var ir=300*1e3,R=class{credentialBackend;callbackUrl;constructor(r){this.credentialBackend=new f,this.callbackUrl=r??`${window.location.origin}/browser/callback.html`}async authorize(r){let e=d(r),t=await this.discover(e);if(!t)return{success:!1,error:`No OAuth discovery endpoint found for '${e}'.`};if(!t.authorizationEndpoint||!t.tokenEndpoint)return{success:!1,error:`OAuth metadata incomplete for '${e}'.`};let o=S(t.dpopSigningAlgValuesSupported),a=null,s=null;if(o){let g=await K();a=g.keys,s=g.dpopKeyPair}let l=await this.credentialBackend.get(e),i=l?.clientId??null,c=l?.clientSecret??null;if(!i&&t.registrationEndpoint){let g=await this.registerClient(t.registrationEndpoint);if(!g)return{success:!1,error:`Dynamic client registration failed for '${e}'.`};i=g.clientId,c=g.clientSecret??null}if(!i)return{success:!1,error:`No OAuth client credentials for '${e}'.`};let m=ar(),p=await cr(m),D=lr(),I=ur(t.authorizationEndpoint,i,this.callbackUrl,D,p),y=await this.openAuthPopup(I,D);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!==D)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 O={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,O),{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 w(e);if(!t.ok)continue;let o=await t.json();return{issuer:k(o.issuer),authorizationEndpoint:k(o.authorization_endpoint),tokenEndpoint:k(o.token_endpoint),registrationEndpoint:k(o.registration_endpoint),revocationEndpoint:k(o.revocation_endpoint),dpopSigningAlgValuesSupported:T(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:T(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await w(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)},ir),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 x(l,"POST",r));try{let m=await w(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 ar(){let n=new Uint8Array(32);return crypto.getRandomValues(n),C(n.buffer)}async function cr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return C(e)}function lr(){let n=new Uint8Array(16);return crypto.getRandomValues(n),C(n.buffer)}function ur(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 C(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 k(n){return typeof n=="string"?n:null}function T(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Le as AmbiguousReferenceRule,le as BooleanStatement,f as BrowserCredentialBackend,R as BrowserOAuthFlow,Ye as ClassDefinitionRule,Ue as ClassHierarchyCycleRule,ee as DefinedKanonak,He as DefinitionPropertyReferenceRule,ke as EdgeType,te as EmbeddedKanonak,Te as EmbeddedKanonakTypeRule,de as EmbeddedStatement,he as GraphBuilder,Y as HttpKanonakDocumentRepository,Ie as ImportExistenceRule,q as InMemoryKanonakDocumentRepository,F as KANONAK_USER_AGENT,Z as Kanonak,be as KanonakDocumentPositions,me as KanonakObjectParser,er as KanonakObjectValidator,L as KanonakParser,ne as KanonakUri,Se as KanonakUriBuilder,pe as ListStatement,Ze as MarkdownLinkRule,ye as MarkdownStatement,ze as NamespaceImportCycleRule,_e as NamespacePrefixRule,we as NodeType,ce as NumberStatement,We as ObjectPropertyImportRule,Ge as ObjectPropertyValueValidationRule,Ce as OntologyValidationError,De as OntologyValidationResult,Xe as PropertyDomainRule,Ve as PropertyHierarchyCycleRule,Ke as PropertyMetadata,Fe as PropertyRangeReferenceRule,$e as PropertyRangeRequiredRule,ve as PropertyTypeSpecificityRule,Qe as PropertyValueTypeRule,X as PublisherConfigResolver,Q as PublisherIndex,oe as ReferenceKanonak,ue as ReferenceStatement,je as ResourceNamingRule,ge as ResourceResolver,Pe as ResourceTypeClassifier,ie as ScalarStatement,se as Statement,ae as StringStatement,Me as SubClassOfReferenceRule,Ne as SubPropertyOfReferenceRule,re as SubjectKanonak,Ae as SubjectKanonakTypeRequiredRule,fe as TypeResolver,Je as UnresolvedPredicateRule,Oe as UnresolvedReferenceRule,Ee as ValidationContext,Be as ValidationSeverity,qe as XsdImportRule,S as browserServerSupportsDPoP,tr as buildOntologyModel,U as compareVersions,x as createBrowserDPoPProof,M as createVersion,rr as findDerivation,Re as findInstancesByType,$ as formatVersion,K as generateBrowserDPoPKeyPair,A as generateBrowserDPoPKeys,G as getKanonakUserAgent,_ as hasValidToken,b as importDPoPKeys,z as isCompatibleVersion,E as isExpired,J as isMajorCompatible,w as kanonakFetch,d as normalizeHost,N as parseVersionString,xe as parseWithPositions,H as pickHighestDocument,W as setKanonakUserAgent,V as versionsEqual};
|
|
@@ -1,24 +1,20 @@
|
|
|
1
1
|
import { type Kanonak } from '../kanonaks/index.js';
|
|
2
2
|
import { type CanonicalInput } from './InputModel.js';
|
|
3
3
|
/**
|
|
4
|
-
* The frozen canonical-form version
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* and lets a consumer record which form produced an address.
|
|
4
|
+
* The frozen canonical-form version, re-exported from the library so the SDK
|
|
5
|
+
* surface is unchanged. It is NOT part of the hashed bytes; it stamps the
|
|
6
|
+
* golden-vector fixtures and lets a consumer record which form produced an
|
|
7
|
+
* address.
|
|
9
8
|
*/
|
|
10
|
-
export
|
|
9
|
+
export { CANONICAL_FORM_VERSION } from '@kanonak-protocol/canonical';
|
|
11
10
|
/**
|
|
12
11
|
* Render a parsed kanonak collection into its canonical JSON form.
|
|
13
12
|
*
|
|
14
|
-
* `kanonaks` should be the `SubjectKanonak` instances from a single
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* Returns the JSON string (no trailing newline). Identical inputs
|
|
21
|
-
* always produce byte-identical output.
|
|
13
|
+
* `kanonaks` should be the `SubjectKanonak` instances from a single package —
|
|
14
|
+
* typically the result of `KanonakObjectParser.parseKanonaks` over a
|
|
15
|
+
* `SingleDocumentRepository`. Embedded, reference, and literal kanonaks are
|
|
16
|
+
* walked through subjects' statement trees; they don't count as top-level
|
|
17
|
+
* subjects. Identical inputs always produce byte-identical output.
|
|
22
18
|
*/
|
|
23
19
|
export declare function canonicalForm(kanonaks: Kanonak[]): string;
|
|
24
20
|
/**
|
|
@@ -28,9 +24,9 @@ export declare function canonicalForm(kanonaks: Kanonak[]): string;
|
|
|
28
24
|
*/
|
|
29
25
|
export declare function canonicalForm(input: CanonicalInput): string;
|
|
30
26
|
/**
|
|
31
|
-
* SHA-256 of the canonical form, prefixed `sha256:`. The output is
|
|
32
|
-
*
|
|
33
|
-
*
|
|
27
|
+
* SHA-256 of the canonical form, prefixed `sha256:`. The output is 71 characters
|
|
28
|
+
* (`sha256:` + 64 hex digits) and matches the convention used by `kanonak.lock`
|
|
29
|
+
* integrity entries.
|
|
34
30
|
*/
|
|
35
31
|
export declare function canonicalHash(kanonaks: Kanonak[]): string;
|
|
36
32
|
/** SHA-256 of the canonical form of a {@link CanonicalInput} model (issue #56). */
|
|
@@ -1,98 +1,24 @@
|
|
|
1
|
-
import type { EntityUri } from '../uri-helpers/index.js';
|
|
2
1
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* SDK adapter over `@kanonak-protocol/canonical`'s datatype layer.
|
|
3
|
+
*
|
|
4
|
+
* The frozen carrier routing and the per-carrier canonical lexical forms — the
|
|
5
|
+
* normative heart of `canonicalFormVersion "1"` — now live in exactly one place,
|
|
6
|
+
* the published `@kanonak-protocol/canonical` library, verified byte-for-byte
|
|
7
|
+
* against the shared golden vectors. This module no longer carries a copy; it
|
|
8
|
+
* only re-exposes `Carrier` on the SDK surface and adds the SDK-shaped
|
|
9
|
+
* `carrierOf` that classifies a datatype given as an {@link EntityUri} object
|
|
10
|
+
* (the form the parser and resolver carry) by delegating to the library's
|
|
11
|
+
* string-keyed `carrierOf`.
|
|
6
12
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
Double = "double",
|
|
11
|
-
Float = "float",
|
|
12
|
-
Boolean = "boolean",
|
|
13
|
-
String = "string",
|
|
14
|
-
AnyUri = "anyURI",
|
|
15
|
-
LangString = "langString",
|
|
16
|
-
DateTime = "dateTime",
|
|
17
|
-
Date = "date",
|
|
18
|
-
Time = "time",
|
|
19
|
-
HexBinary = "hexBinary",
|
|
20
|
-
Base64Binary = "base64Binary"
|
|
21
|
-
}
|
|
13
|
+
import type { EntityUri } from '../uri-helpers/index.js';
|
|
14
|
+
import { Carrier } from '@kanonak-protocol/canonical';
|
|
15
|
+
export { Carrier };
|
|
22
16
|
/**
|
|
23
|
-
* The carrier for a datatype, or `undefined`
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* carrier.
|
|
17
|
+
* The carrier for a datatype identified by an {@link EntityUri}, or `undefined`
|
|
18
|
+
* if it is outside the canonicalized set. Builds the `publisher/package/name`
|
|
19
|
+
* key the library classifies on — a datatype's version never affects its
|
|
20
|
+
* carrier identity, so it is omitted. The routing itself (the whole integer
|
|
21
|
+
* tree → {@link Carrier.Integer}, `normalizedString`/`token` → {@link
|
|
22
|
+
* Carrier.String}, etc.) is the library's frozen contract.
|
|
27
23
|
*/
|
|
28
24
|
export declare function carrierOf(datatype: EntityUri): Carrier | undefined;
|
|
29
|
-
/**
|
|
30
|
-
* Canonical `xsd:integer` (and every derived integer): optional `-`, digits
|
|
31
|
-
* with no leading zeros, `0` for zero, never `-0`, never a leading `+`.
|
|
32
|
-
* Backed by `BigInt` so values beyond 2^53 (e.g. epoch-nanoseconds) are exact.
|
|
33
|
-
*/
|
|
34
|
-
export declare function canonicalInteger(raw: string): string;
|
|
35
|
-
/**
|
|
36
|
-
* Canonical `xsd:decimal`: value-based minimal form. Optional `-`, integer part
|
|
37
|
-
* with no leading zeros (`0` if zero), then `.`+fraction only when the fraction
|
|
38
|
-
* is non-zero, with no trailing zeros. `1.10 → 1.1`, `1.00 → 1`, `0.10 → 0.1`,
|
|
39
|
-
* `-0 → 0`, `-0.00 → 0`. Pure string arithmetic — never parsed to a double.
|
|
40
|
-
*/
|
|
41
|
-
export declare function canonicalDecimal(raw: string): string;
|
|
42
|
-
/** Canonical `xsd:double` — shortest round-tripping decimal; INF / -INF / NaN. */
|
|
43
|
-
export declare function canonicalDouble(raw: string): string;
|
|
44
|
-
/**
|
|
45
|
-
* Canonical `xsd:float` — like {@link canonicalDouble} but the value is first
|
|
46
|
-
* rounded to IEEE single precision (`Math.fround`). NOTE: exact cross-language
|
|
47
|
-
* agreement on shortest-float32 strings is a known sharp edge to lock against
|
|
48
|
-
* the golden vectors; representative values agree.
|
|
49
|
-
*/
|
|
50
|
-
export declare function canonicalFloat(raw: string): string;
|
|
51
|
-
/** Canonical `xsd:boolean`: `true` / `false`. Accepts the `1`/`0` lexicals. */
|
|
52
|
-
export declare function canonicalBoolean(raw: string): string;
|
|
53
|
-
/** Canonical string value: Unicode NFC. No whitespace collapse (that's a facet). */
|
|
54
|
-
export declare function canonicalString(raw: string): string;
|
|
55
|
-
/** Canonical `xsd:anyURI`: NFC (distinct carrier/tag from string, same lexical rule). */
|
|
56
|
-
export declare function canonicalAnyUri(raw: string): string;
|
|
57
|
-
/**
|
|
58
|
-
* Canonical `rdf:langString`: NFC value + BCP 47 canonical-CASE language tag
|
|
59
|
-
* (language lowercase, script titlecase, region uppercase) — `"hi"@EN-us`
|
|
60
|
-
* becomes `("hi", "en-US")`. Case only; no IANA registry / preferred-value
|
|
61
|
-
* substitution. Returns the pair; the canonical form serializes both.
|
|
62
|
-
*/
|
|
63
|
-
export declare function canonicalLangString(value: string, lang: string): {
|
|
64
|
-
value: string;
|
|
65
|
-
lang: string;
|
|
66
|
-
};
|
|
67
|
-
/** BCP 47 canonical case by subtag position. */
|
|
68
|
-
export declare function canonicalLanguageTag(tag: string): string;
|
|
69
|
-
/** Canonical `xsd:hexBinary`: uppercase hex digits, even length. */
|
|
70
|
-
export declare function canonicalHexBinary(raw: string): string;
|
|
71
|
-
/**
|
|
72
|
-
* Canonical `xsd:base64Binary`: RFC 4648 standard alphabet, canonical padding,
|
|
73
|
-
* no line breaks. Decodes (tolerating XSD-permitted internal whitespace) then
|
|
74
|
-
* re-encodes, so any padding/line-wrap variant of the same bytes collapses.
|
|
75
|
-
*/
|
|
76
|
-
export declare function canonicalBase64(raw: string): string;
|
|
77
|
-
/**
|
|
78
|
-
* Canonical `xsd:dateTime`. Offset-bearing → shifted to UTC `Z` (instant
|
|
79
|
-
* equality, so `13:00:00+01:00` and `12:00:00Z` collide). Timezone-less →
|
|
80
|
-
* floating: canonical lexical form, no `Z`, distinct from any zoned instant.
|
|
81
|
-
* Fractional seconds are preserved at arbitrary precision (only trailing zeros
|
|
82
|
-
* trimmed) and never participate in the offset shift.
|
|
83
|
-
*/
|
|
84
|
-
export declare function canonicalDateTime(raw: string): string;
|
|
85
|
-
/**
|
|
86
|
-
* Canonical `xsd:date`: lexical only — canonical year width + canonical
|
|
87
|
-
* timezone spelling, NO UTC shift (a date is not an instant; shifting could
|
|
88
|
-
* cross midnight). Timezone-less stays distinct from a zoned date.
|
|
89
|
-
*/
|
|
90
|
-
export declare function canonicalDate(raw: string): string;
|
|
91
|
-
/**
|
|
92
|
-
* Canonical `xsd:time`: lexical only — arbitrary-precision fractional seconds,
|
|
93
|
-
* canonical timezone spelling, NO UTC shift. `24:00:00` normalizes to
|
|
94
|
-
* `00:00:00` (XSD value-space equivalence within a day).
|
|
95
|
-
*/
|
|
96
|
-
export declare function canonicalTime(raw: string): string;
|
|
97
|
-
/** Canonical lexical form of a raw token under a carrier. Throws on malformed input. */
|
|
98
|
-
export declare function canonicalScalarLexical(carrier: Carrier, raw: string): string;
|
|
@@ -1,54 +1,17 @@
|
|
|
1
|
-
import type { Kanonak } from '../kanonaks/Kanonak.js';
|
|
2
1
|
/**
|
|
3
2
|
* The language-neutral canonical INPUT model (issue #56) — the one
|
|
4
3
|
* cross-language contract a codec builds to content-address a typed object,
|
|
5
4
|
* carrying datatypes explicitly so canonicalization needs no parser. It is
|
|
6
5
|
* exactly the shape `full-form-vectors.json` is defined over and `kanonak hash
|
|
7
|
-
* -v` emits.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
6
|
+
* -v` emits.
|
|
7
|
+
*
|
|
8
|
+
* The types are re-exported from `@kanonak-protocol/canonical`, the single home
|
|
9
|
+
* of the frozen canonical form, so the SDK surface is unchanged for existing
|
|
10
|
+
* consumers while the definition lives in exactly one place. The SDK keeps the
|
|
11
|
+
* {@link isCanonicalInput} discriminator the public `canonicalForm` /
|
|
12
|
+
* `canonicalHash` overloads use to tell a `CanonicalInput` from a `Kanonak[]`.
|
|
10
13
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
export interface CanonicalInputSubject {
|
|
15
|
-
/** The subject's canonical URI, e.g. `publisher/package@1.0.0/Name`. */
|
|
16
|
-
uri: string;
|
|
17
|
-
statements: CanonicalInputStatement[];
|
|
18
|
-
}
|
|
19
|
-
export interface CanonicalInputStatement {
|
|
20
|
-
/** The predicate's canonical URI. */
|
|
21
|
-
predicate: string;
|
|
22
|
-
value: CanonicalInputValue;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* A value: a typed scalar (`lit` + its `datatype` URI), an untyped/open-world
|
|
26
|
-
* scalar (`raw` token, no carrier), a reference, an embedded node, or a list.
|
|
27
|
-
*/
|
|
28
|
-
export type CanonicalInputValue = {
|
|
29
|
-
lit: string;
|
|
30
|
-
datatype: string;
|
|
31
|
-
} | {
|
|
32
|
-
raw: string;
|
|
33
|
-
} | {
|
|
34
|
-
ref: string;
|
|
35
|
-
} | {
|
|
36
|
-
embed: {
|
|
37
|
-
name?: string;
|
|
38
|
-
statements: CanonicalInputStatement[];
|
|
39
|
-
};
|
|
40
|
-
} | {
|
|
41
|
-
list: CanonicalInputValue[];
|
|
42
|
-
};
|
|
14
|
+
import type { CanonicalInput } from '@kanonak-protocol/canonical';
|
|
15
|
+
export type { CanonicalInput, CanonicalInputSubject, CanonicalInputStatement, CanonicalInputValue, } from '@kanonak-protocol/canonical';
|
|
43
16
|
/** Discriminate a `CanonicalInput` from a `Kanonak[]` (for the public overload). */
|
|
44
17
|
export declare function isCanonicalInput(arg: unknown): arg is CanonicalInput;
|
|
45
|
-
/**
|
|
46
|
-
* Build the SDK object model the canonical form consumes from a `CanonicalInput`.
|
|
47
|
-
* Datatypes are classified by their URI via {@link carrierOf} (the same routing
|
|
48
|
-
* the parser uses); predicate/reference URIs resolve through the canonical URI
|
|
49
|
-
* parser; a typed scalar carries `(carrier, lexical)`, an untyped one its raw
|
|
50
|
-
* token. The canonical form reads `(carrier, lexical)` off any scalar statement,
|
|
51
|
-
* so a single `StringStatement` faithfully represents every scalar carrier —
|
|
52
|
-
* producing bytes identical to the parsed-model path for equivalent content.
|
|
53
|
-
*/
|
|
54
|
-
export declare function buildModelFromInput(input: CanonicalInput): Kanonak[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as N}from"./chunk-NJ3AZYQD.js";import{b as V,c as C,i as B,j as M}from"./chunk-7HRKWTBB.js";import{a as _,b as U,c as S,d as k,g as P,h as x,i as O,j as I,k as R,l as v}from"./chunk-4UT2CLAT.js";import{j as $}from"./chunk-2ACBWC7K.js";var w=class extends U{name};var K=class extends _{value;carrier;lexical};var D=class extends P{links=[]};import{Carrier as j,carrierOf as F}from"@kanonak-protocol/canonical";function T(p){return F(`${p.publisher}/${p.package_}/${p.name}`)}var Y=/\[\[([^\[\]\n]+)\]\]/g,G=/\[\[/g,z=/```[\s\S]*?```|`[^`\n]*`/g;function q(p){let e=[];for(let t of p.matchAll(z))e.push([t.index,t.index+t[0].length]);return e}function ae(p){if(!p||!p.includes("[["))return[];let e=q(p),t=s=>e.some(([r,i])=>s>=r&&s<i),a=new Set(E(p).map(s=>s.startOffset)),n=[];for(let s of p.matchAll(G)){let r=s.index;if(t(r)||a.has(r))continue;let i=p.slice(r,r+48).replace(/\s+/g," ").trim();n.push({startOffset:r,snippet:i})}return n}function E(p){if(!p||!p.includes("[["))return[];let e=[];for(let n of p.matchAll(z))e.push([n.index,n.index+n[0].length]);let t=n=>e.some(([s,r])=>n>=s&&n<r),a=[];for(let n of p.matchAll(Y)){let s=n.index;if(t(s))continue;let r=n[1],i=r.indexOf("|"),c=(i===-1?r:r.slice(0,i)).trim();if(c.length===0)continue;let f=i===-1?"":r.slice(i+1).trim(),g={reference:c,startOffset:s,endOffset:s+n[0].length};f.length>0&&(g.displayText=f),a.push(g)}return a}var X=class{constructor(e){}async parseKanonaks(e){let t=[],a=await e.getAllDocumentsAsync(),n=new V(e),s=new C(n);for(let o of a){let m=o.metadata.namespace_?.toString()??"";for(let[u,y]of Object.entries(o.body)){let d=new S,b=this.resolveCanonicalEntity(u,o,m);d.namespace=b.namespace,d.name=b.name,d.statement=[];let h=await this.parseStatements(y,o,n,s,e);d.statement.push(...h.statements),d.unresolvedPredicates=h.unresolved,t.push(d)}}let r=new Map,i=new Map,c=[];for(let o of t)if(o instanceof S){let m=`${o.namespace}/${o.name}`,u=r.get(m);if(u){let y=i.get(m);for(let d of o.statement){let b=L(d);y.has(b)||(y.add(b),u.statement.push(d))}for(let d of o.unresolvedPredicates)u.unresolvedPredicates.some(b=>b.key===d.key&&b.sourceDoc===d.sourceDoc)||u.unresolvedPredicates.push(d)}else{let y=new Set,d=[];for(let b of o.statement){let h=L(b);y.has(h)||(y.add(h),d.push(b))}o.statement=d,i.set(m,y),r.set(m,o),c.push(o)}}else c.push(o);let f=new Set;for(let o of c)if(o instanceof S){let m=o.namespace||"",u=m.indexOf("/"),y=u>=0?m.slice(0,u):"",d=u>=0?m.slice(u+1):"",b=d.indexOf("@"),h=b>=0?d.slice(0,b):d;f.add(`${y}/${h}/${o.name}`)}let g=o=>f.has(`${o.publisher}/${o.package_}/${o.name}`),l=new Map;for(let o of["core-rdf","core-owl","core-kanonak"]){let m=await e.getDocumentsByNamespaceAsync("kanonak.org",o);l.set(o,$(m).chosen?.metadata.namespace_?.version??void 0)}for(let o of c)o instanceof S&&this.canonicalizeStatementBuiltins(o.statement,g,l);return c}canonicalizeStatementBuiltins(e,t,a){for(let n of e){let s=n.predicate?.subject;if(M(s,t,a),n instanceof I)n.object instanceof k&&M(n.object.subject,t,a);else if(n instanceof R)n.object&&this.canonicalizeStatementBuiltins(n.object.statement,t,a);else if(n instanceof v)for(let r of n.object??[])r instanceof k?M(r.subject,t,a):r instanceof w&&this.canonicalizeStatementBuiltins(r.statement,t,a)}}resolveCanonicalEntity(e,t,a){if(!e.includes(".")||!t.metadata?.imports)return{namespace:a,name:e};let n=e.indexOf("."),s=e.substring(0,n),r=e.substring(n+1);for(let[i,c]of Object.entries(t.metadata.imports))for(let f of c)if((f.alias??f.packageName)===s){let l=f.version;return{namespace:`${i}/${f.packageName}@${l.major}.${l.minor}.${l.patch}`,name:r}}return{namespace:a,name:e}}async parseStatements(e,t,a,n,s){let r=[],i=[];if(typeof e!="object"||e===null||Array.isArray(e))return{statements:r,unresolved:i};let c=t.metadata.namespace_?.toString()??"";for(let[f,g]of Object.entries(e))try{let l=await this.getPropertyMetadata(f,t,a,s,n);if(!l){let m=f.includes(".")?f.slice(f.lastIndexOf(".")+1):f;B(m)||i.push({key:f,sourceDoc:c});continue}let o=await this.parsePropertyValue(f,g,l,t,a,n,s);o&&r.push(o)}catch(l){throw new Error(`Failed to parse property '${f}': ${l.message}`,{cause:l})}return{statements:r,unresolved:i}}async getPropertyMetadata(e,t,a,n,s){let r=await a.resolveEntityAsync(e,t);if(!r)return;let i=r.entity,c=i.type?.toString()??"",f=c.includes(".")?c.substring(c.lastIndexOf(".")+1):c;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(f))return;let l=s.getPropertyTypeClassification(c),o=i.range?.toString(),m;if(l==="ObjectProperty")m="ObjectProperty";else if(l==="DatatypeProperty")m="DatatypeProperty";else{let d=o&&o.includes(".")?o.substring(o.lastIndexOf(".")+1):o??"";(o?s.isKnownXsdDatatypeName(o):!1)||d==="Literal"?m="DatatypeProperty":m="ObjectProperty"}let u;if(o){let d=t;if(r.isImported&&r.definedInNamespace){if(typeof n.getDocumentAsync!="function")throw new Error(`Cannot resolve the range of imported property '${e}': the parse repository cannot fetch defining document '${r.definedInNamespace}'. Thread the real repository through to embedded-object parsing \u2014 no stub, no fallback.`);let h=await n.getDocumentAsync(r.definedInNamespace);if(!h)throw new Error(`Cannot resolve the range of imported property '${e}': defining document '${r.definedInNamespace}' was not found in the repository.`);d=h}u=(await a.resolveEntityAsync(o,d))?.uri}return{propertyUri:r.uri.toString(),propertyType:m,range:o,rangeUri:u,isImported:r.isImported,definedInNamespace:r.definedInNamespace}}async parsePropertyValue(e,t,a,n,s,r,i){let c=a.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(c,t,a,n,s,r,i);if(a.propertyType==="DatatypeProperty")return this.parseDatatypeValue(c,t,a,n,s,r);if(a.propertyType==="ObjectProperty")return this.parseObjectValue(c,t,a,n,s,r,i)}}async parseDatatypeValue(e,t,a,n,s,r){let i;if(typeof t=="string"){if(r.isSubstitutableDatatype(a.rangeUri))return await this.parseSubstitutableValue(e,t,n,s);i=t}else if(typeof t=="number"||typeof t=="boolean")i=String(t);else return;return this.typedScalarStatement(e,i,a)}typedScalarStatement(e,t,a){let n=k.parse(e),s=a.rangeUri?T(a.rangeUri):void 0;if(s===j.Boolean){let i=new O;return i.predicate=n,i.object=t==="true"||t==="1",i.carrier=s,i.lexical=t,i}if(s===j.Integer||s===j.Decimal||s===j.Double||s===j.Float){let i=new x;return i.predicate=n,i.object=Number(t),i.carrier=s,i.lexical=t,i}let r=P.parse(e,t);return s&&(r.carrier=s,r.lexical=t),r}typedListLiteral(e,t){let a=new K,n=t.rangeUri?T(t.rangeUri):void 0;return n===j.Boolean?a.value=e==="true"||e==="1":n===j.Integer||n===j.Decimal||n===j.Double||n===j.Float?a.value=Number(e):a.value=e,n&&(a.carrier=n,a.lexical=e),a}async parseSubstitutableValue(e,t,a,n){let s=new D;s.predicate=k.parse(e),s.object=t;for(let r of E(t)){let i=await n.resolveEntityAsync(r.reference,a),c;i&&(c=new k,c.subject=i.uri);let f={reference:r.reference,startOffset:r.startOffset,endOffset:r.endOffset};r.displayText!==void 0&&(f.displayText=r.displayText),c!==void 0&&(f.target=c),s.links.push(f)}return s}async parseObjectValue(e,t,a,n,s,r,i){if(typeof t=="string"){let c=await this.resolveReference(t,n,s);if(!c)return;let f=new I;return f.predicate=k.parse(e),f.object=c,f}if(typeof t=="object"&&!Array.isArray(t)){let c=await this.parseStatements(t,n,s,r,i);if(c.statements.length>0){let l=new w;l.statement=c.statements,l.unresolvedPredicates=c.unresolved;let o=new R;return o.predicate=k.parse(e),o.object=l,o}let f=[];for(let[l,o]of Object.entries(t))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let m=new w;m.name=l;let u=await this.parseStatements(o,n,s,r,i);m.statement=u.statements,m.unresolvedPredicates=u.unresolved,f.push(m)}else if(typeof o=="string"){let m=await this.resolveReference(o,n,s);m&&f.push(m)}if(f.length>0){let l=new v;return l.predicate=k.parse(e),l.object=f,l}let g=new R;return g.predicate=k.parse(e),g.object=new w,g}}async parseListValue(e,t,a,n,s,r,i){let c=[],f=a.propertyType==="DatatypeProperty",g=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 o of t){let m=typeof o=="string"||typeof o=="number"||typeof o=="boolean";if(f&&m){let u=typeof o=="string"?o:String(o);c.push(this.typedListLiteral(u,a));continue}if(g&&m){if(typeof o=="string"){let u=await s.resolveEntityAsync(o,n);if(u){let y=new k;y.subject=u.uri,c.push(y)}else{let y=new K;y.value=o,c.push(y)}}else{let u=new K;u.value=o,c.push(u)}continue}if(typeof o=="string"){let u=await this.resolveReference(o,n,s);u&&c.push(u)}else if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let u=new w,y=await this.parseStatements(o,n,s,r,i);u.statement=y.statements,u.unresolvedPredicates=y.unresolved,c.push(u)}}let l=new v;return l.predicate=k.parse(e),l.object=c,l}async resolveReference(e,t,a){let n=await a.resolveEntityAsync(e,t);if(n){let r=new k;return r.subject=n.uri,r}let s=t.metadata?.namespace_;if(s){let{KanonakUri:r}=await import("./KanonakUri-4VJGV3FN.js");if(e.includes(".")){let c=e.indexOf("."),f=e.substring(0,c),g=e.substring(c+1);if(t.metadata?.imports){for(let[l,o]of Object.entries(t.metadata.imports))for(let m of o)if((m.alias??m.packageName)===f){let y=new k;return y.subject=new r(l,m.packageName,g,m.version),y}}}let i=new k;return i.subject=new r(s.publisher,s.package_,e,s.version??void 0),i}return null}async saveKanonaks(e,t){let a=new Map;for(let n of e)n instanceof S&&n.namespace&&(a.has(n.namespace)||a.set(n.namespace,[]),a.get(n.namespace).push(n));for(let[n,s]of a){let r=await this.convertKanonaksToDocument(n,s),i=`${n.split("@")[0]}.yml`;await t.saveDocumentAsync(r,i)}}async serializeToYaml(e,t){let a=e.filter(r=>r instanceof S&&r.namespace===t);if(a.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let n=await this.convertKanonaksToDocument(t,a);return new N().save(n)}async convertKanonaksToDocument(e,t){let n={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let r=[];for(let i of Object.values(this.imports))r.push(...i);return r}},body:{}},s=new Map;for(let r of t){let i={};for(let c of r.statement){let[f,g]=this.convertStatementToProperty(c);f&&g!==null&&g!==void 0&&(i[f]=g),this.collectImportsFromStatement(c,e,s)}n.body[r.name]=i}return n}convertStatementToProperty(e){if(e instanceof P)return[e.predicate.subject.name,e.object];if(e instanceof x)return[e.predicate.subject.name,e.object];if(e instanceof O)return[e.predicate.subject.name,e.object];if(e instanceof I)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof v){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof R){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 w&&t.push(this.convertEmbeddedKanonakToValue(a));return t}convertEmbeddedKanonakToValue(e){let t={};for(let a of e.statement){let[n,s]=this.convertStatementToProperty(a);n&&s!==null&&s!==void 0&&(t[n]=s)}return t}collectImportsFromStatement(e,t,a){}};function L(p){let e=p.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+H(p)}function H(p){return p instanceof D?"m:"+String(p.object):p instanceof P?"s:"+String(p.object):p instanceof x?"n:"+String(p.object):p instanceof O?"b:"+String(p.object):p instanceof I?"r:"+A(p.object):p instanceof R?"e:"+A(p.object):p instanceof v?"l:["+(p.object??[]).map(A).join("|")+"]":"x"}function A(p){if(!p)return"";if(p instanceof k){let e=p.subject;return"R("+(e?`${e.publisher}/${e.package_}/${e.name}`:"")+")"}return p instanceof w?"E("+(p.statement??[]).map(L).join(";")+")":p instanceof K?"L("+String(p.value)+")":"N"}export{w as a,K as b,D as c,j as d,T as e,ae as f,E as g,X as h};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as j,b as x,
|
|
1
|
+
import{a as j,b as x,h as _}from"./chunk-BKVPSPG4.js";import{d as l,e as u,f as b,g as $,h as s,k as h}from"./chunk-7HRKWTBB.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-4UT2CLAT.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{
|
|
1
|
+
import{g as V}from"./chunk-BKVPSPG4.js";import{a as E}from"./chunk-NJ3AZYQD.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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{J as W,K as X}from"./chunk-
|
|
1
|
+
import{J as W,K as X}from"./chunk-UBBZWWRB.js";import{b as B,c as V,h as w}from"./chunk-BKVPSPG4.js";import{a as b,d as K,e as q,f as z}from"./chunk-IEOSSSB5.js";import{a as D,f as E,h as F,j as N,k as Y,m as v}from"./chunk-7TKJHKC2.js";import{c as G,d as x}from"./chunk-4UT2CLAT.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,4 +1,4 @@
|
|
|
1
|
-
import{d as _}from"./chunk-SHDHMKMJ.js";import{a as I,b as Ne,c as Qe,g as tt,i as E}from"./chunk-MFNVQSBW.js";import{a as Ye}from"./chunk-NJ3AZYQD.js";import{a as B,d as W,e as nt,f as ot,g as x,h as rt}from"./chunk-IEOSSSB5.js";import{a as C,d as A,f as T,h as xe,i as w,j as L,k as V,l as O,m as S,n as M}from"./chunk-7TKJHKC2.js";import{a as N,b as U,c as et}from"./chunk-7HRKWTBB.js";import{c as D,d as H,k as Ze,l as Je}from"./chunk-4UT2CLAT.js";import{a as Ge}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=(t=>(t.Warning="Warning",t.Error="Error",t))(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 Le=class m{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new m;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var Se=class{constructor(e){this.underlying=e;this.repository=new We(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new E().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let t=this.importClosureCache.get(e);return t||(t=this.computeImportClosure(e),this.importClosureCache.set(e,t),t)}async getClassDeclarations(e){let t=this.classDeclarationsCache.get(e);return t||(t=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,t),t)}async getPropertyNames(e){let t=this.propertyNamesCache.get(e);return t||(t=this.computePropertyNames(e),this.propertyNamesCache.set(e,t),t)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let t=new Set([e]),n=[e],o=await this.buildDocsByIdIndex();for(;n.length>0;){let a=n.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=Me(p);!l||t.has(l)||(t.add(l),n.push(l))}}return t}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),t=new Map;for(let n of e){let o=Me(n);o&&t.set(o,n)}return t}async computeClassDeclarations(e){let t=await this.findDocById(e),n=new Map;if(!t)return n;for(let[o,a]of Object.entries(t.body)){if(!it(a))continue;let r=a,i=at(r,"type");if(i==="Class"||i?.endsWith(".Class")){let s=Rt(r);n.set(o,s)}}return n}async computePropertyNames(e){let t=await this.findDocById(e),n=new Set;if(!t)return n;for(let[o,a]of Object.entries(t.body)){if(!it(a))continue;let i=at(a,"type");(i==="ObjectProperty"||i?.endsWith(".ObjectProperty")||i==="DatatypeProperty"||i?.endsWith(".DatatypeProperty")||i==="AnnotationProperty"||i?.endsWith(".AnnotationProperty")||i==="Property"||i?.endsWith(".Property"))&&n.add(o)}return n}async findDocById(e){let t=await this.getAllDocuments();for(let n of t)if(Me(n)===e)return n}};function Me(m){let e=m.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${P(e.version)}`}function it(m){return typeof m=="object"&&m!==null&&!Array.isArray(m)}function at(m,e){if(e in m)return st(m[e]);for(let t of Object.keys(m))if(t.endsWith(`.${e}`))return st(m[t])}function st(m){return Array.isArray(m)?m.length>0?String(m[0]):void 0:m==null?void 0:String(m)}function Rt(m){let e=m.subClassOf;if(e===void 0){for(let t of Object.keys(m))if(t.endsWith(".subClassOf")){e=m[t];break}}return N(e)}var We=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let n=`${e}/${t}`,o=this.byNamespaceCache.get(n);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(n,o),o)}getHighestCompatibleVersionAsync(e,t){let n=t.version,o=n?`${n.major}.${n.minor}.${n.patch}`:"",a=`${e}/${t.packageName}@${t.versionOperator}:${o}`,r=this.highestVersionCache.get(a);return r||(r=this.inner.getHighestCompatibleVersionAsync(e,t),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 m{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[n,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(n,o,t);return t}validateEntity(e,t,n){for(let[o,a]of Object.entries(t)){let r=a?.toString()??"";if(r&&m.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.",n.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,n)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let n=e.indexOf(":");return n>=0?e.substring(n+1):e}};var Y=class m{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],n=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let r=m.VALID_AUGMENTATION_PATTERN.test(o);if(!r&&!n&&m.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.",t.push(i);continue}if(!r&&!m.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,t.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,t)}return t}validatePropertyNames(e,t,n){for(let o of Object.keys(t))if(!m.VALID_PROPERTIES.has(o)&&!m.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.",n.push(a)}}};var G=class m{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let n=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"&&!n&&s.push(p)}else{let c=i?.toString();c&&c==="Property"&&!n&&s.push(c)}for(let c of s){let p=this.getPropertyValue(r,"range"),l=this.determinePropertyType(p),u=new g;u.ruleType=this.ruleName,u.severity="Error",u.entityName=o,u.propertyName="type",u.actualValue=c,u.expectedValue=l,u.message=`Invalid property type '${c}'. Use '${l}' instead.`,u.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(u)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":m.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let n=e[t];return n?n.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t.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 t=[];for(let[n,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||n.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=n,s.propertyName="type",s.message=`Subject Kanonak '${n}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
|
|
1
|
+
import{d as _}from"./chunk-SHDHMKMJ.js";import{a as I,b as Ne,c as Qe,f as tt,h as E}from"./chunk-BKVPSPG4.js";import{a as Ye}from"./chunk-NJ3AZYQD.js";import{a as B,d as W,e as nt,f as ot,g as x,h as rt}from"./chunk-IEOSSSB5.js";import{a as C,d as A,f as T,h as xe,i as w,j as L,k as V,l as O,m as S,n as M}from"./chunk-7TKJHKC2.js";import{a as N,b as U,c as et}from"./chunk-7HRKWTBB.js";import{c as D,d as H,k as Ze,l as Je}from"./chunk-4UT2CLAT.js";import{a as Ge}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=(t=>(t.Warning="Warning",t.Error="Error",t))(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 Le=class m{resolvedDocuments=[];currentEntityPath;withPath(e){let t=new m;return t.resolvedDocuments=this.resolvedDocuments,t.currentEntityPath=e,t}};var Se=class{constructor(e){this.underlying=e;this.repository=new We(e)}underlying;repository;kanonaksPromise=null;importClosureCache=new Map;classDeclarationsCache=new Map;propertyNamesCache=new Map;allDocumentsPromise=null;getKanonaks(){return this.kanonaksPromise||(this.kanonaksPromise=new E().parseKanonaks(this.underlying)),this.kanonaksPromise}async getImportClosure(e){let t=this.importClosureCache.get(e);return t||(t=this.computeImportClosure(e),this.importClosureCache.set(e,t),t)}async getClassDeclarations(e){let t=this.classDeclarationsCache.get(e);return t||(t=this.computeClassDeclarations(e),this.classDeclarationsCache.set(e,t),t)}async getPropertyNames(e){let t=this.propertyNamesCache.get(e);return t||(t=this.computePropertyNames(e),this.propertyNamesCache.set(e,t),t)}getAllDocuments(){return this.allDocumentsPromise||(this.allDocumentsPromise=this.underlying.getAllDocumentsAsync()),this.allDocumentsPromise}async computeImportClosure(e){let t=new Set([e]),n=[e],o=await this.buildDocsByIdIndex();for(;n.length>0;){let a=n.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=Me(p);!l||t.has(l)||(t.add(l),n.push(l))}}return t}async buildDocsByIdIndex(){let e=await this.getAllDocuments(),t=new Map;for(let n of e){let o=Me(n);o&&t.set(o,n)}return t}async computeClassDeclarations(e){let t=await this.findDocById(e),n=new Map;if(!t)return n;for(let[o,a]of Object.entries(t.body)){if(!it(a))continue;let r=a,i=at(r,"type");if(i==="Class"||i?.endsWith(".Class")){let s=Rt(r);n.set(o,s)}}return n}async computePropertyNames(e){let t=await this.findDocById(e),n=new Set;if(!t)return n;for(let[o,a]of Object.entries(t.body)){if(!it(a))continue;let i=at(a,"type");(i==="ObjectProperty"||i?.endsWith(".ObjectProperty")||i==="DatatypeProperty"||i?.endsWith(".DatatypeProperty")||i==="AnnotationProperty"||i?.endsWith(".AnnotationProperty")||i==="Property"||i?.endsWith(".Property"))&&n.add(o)}return n}async findDocById(e){let t=await this.getAllDocuments();for(let n of t)if(Me(n)===e)return n}};function Me(m){let e=m.metadata.namespace_;if(!(!e||!e.version))return`${e.publisher}/${e.package_}@${P(e.version)}`}function it(m){return typeof m=="object"&&m!==null&&!Array.isArray(m)}function at(m,e){if(e in m)return st(m[e]);for(let t of Object.keys(m))if(t.endsWith(`.${e}`))return st(m[t])}function st(m){return Array.isArray(m)?m.length>0?String(m[0]):void 0:m==null?void 0:String(m)}function Rt(m){let e=m.subClassOf;if(e===void 0){for(let t of Object.keys(m))if(t.endsWith(".subClassOf")){e=m[t];break}}return N(e)}var We=class{constructor(e){this.inner=e}inner;highestVersionCache=new Map;byNamespaceCache=new Map;getAllDocumentsAsync(){return this.inner.getAllDocumentsAsync()}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,t){let n=`${e}/${t}`,o=this.byNamespaceCache.get(n);return o||(o=this.inner.getDocumentsByNamespaceAsync(e,t),this.byNamespaceCache.set(n,o),o)}getHighestCompatibleVersionAsync(e,t){let n=t.version,o=n?`${n.major}.${n.minor}.${n.patch}`:"",a=`${e}/${t.packageName}@${t.versionOperator}:${o}`,r=this.highestVersionCache.get(a);return r||(r=this.inner.getHighestCompatibleVersionAsync(e,t),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 m{static NAMESPACE_PREFIX_PATTERN=/^(rdfs|xsd|owl|rdf|dc|foaf|skos|dct|dcterms|geo|time|prov|schema|og|dbo):/i;ruleName="NamespacePrefix";validate(e){let t=[];for(let[n,o]of Object.entries(e.body))o&&typeof o=="object"&&!Array.isArray(o)&&this.validateEntity(n,o,t);return t}validateEntity(e,t,n){for(let[o,a]of Object.entries(t)){let r=a?.toString()??"";if(r&&m.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.",n.push(c)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validateEntity(`${e}.${o}`,a,n)}}getSuggestionForPrefixedValue(e){let t=e.toLowerCase();if(t==="rdfs:class"||t==="owl:class")return"Class";if(t==="rdfs:property"||t==="rdf:property")return"DatatypeProperty or ObjectProperty";if(t.startsWith("xsd:"))return e.substring(4);let n=e.indexOf(":");return n>=0?e.substring(n+1):e}};var Y=class m{static RESERVED_WORDS=new Set(["imports","namespace","type","label","comment","subclassof","domain","range","required","functional"]);static VALID_PROPERTIES=new Set(["type","label","comment","subClassOf","subPropertyOf","domain","range","required","functional","inverseOf","transitive","symmetric","inverseFunctional"]);static VALID_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_AUGMENTATION_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]*\.[a-zA-Z][a-zA-Z0-9_-]*$/;static VALID_PROPERTY_NAME_PATTERN=/^[a-zA-Z][a-zA-Z0-9_.]*$/;ruleName="ResourceNaming";validate(e){let t=[],n=e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-");for(let[o,a]of Object.entries(e.body)){let r=m.VALID_AUGMENTATION_PATTERN.test(o);if(!r&&!n&&m.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.",t.push(i);continue}if(!r&&!m.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,t.push(s)}a&&typeof a=="object"&&!Array.isArray(a)&&this.validatePropertyNames(o,a,t)}return t}validatePropertyNames(e,t,n){for(let o of Object.keys(t))if(!m.VALID_PROPERTIES.has(o)&&!m.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.",n.push(a)}}};var G=class m{static XSD_TYPES=new Set(["string","integer","int","long","short","byte","decimal","float","double","boolean","bool","datetime","date","time","duration","anyuri","anysimpletype","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte","base64binary","hexbinary"]);ruleName="PropertyTypeSpecificity";validate(e){let t=[];if(e.metadata?.namespace_?.publisher==="kanonak.org"&&e.metadata?.namespace_?.package_?.startsWith("core-"))return t;let n=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"&&!n&&s.push(p)}else{let c=i?.toString();c&&c==="Property"&&!n&&s.push(c)}for(let c of s){let p=this.getPropertyValue(r,"range"),l=this.determinePropertyType(p),u=new g;u.ruleType=this.ruleName,u.severity="Error",u.entityName=o,u.propertyName="type",u.actualValue=c,u.expectedValue=l,u.message=`Invalid property type '${c}'. Use '${l}' instead.`,u.suggestion="Properties should specify their type: DatatypeProperty for data values, ObjectProperty for relationships.",t.push(u)}}}return t}determinePropertyType(e){return!e||e.trim().length===0?"DatatypeProperty or ObjectProperty":m.XSD_TYPES.has(e.toLowerCase())?"DatatypeProperty":/^[A-Z]/.test(e)?"ObjectProperty":"DatatypeProperty or ObjectProperty"}getPropertyValue(e,t){let n=e[t];return n?n.toString():null}isPropertyDefinedAsClass(e){let t=e.body.Property;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t.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 t=[];for(let[n,o]of Object.entries(e.body)){if(typeof o!="object"||o===null||Array.isArray(o)||n.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=n,s.propertyName="type",s.message=`Subject Kanonak '${n}' must have a 'type' property.`,s.suggestion=`Add a type statement like:
|
|
2
2
|
type: Scene
|
|
3
3
|
|
|
4
4
|
Only embedded objects can infer type from their parent property's range. Subject Kanonaks (top-level entities) must explicitly declare their type.`,s.expectedValue="A valid class name (Scene, Character, Story, etc.)",t.push(s)}}return t}};var vt=new Set(["EphemeralPackage"]),J=class{get ruleName(){return"PackageHeader"}validate(e){let t=e.metadata;if(!t.type_)return[];let n=[],o=this.packageKey(e,t.type_);return t.namespace_?(!vt.has(t.type_)&&!t.namespace_.version&&n.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,4 +1,4 @@
|
|
|
1
|
-
import{a as Cn}from"./chunk-4NO7MHS7.js";import{a as An}from"./chunk-PEJALHXK.js";import{d as u}from"./chunk-SHDHMKMJ.js";import{a as M,c as Me,
|
|
1
|
+
import{a as Cn}from"./chunk-4NO7MHS7.js";import{a as An}from"./chunk-PEJALHXK.js";import{d as u}from"./chunk-SHDHMKMJ.js";import{a as M,c as Me,h as Vn}from"./chunk-BKVPSPG4.js";import{a as Fn}from"./chunk-NJ3AZYQD.js";import{a as pn,b as ue,c as xn,d as w,f as Ne,g as ke,j as gn,k as qe,m as Mn,n as Nn}from"./chunk-7TKJHKC2.js";import{b as Oe,c as G,d as E,g as X,h as me,i as re,j as V,k as H,l as T}from"./chunk-4UT2CLAT.js";import{a as Tn}from"./chunk-FUUTGGJS.js";import{c as en,g as ye}from"./chunk-2ACBWC7K.js";var Te="kanonak.org",Hn="look",We="core-rdf",Et={publisher:Te,package_:Hn,name:"displayLabel"},Kt={publisher:Te,package_:Hn,name:"displaySummary"},Rt={publisher:Te,package_:We,name:"type"},Lt={publisher:Te,package_:We,name:"subClassOf"},Ot={publisher:Te,package_:We,name:"label"},Ut={publisher:Te,package_:We,name:"comment"},Pn=new Tn(Te,We,"Resource");function D(r,e){let n=Dn(r,e,Et)??Ot,t=Dn(r,e,Kt)??Ut,a=gn(e,n)??e.name,s=gn(e,t);return{label:a,summary:s}}function Dn(r,e,n){let t=qe(e,n);if(t)return t;let a=new Set,s=Bn(e,Rt);for(;s.length>0;){let o=s.shift(),i=pn(o);if(a.has(i))continue;a.add(i);let c=Ne(r,o);if(!c)continue;let l=qe(c,n);if(l)return l;s.push(...Bn(c,Lt))}if(!a.has(pn(Pn))){let o=Ne(r,Pn);if(o){let i=qe(o,n);if(i)return i}}}function Bn(r,e){let n=qe(r,e);if(n)return[n];let t=[];for(let a of Mn(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-${Gn(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=Pe(i[2].trim());t.push(`<h${l}>${d}</h${l}>`),a++;continue}if(s.includes("|")&&a+1<n.length&&zn(n[a+1])){let l=mn(s),d=It(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(Ct(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>${Pe(d.join(" ").trim())}</li>`)}t.push(`<ul>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as D}from"./chunk-
|
|
1
|
+
import{a as D}from"./chunk-BKVPSPG4.js";import{c as j,d as m,g as R,j as p,k as K,l as k}from"./chunk-4UT2CLAT.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};
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(
|
|
1
|
+
import{a as kr,b as hr,c as br,d as Pr,e as he}from"./chunk-CR55WXIN.js";import{a as mn,c as Ce,e as Le,h as Fe,i as Me,j as fn}from"./chunk-V72IVYR4.js";import{a as fr,b as yr,c as gr,d as L,e as F,f as l,g as yn}from"./chunk-U7LVFPEO.js";import{a as dn}from"./chunk-VWS25JH4.js";import"./chunk-QHABFCRC.js";import{a as Ut,b as _t,c as Lt,d as Ft,e as Mt,f as Zt,g as Xt,h as Qt,i as er}from"./chunk-GMEPM2QQ.js";import{a as Ht,b as zt,c as Wt,d as b,f as Gt,g as Jt,h as Yt}from"./chunk-JYBKSBB5.js";import{a as Bt}from"./chunk-4NO7MHS7.js";import{a as Cr,b as Sr,c as Rr,d as Er}from"./chunk-RGOBWOBB.js";import{a as xr,b as Vr}from"./chunk-PEUTCG3B.js";import{a as vr}from"./chunk-PEJALHXK.js";import{a as qt}from"./chunk-SC5M74NM.js";import{A as sn,B as cn,C as ln,D as un,M as pn,a as Or,b as Dr,c as Tr,d as Nr,e as Br,f as Ur,g as _r,h as Lr,i as Fr,j as Mr,k as Hr,l as zr,m as Wr,n as Gr,o as Jr,p as qr,q as Yr,r as Zr,s as Xr,t as Qr,u as en,v as tn,w as rn,x as nn,y as on,z as an}from"./chunk-UBBZWWRB.js";import"./chunk-SHDHMKMJ.js";import{a as y,b as ue,c as or,d as U,e as Ue,f as pr,g as dr,h as E}from"./chunk-BKVPSPG4.js";import{a as S}from"./chunk-NJ3AZYQD.js";import{a as mr,b as be,c as Ir,d as g,e as Kr,f as $r,g as jr,h as Ar}from"./chunk-IEOSSSB5.js";import{f as _,k as x,l as Pe,m as we,n as _e}from"./chunk-7TKJHKC2.js";import{b as ar,c as ir,d as R,e as sr,f as cr,h as lr,k as ur}from"./chunk-7HRKWTBB.js";import{a as tr,b as le,c as f,d as h,e as nr,f as pe,g as de,h as me,i as fe,j as ye,k as ge,l as ke}from"./chunk-4UT2CLAT.js";import{a as rr}from"./chunk-FUUTGGJS.js";import{a as jt,b as ce,c as B,d as At,e as k,f as Vt,g as Ot,h as Dt,i as Tt,j as Nt}from"./chunk-2ACBWC7K.js";import{a as wr}from"./chunk-ODIECDN7.js";import{VersionOperator as Si}from"@kanonak-protocol/types/document/models/enums";import{existsSync as Vn,readFileSync as On}from"fs";import{homedir as Dn}from"os";import{join as Tn}from"path";import{execFile as gn}from"child_process";import{promisify as kn}from"util";var M=kn(gn),H="kanonak",z="/usr/bin/security",I=class{async get(e){let t=l(e);try{let{stdout:n}=await M(z,["find-generic-password","-s",H,"-a",t,"-w"],{timeout:1e4});try{return JSON.parse(n.trim())}catch{throw new Error(`Stored credential for '${t}' is corrupted (not valid JSON).
|
|
2
|
+
Run 'kanonak logout ${t}' then 'kanonak login ${t}' to fix.`)}}catch(n){if(He(n,44))return null;throw new Error(`macOS Keychain read failed for '${t}': ${W(n)}
|
|
3
3
|
The Keychain may be locked or inaccessible.
|
|
4
|
-
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let
|
|
4
|
+
Try unlocking it via Keychain Access.app or running 'security unlock-keychain'.`)}}async store(e,t){let n=l(e),o=JSON.stringify(t);try{await M(z,["add-generic-password","-s",H,"-a",n,"-U","-w",o],{timeout:1e4})}catch(a){throw new Error(`macOS Keychain write failed for '${n}': ${W(a)}
|
|
5
5
|
Ensure the Keychain is unlocked and the CLI has write permission.
|
|
6
|
-
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await
|
|
7
|
-
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await
|
|
8
|
-
`))if(o.includes(`"svce"<blob>="${
|
|
9
|
-
${
|
|
6
|
+
On managed devices, your IT policy may block credential storage.`)}}async remove(e){let t=l(e);try{await M(z,["delete-generic-password","-s",H,"-a",t],{timeout:1e4})}catch(n){if(He(n,44))return;console.warn(` Warning: macOS Keychain delete failed for '${t}': ${W(n)}
|
|
7
|
+
The credential may not have been fully removed.`)}}async list(){try{let{stdout:e}=await M(z,["dump-keychain"],{timeout:1e4}),t=[],n=!1;for(let o of e.split(`
|
|
8
|
+
`))if(o.includes(`"svce"<blob>="${H}"`)&&(n=!0),n&&o.includes('"acct"<blob>=')){let a=o.match(/"acct"<blob>="([^"]+)"/);a&&t.push(a[1]),n=!1}return t}catch(e){return console.warn(` Warning: Could not enumerate Keychain entries: ${W(e)}`),[]}}};function He(r,e){return typeof r=="object"&&r!==null&&"code"in r&&r.code===e}function W(r){return r instanceof Error?r.message:String(r)}import{execFile as hn}from"child_process";import{promisify as bn}from"util";var Pn=bn(hn),G="kanonak:",v=class{async get(e){let t=G+l(e),n=`
|
|
9
|
+
${q}
|
|
10
10
|
$target = [Console]::In.ReadLine()
|
|
11
11
|
$ptr = [IntPtr]::Zero
|
|
12
12
|
$result = [CredMan]::CredRead($target, 1, 0, [ref]$ptr)
|
|
@@ -18,8 +18,8 @@ try {
|
|
|
18
18
|
[System.Text.Encoding]::Unicode.GetString($bytes)
|
|
19
19
|
} finally {
|
|
20
20
|
[CredMan]::CredFree($ptr)
|
|
21
|
-
}`;try{let{stdout:o}=await
|
|
22
|
-
${
|
|
21
|
+
}`;try{let{stdout:o}=await J(n,t),a=o.trim();return a?JSON.parse(a):null}catch{return null}}async store(e,t){let n=G+l(e),o=JSON.stringify(t),a=`
|
|
22
|
+
${q}
|
|
23
23
|
$target = [Console]::In.ReadLine()
|
|
24
24
|
$json = [Console]::In.ReadLine()
|
|
25
25
|
$bytes = [System.Text.Encoding]::Unicode.GetBytes($json)
|
|
@@ -35,13 +35,13 @@ try {
|
|
|
35
35
|
if (-not $result) { throw "CredWrite failed" }
|
|
36
36
|
} finally {
|
|
37
37
|
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($cred.CredentialBlob)
|
|
38
|
-
}`;try{await
|
|
39
|
-
${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=
|
|
40
|
-
${
|
|
38
|
+
}`;try{await J(a,`${n}
|
|
39
|
+
${o}`)}catch(i){throw new Error(`Windows Credential Manager write failed: ${String(i)}`)}}async remove(e){let t=G+l(e),n=`
|
|
40
|
+
${q}
|
|
41
41
|
$target = [Console]::In.ReadLine()
|
|
42
|
-
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await
|
|
43
|
-
${
|
|
44
|
-
${
|
|
42
|
+
[CredMan]::CredDelete($target, 1, 0) | Out-Null`;try{await J(n,t)}catch{}}async list(){let e=`
|
|
43
|
+
${q}
|
|
44
|
+
${wn}
|
|
45
45
|
$prefix = [Console]::In.ReadLine()
|
|
46
46
|
$count = 0
|
|
47
47
|
$pCreds = [IntPtr]::Zero
|
|
@@ -55,8 +55,8 @@ if ([CredMan]::CredEnumerate($null, 0, [ref]$count, [ref]$pCreds)) {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
[CredMan]::CredFree($pCreds)
|
|
58
|
-
}`;try{let{stdout:t}=await
|
|
59
|
-
`).map(
|
|
58
|
+
}`;try{let{stdout:t}=await J(e,G);return t.trim().split(`
|
|
59
|
+
`).map(n=>n.trim()).filter(Boolean)}catch{return[]}}};async function J(r,e){for(let t of["pwsh","powershell"])try{return await Pn(t,["-NoProfile","-NonInteractive","-Command",r],{timeout:15e3,...e!==void 0&&{input:e}})}catch(n){if(t==="powershell")throw n}throw new Error("Neither pwsh nor powershell found")}var q=`
|
|
60
60
|
Add-Type -TypeDefinition @"
|
|
61
61
|
using System;
|
|
62
62
|
using System.Runtime.InteropServices;
|
|
@@ -87,13 +87,13 @@ public class CredMan {
|
|
|
87
87
|
[DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
88
88
|
public static extern bool CredEnumerate(string filter, int flags, out int count, out IntPtr credentials);
|
|
89
89
|
}
|
|
90
|
-
"@`,
|
|
91
|
-
`)){let o=
|
|
90
|
+
"@`,wn="";import{execFile as Cn,spawn as Sn}from"child_process";import{promisify as Rn}from"util";var Z=Rn(Cn),Y="kanonak",K=class{async get(e){let t=l(e);try{let{stdout:n}=await Z("secret-tool",["lookup","service",Y,"publisher",t],{timeout:1e4}),o=n.trim();return o?JSON.parse(o):null}catch{return null}}async store(e,t){let n=l(e),o=JSON.stringify(t);await new Promise((a,i)=>{let s=Sn("secret-tool",["store","--label",`Kanonak: ${n}`,"service",Y,"publisher",n],{stdio:["pipe","ignore","ignore"],timeout:1e4});s.stdin.write(o),s.stdin.end(),s.on("close",c=>{c===0?a():i(new Error(`secret-tool store exited with code ${c}`))}),s.on("error",i)})}async remove(e){let t=l(e);try{await Z("secret-tool",["clear","service",Y,"publisher",t],{timeout:1e4})}catch{}}async list(){try{let{stdout:e}=await Z("secret-tool",["search","service",Y],{timeout:1e4}),t=[];for(let n of e.split(`
|
|
91
|
+
`)){let o=n.match(/attribute\.publisher\s*=\s*(.+)/);o&&t.push(o[1].trim())}return t}catch{return[]}}};async function Se(){try{return await Z("sh",["-c","command -v secret-tool"],{timeout:5e3}),!0}catch{return!1}}import{existsSync as ze,mkdirSync as We,readFileSync as Ge,writeFileSync as Je}from"fs";import{createCipheriv as En,createDecipheriv as xn,randomBytes as qe}from"crypto";import{homedir as In}from"os";import{join as xe,dirname as Ye}from"path";var Xe=xe(In(),".config","kanonak"),$=xe(Xe,"keyring.key"),X=xe(Xe,"credentials.enc"),Ze="aes-256-gcm",Re=32,P=12,Ee=16,j=class{async get(e){let t=this.loadStore(),n=l(e);return t[n]??null}async store(e,t){let n=this.loadStore(),o=l(e);n[o]=t,this.saveStore(n)}async remove(e){let t=this.loadStore(),n=l(e);delete t[n],this.saveStore(t)}async list(){let e=this.loadStore();return Object.keys(e)}loadStore(){if(!ze(X))return{};try{let e=this.getOrCreateKey(),t=Ge(X);if(t.length<P+Ee)return{};let n=t.subarray(0,P),o=t.subarray(P,P+Ee),a=t.subarray(P+Ee),i=xn(Ze,e,n);i.setAuthTag(o);let s=Buffer.concat([i.update(a),i.final()]);return JSON.parse(s.toString("utf-8"))}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),n=qe(P),o=En(Ze,t,n),a=Buffer.from(JSON.stringify(e),"utf-8"),i=Buffer.concat([o.update(a),o.final()]),s=o.getAuthTag(),c=Buffer.concat([n,s,i]);We(Ye(X),{recursive:!0}),Je(X,c,{mode:384})}getOrCreateKey(){if(ze($)){let t=Ge($);if(t.length!==Re)throw new Error(`Credential keyring key is corrupted (expected ${Re} bytes, got ${t.length}). Delete ${$} and re-authenticate.`);return t}let e=qe(Re);return We(Ye($),{recursive:!0}),Je($,e,{mode:384}),e}};import{execFile as vn}from"child_process";import{promisify as Kn}from"util";var $n=Kn(vn),Qe=3e4,A=class{constructor(e){this.helperPath=e}helperPath;async get(e){let t=l(e);try{let o=(await this.runHelper("get",{publisher:t})).trim();return o?JSON.parse(o):null}catch(n){throw new Error(`Credential helper '${this.helperPath}' failed to read credential for '${t}': ${Q(n)}
|
|
92
92
|
Verify the helper binary exists, is executable, and implements the Kanonak credential helper protocol.
|
|
93
|
-
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let
|
|
94
|
-
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(
|
|
95
|
-
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):
|
|
96
|
-
The helper may be waiting for authentication to an external vault.`):
|
|
97
|
-
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as
|
|
98
|
-
The stored key pair may be corrupted. Run 'kanonak login ${
|
|
99
|
-
`;function ut(n=lt){if(!Qr(n))return null;let e=Zr(n,"utf-8"),t=ct.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function pt(n,e=lt){n.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(n.packages).sort())t[o]=n.packages[o];n.packages=t;let r=ct.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Xr(e,to+r,"utf-8")}function dt(n){return`sha256:${eo("sha256").update(n).digest("hex")}`}import*as Be from"js-yaml";import{createHash as ro}from"crypto";function $e(n){return typeof n=="object"&&n!==null&&Array.isArray(n.subjects)}function je(n){return n.subjects.map(e=>{let t=new f,r=e.uri.lastIndexOf("/");return t.namespace=e.uri.slice(0,r),t.name=e.uri.slice(r+1),t.statement=(e.statements??[]).map(o=>ft(o.predicate,o.value)),t})}function mt(n,e,t){let r=new E;return r.predicate=p.parse(n),r.object=t,e&&(r.carrier=e,r.lexical=t),r}function ft(n,e){if("lit"in e)return mt(n,K(z.parse(e.datatype)),e.lit);if("raw"in e)return mt(n,void 0,e.raw);if("ref"in e){let t=new x;return t.predicate=p.parse(n),t.object=p.parse(e.ref),t}if("embed"in e){let t=new I;return t.predicate=p.parse(n),t.object=yt(e.embed),t}if("list"in e){let t=new v;return t.predicate=p.parse(n),t.object=e.list.map(no),t}throw new Error(`canonical input: unknown value shape ${JSON.stringify(e)}`)}function yt(n){let e=new y;return n.name&&(e.name=n.name),e.statement=(n.statements??[]).map(t=>ft(t.predicate,t.value)),e}function no(n){if("ref"in n)return p.parse(n.ref);if("embed"in n)return yt(n.embed);let e=new R;if("lit"in n){e.value=n.lit;let t=K(z.parse(n.datatype));t&&(e.carrier=t,e.lexical=n.lit)}else if("raw"in n)e.value=n.raw;else throw new Error(`canonical input: unknown list item shape ${JSON.stringify(n)}`);return e}var kt="1",gt=new TextEncoder;function ht(n,e){let t=gt.encode(n),r=gt.encode(e),o=Math.min(t.length,r.length);for(let a=0;a<o;a++)if(t[a]!==r[a])return t[a]-r[a];return t.length-r.length}function Ae(n){let e=$e(n)?je(n):n,t=[];for(let o of e)o instanceof f&&t.push(oo(o));return t.sort((o,a)=>ht(o.uri,a.uri)),JSON.stringify({subjects:t})}function se(n){let e=$e(n)?je(n):n,t=Ae(e);return`sha256:${ro("sha256").update(t,"utf8").digest("hex")}`}function oo(n){let e=uo(n),t=Ve(n.statement);return{uri:e,statements:t}}function Ve(n){let e=[];for(let t of n){let r=ao(t);r&&e.push(r)}return e.sort((t,r)=>ht(t.predicate,r.predicate)),e}function ao(n){let e=lo(n);if(!e)return;let t=io(n);if(t)return co(e,t)}function io(n){if(n instanceof ge&&n.carrier)return{type:"typed",carrier:n.carrier,value:be(n.carrier,n.lexical??String(n.object))};if(n instanceof E)return{type:"string",value:n.object};if(n instanceof ke)return{type:"number",value:St(n.object)};if(n instanceof he)return{type:"boolean",value:n.object};if(n instanceof x)return{type:"ref",value:Pt(n.object)};if(n instanceof I){let e=n.object;return bt(e)}if(n instanceof v)return{type:"list",items:n.object.map(so)}}function bt(n){let e=Ve(n.statement);return n.name&&n.name.length>0?{type:"embedded",name:n.name,statements:e}:{type:"embedded",statements:e}}function so(n){if(n instanceof p)return{type:"ref",value:Pt(n)};if(n instanceof y)return bt(n);if(n instanceof R){if(n.carrier)return{type:"typed",carrier:n.carrier,value:be(n.carrier,n.lexical??String(n.value))};let e=n.value;if(typeof e=="string")return{type:"string",value:e};if(typeof e=="number")return{type:"number",value:St(e)};if(typeof e=="boolean")return{type:"boolean",value:e}}if(n instanceof ye)return{type:"embedded",statements:Ve(n.statement)};throw new Error(`canonicalForm: list item of unrecognized kind (${n.constructor?.name??typeof n}); add canonicalization support before hashing data that contains it`)}function co(n,e){switch(e.type){case"string":return{predicate:n,type:"string",value:e.value};case"number":return{predicate:n,type:"number",value:e.value};case"boolean":return{predicate:n,type:"boolean",value:e.value};case"typed":return{predicate:n,type:"typed",carrier:e.carrier,value:e.value};case"ref":return{predicate:n,type:"ref",value:e.value};case"embedded":return e.name!==void 0?{predicate:n,type:"embedded",name:e.name,statements:e.statements}:{predicate:n,type:"embedded",statements:e.statements};case"list":return{predicate:n,type:"list",items:e.items}}}function lo(n){let e=n.predicate;if(e)return wt(e.subject)}function uo(n){let e=n.namespace??"",t=n.name??"";return`${e}/${t}`}function Pt(n){return wt(n.subject)}function wt(n){let e=n.version;return e&&typeof e.major=="number"?`${n.publisher}/${n.package_}@${e.major}.${e.minor}.${e.patch}/${n.name}`:`${n.publisher}/${n.package_}/${n.name}`}function St(n){if(Number.isNaN(n))throw new Error("canonicalForm: NaN cannot be canonicalized");if(!Number.isFinite(n))throw new Error("canonicalForm: \xB1Infinity cannot be canonicalized");return Object.is(n,-0)?"0":String(n)}import{VersionOperator as Ct}from"@kanonak-protocol/types/document/models/enums";var po="0.0.0",w=class{constructor(e,t=new C,r){this.repository=e;this.parser=t;this.objectParser=r??new j(this.parser)}repository;parser;objectParser;imports(){return new U}serializeValue(e,t){return xt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),r=await this.hashBody(e.publisher,t,e.body),o=Oe(r),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=r),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:Et(s),contentHash:r,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),r={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),r[e.contentHashProperty]=o),Object.assign(r,e.header??{}),r.imports=t;let a={[e.name]:r,...e.body},i=this.dump(a),s={yaml:i,byteCount:Et(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return Be.dump(e,{lineWidth:-1})}async hashBody(e,t,r){let o={[Rt]:{type:"EphemeralPackage",publisher:e,imports:t},...r},a=this.parser.parse(Be.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new He(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==Rt);for(let u of c)u.namespace="ephemeral";return se(c)}},Rt="__pkgbuilder_probe__";function Et(n){return new TextEncoder().encode(n).length}function Oe(n){let e="sha256:",t=n.startsWith(e)?e.length:0;return`q-${n.slice(t,t+16)}`}var U=class{byKey=new Map;aliases=new Set;ensure(e,t,r,o,a=Ct.Major){let i=`${e}/${t}@${r}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:r,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,h(e.version),e.package_)}.${e.name}`}refLatest(e,t,r,o){return`${this.ensure(e,t,po,o??t,Ct.Any)}.${r}`}toImports(){let e=new Map;for(let r of this.byKey.values()){let o=e.get(r.publisher)??[];o.push(r),e.set(r.publisher,o)}return[...e.keys()].sort().map(r=>({publisher:r,packages:e.get(r).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:fe(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=L(e)||"pkg",r=t,o=2;for(;this.aliases.has(r);)r=`${t}${o++}`;return this.aliases.add(r),r}};function xt(n,e){if(n!=null){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(n instanceof p)return e.ref(n.subject);if(Array.isArray(n)){let t=n.map(r=>xt(r,e)).filter(r=>r!==void 0);return t.length>0?t:void 0}if(n instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(mo(n))throw new Error(`Value produced a bare URI without a version (${n.publisher}/${n.package_}/${n.name}); cannot serialize it as a reference.`)}}function L(n){return n.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function mo(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}var ce=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(r=>r.canProduce(e,t))}async produceCached(e,t,r,o){let a=`${t}/${r}@${h(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,r,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let r=this.producerFor(e,t.packageName);if(!r)return null;let o={operator:t.versionOperator,version:t.version},a=await r.resolveVersion(e,t.packageName,o);return a?this.produceCached(r,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=we(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let r=this.producerFor(t.publisher,t.package_);return r?this.produceCached(r,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(r=>{let o=r.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ne={async authorize(){return{allowed:!0}}},De={async record(){}},F=class extends Error{constructor(t,r){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${r?`: ${r}`:""}`);this.address=t;this.reason=r;this.name="EntitlementDeniedError"}address;reason},le=class{inner;ctx;policy;meter;constructor(e,t,r=Ne,o=De){this.inner=e,this.ctx=t,this.policy=r,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,r){return await this.assertAllowed({publisher:e,package_:t,version:r.version}),this.inner.resolveVersion(e,t,r)}async produce(e,t,r){let o={publisher:e,package_:t,version:r};await this.assertAllowed(o);let a=await this.inner.produce(e,t,r);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new F(e,t.reason)}};var m="kanonak.org",g="view",It="core-kanonak",fo={publisher:m,package_:g,name:"rootView"},yo={publisher:m,package_:g,name:"bind"},go={publisher:m,package_:g,name:"produces"},ko={publisher:m,package_:g,name:"projections"},ho={publisher:m,package_:g,name:"where"},bo={publisher:m,package_:g,name:"value"},Po={publisher:m,package_:g,name:"as"},ue=class{constructor(e,t=new C){this.repository=e;this.parser=t;this.objectParser=new j(this.parser),this.builder=new w(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let r=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(r,e),a=A(o,yo);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=A(o,go);if(!i)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=wo(o),c=vt(r,m,It),u=vt(r,m,g),d=this.builder.imports(),pe=d.ensure(m,It,c,"ck"),$t=d.ensure(m,g,u,"v"),jt=d.ref(i),At=new Ge(this.repository,this.parser,this.objectParser),Te=new ze(At,r),Vt=this.readProjections(r,o),Bt=Ro(o,ho),Ot=this.findInstances(r,a,await this.reason(t)),_e={},Nt=new Set;for(let M of Ot){if(!await this.passesWhere(Te,r,Bt,M))continue;let me={type:jt};for(let Le of Vt){let Dt=await this.evaluateValue(Te,r,Le.value,M),Fe=this.builder.serializeValue(Kt(Dt),d);Fe!==void 0&&(me[d.ref(Le.as)]=Fe)}let Ue=k(M);Ue&&(me[`${$t}.derivedFrom`]=d.ref(Ue)),_e[this.rowName(M,Nt)]=me}let de={};t.resolvedAt&&(de[`${pe}.resolvedAt`]=t.resolvedAt),t.invocationId&&(de[`${pe}.id`]=t.invocationId);let S=await this.builder.buildContentAddressed({publisher:s,book:d,body:_e,contentHashProperty:`${pe}.contentHash`,header:de});return{yaml:S.yaml,contentHash:S.contentHash,packageName:S.packageName,publisher:S.publisher,rowCount:S.resourceCount}}resolveView(e,t){let r=W(e,t);if(!r)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=A(r,fo);if(o){let a=W(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return r}readProjections(e,t){let r=[];for(let o of Ce(t,ko)){let a=o instanceof y?o:o instanceof p?W(e,o.subject):void 0;if(!a)continue;let i=Se(a,bo),s=A(a,Po);i&&s&&r.push({value:i,as:s})}return r}async reason(e){return new Pe({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,r){let o=Co(e),a=[],i=new Set;for(let s of r.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=$(k(s)),d=$(k(c));return u<d?-1:u>d?1:0}),a}async passesWhere(e,t,r,o){for(let a of r){let i=await this.evaluateValue(e,t,a,o);if(!Eo(i))return!1}return!0}async evaluateValue(e,t,r,o){let a=We(r,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let r=L(e.name)||"row",o=r,a=2;for(;t.has(o);)o=`${r}-${a++}`;return t.add(o),o}};function Kt(n){return Re(n)?n.value:Array.isArray(n)?n.map(Kt):n}function wo(n){let e=k(n);if(!e)throw new Error(`Could not derive a publisher from view ${n.namespace}/${n.name}.`);return e.publisher}function vt(n,e,t){let r=So(n,e,t);if(!r)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return r}function So(n,e,t){let r;for(let o of n){if(!(o instanceof f))continue;let a=k(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!r||H(a.version,r)>0)&&(r=a.version)}return r?h(r):void 0}function Co(n){let e=new Map,t=new Map;for(let r of n){if(!(r instanceof f))continue;let o=k(r);if(!o||!o.version)continue;let a=$(o),i=t.get(a);(!i||H(o.version,i)>0)&&(t.set(a,o.version),e.set(a,r))}return e}function Ro(n,e){let t=Se(n,e);return t?[t]:Ce(n,e).filter(r=>r instanceof y)}function Eo(n){return n===!0?!0:n===!1||n===void 0||n===null?!1:typeof n=="string"?n.length>0:typeof n=="number"?n!==0:Re(n)?n.value.length>0:Array.isArray(n)?n.length>0:!!n}export{lr as AmbiguousReferenceRule,he as BooleanStatement,kt as CANONICAL_FORM_VERSION,Me as Carrier,yr as ClassDefinitionRule,er as ClassHierarchyCycleRule,Jt as CompositeKanonakDocumentRepository,ie as CredentialStore,ye as DefinedKanonak,sr as DefinitionPropertyReferenceRule,Gt as DocumentLocation,Sn as EdgeType,y as EmbeddedKanonak,Zn as EmbeddedKanonakTypeRule,I as EmbeddedStatement,F as EntitlementDeniedError,le as EntitlementProducer,Wt as FileSystemKanonakDocumentRepository,vn as GitIgnoreFilter,Cn as GraphBuilder,rn as HttpKanonakDocumentRepository,U as ImportBook,Xn as ImportExistenceRule,zt as InMemoryKanonakDocumentRepository,Zt as KANONAK_USER_AGENT,ln as Kanonak,$n as KanonakDocumentPositions,j as KanonakObjectParser,kr as KanonakObjectValidator,C as KanonakParser,z as KanonakUri,Vn as KanonakUriBuilder,On as KanonakUrlResolver,kn as KanonakVocabulary,v as ListStatement,R as LiteralKanonak,on as LocalFirstRepository,an as LockAwareRepository,Pr as LookRenderer,gr as MarkdownLinkRule,pn as MarkdownStatement,ar as NamespaceImportCycleRule,Wn as NamespacePrefixRule,wn as NodeType,ke as NumberStatement,xn as OWL_RL_CLASSIFICATION_RULES,pr as ObjectPropertyImportRule,dr as ObjectPropertyValueValidationRule,Mn as OntologyValidationError,Ln as OntologyValidationResult,w as PackageBuilder,Yn as PackageHeaderRule,ce as ProducerRepository,mr as PropertyDomainRule,tr as PropertyHierarchyCycleRule,Kn as PropertyMetadata,ur as PropertyRangeReferenceRule,nr as PropertyRangeRequiredRule,Jn as PropertyTypeSpecificityRule,fr as PropertyValueTypeRule,en as PublisherConfigResolver,tn as PublisherIndex,En as RDFS_RULES,Pe as Reasoner,In as ReasoningResult,p as ReferenceKanonak,x as ReferenceStatement,Yt as RepositoryFactory,Gn as ResourceNamingRule,dn as ResourceResolver,Pn as ResourceTypeClassifier,ge as ScalarStatement,un as Statement,E as StringStatement,rr as SubClassOfReferenceRule,or as SubPropertyOfReferenceRule,f as SubjectKanonak,qn as SubjectKanonakTypeRequiredRule,Rn as TripleStore,mn as TypeResolver,ir as UnresolvedPredicateRule,Qn as UnresolvedReferenceRule,zn as ValidationCache,Hn as ValidationContext,Fn as ValidationSeverity,Fi as VersionOperator,ue as ViewMaterializer,cr as XsdImportRule,Ne as allowAllPolicy,nn as assertPackageIdentity,cn as buildLocalFirstRepository,wr as buildOntologyModel,Ae as canonicalForm,se as canonicalHash,K as carrierOf,sn as collectKanonakFiles,H as compareVersions,dt as computeIntegrity,Oe as contentAddressedName,_n as contextTypesOf,st as createAuthenticatedFetch,_ as createDPoPProof,Ut as createVersion,bn as extractMarkdownLinks,hr as findDerivation,Un as findInstancesByType,hn as findMalformedReferences,An as findMarkdownLinkAt,Bn as formatKanonakAddress,h as formatVersion,at as generateDPoPKeyPair,qt as getGlobalCachePath,Qt as getKanonakUserAgent,J as hasValidToken,Ft as isCompatibleVersion,G as isExpired,Mt as isMajorCompatible,b as kanonakFetch,ut as loadLockFile,fn as makeUriKey,De as noopMeter,l as normalizeHost,we as parseKanonakAddress,Lt as parseVersionString,jn as parseWithPositions,Ht as pickHighestDocument,Dn as propertiesInScope,br as resolveDisplayValue,Tn as resolvePropertyStep,L as sanitizeName,pt as saveLockFile,it as serverSupportsDPoP,Xt as setKanonakUserAgent,k as subjectUri,Nn as superClassChain,yn as tripleKey,$ as uriKey,gn as uriTriple,Tt as versionOperatorFromChar,fe as versionOperatorToChar,_t as versionsEqual};
|
|
93
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`)}}async store(e,t){let n=l(e);try{await this.runHelper("store",{publisher:n,credential:t})}catch(o){throw new Error(`Credential helper '${this.helperPath}' failed to store credential for '${n}': ${Q(o)}
|
|
94
|
+
Verify the helper binary supports the 'store' action.`)}}async remove(e){let t=l(e);try{await this.runHelper("erase",{publisher:t})}catch(n){console.warn(` Warning: Credential helper '${this.helperPath}' failed to erase credential for '${t}': ${Q(n)}`)}}async list(){try{let e=await this.runHelper("list",void 0);return JSON.parse(e.trim())}catch(e){return console.warn(` Warning: Credential helper '${this.helperPath}' failed to list credentials: ${Q(e)}`),[]}}async runHelper(e,t){try{let{stdout:n}=await $n(this.helperPath,[e],{...t&&{input:JSON.stringify(t)},timeout:Qe});return n}catch(n){throw jn(n)?new Error(`Credential helper not found at '${this.helperPath}'.
|
|
95
|
+
Check the 'credentialHelper' path in ~/.kanonak/config.json.`):An(n)?new Error(`Credential helper '${this.helperPath}' timed out after ${Qe/1e3}s on '${e}'.
|
|
96
|
+
The helper may be waiting for authentication to an external vault.`):n}}};function Q(r){return r instanceof Error?r.message:String(r)}function jn(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}function An(r){return r instanceof Error&&"killed"in r&&r.killed}var Ie=Tn(Dn(),".kanonak","config.json"),ee=class{backend=null;backendReady=null;async getBackend(){if(this.backend)return this.backend;if(this.backendReady)return this.backendReady;this.backendReady=this.resolveBackend();try{return this.backend=await this.backendReady,this.backend}catch(e){throw this.backendReady=null,e}}async getToken(e){let t=Nn(e);if(t)return t;let o=await(await this.getBackend()).get(e);return!o||!F(o)?null:o.accessToken??null}async getCredential(e){return(await this.getBackend()).get(e)}async store(e,t){return(await this.getBackend()).store(e,t)}async remove(e){return(await this.getBackend()).remove(e)}async list(){return(await this.getBackend()).list()}async resolveBackend(){let e=Bn();return e.credentialHelper?new A(e.credentialHelper):process.platform==="darwin"?new I:process.platform==="win32"?new v:await Se()?new K:new j}};function Nn(r){let t="KANONAK_TOKEN_"+l(r).replace(/[.\-]/g,"_").toUpperCase();return process.env[t]??null}function Bn(){if(!Vn(Ie))return{};try{return JSON.parse(On(Ie,"utf-8"))}catch(r){let e=r instanceof Error?r.message:String(r);return console.warn(` Warning: Failed to parse ${Ie}: ${e}
|
|
97
|
+
Using default credential backend. Fix the JSON syntax or delete the file.`),{}}}import{createHash as Un,createPrivateKey as _n,generateKeyPairSync as Ln,randomUUID as Fn,sign as Mn}from"crypto";function tt(){let{publicKey:r,privateKey:e}=Ln("ec",{namedCurve:"P-256"});return{publicKey:r.export({format:"jwk"}),privateKey:e.export({format:"jwk"})}}function V(r,e,t,n,o,a){let i={alg:"ES256",typ:"dpop+jwt",jwk:{kty:e.kty,crv:e.crv,x:e.x,y:e.y}},s={jti:Fn(),htm:t.toUpperCase(),htu:n,iat:Math.floor(Date.now()/1e3)};return o&&(s.ath=Un("sha256").update(o).digest("base64url")),a&&(s.nonce=a),Hn(i,s,r)}function rt(r){return!r||r.length===0?!1:r.some(e=>e.toUpperCase()==="ES256")}function Hn(r,e,t){let n=et(JSON.stringify(r)),o=et(JSON.stringify(e)),a=`${n}.${o}`,i=_n({key:t,format:"jwk"}),c=Mn("SHA256",Buffer.from(a),{key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${a}.${c}`}function et(r){return Buffer.from(r,"utf-8").toString("base64url")}function nt(r){let e=new Map;return async(t,n,o="GET")=>{if(!r)return b(t,{method:o});let a=await r.getCredential(n);if(!a?.accessToken)return b(t,{method:o});L(a)&&console.warn(` Warning: Access token for '${n}' is expired. Run 'kanonak login ${n}' to re-authenticate.`);let i={};if(a.dpopKeyPair){let c=e.get(n);try{let u=V(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.Authorization=`DPoP ${a.accessToken}`,i.DPoP=u}catch(u){let p=u instanceof Error?u.message:String(u);console.error(` Error: Failed to create DPoP proof for '${n}': ${p}
|
|
98
|
+
The stored key pair may be corrupted. Run 'kanonak login ${n}' to re-authenticate.`),i.Authorization=`Bearer ${a.accessToken}`}}else i.Authorization=`Bearer ${a.accessToken}`;let s=await b(t,{method:o,headers:i});if(s.status===401&&a.dpopKeyPair){let c=s.headers.get("DPoP-Nonce");if(c){e.set(n,c);try{let u=V(a.dpopKeyPair.privateKey,a.dpopKeyPair.publicKey,o,t,a.accessToken,c);i.DPoP=u,s=await b(t,{method:o,headers:i})}catch{}}}return s}}import{readFileSync as zn,writeFileSync as Wn,existsSync as Gn}from"fs";import{createHash as Jn}from"crypto";import ot from"js-yaml";var at="kanonak.lock",qn=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
99
|
+
`;function it(r=at){if(!Gn(r))return null;let e=zn(r,"utf-8"),t=ot.load(e);return!t||typeof t!="object"||t.version!=="1"?null:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),packages:t.packages??{}}}function st(r,e=at){r.lastUpdated=new Date().toISOString();let t={};for(let o of Object.keys(r.packages).sort())t[o]=r.packages[o];r.packages=t;let n=ot.dump(r,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Wn(e,qn+n,"utf-8")}function ct(r){return`sha256:${Jn("sha256").update(r).digest("hex")}`}import*as $e from"js-yaml";import{canonicalForm as Yn,canonicalHash as Zn}from"@kanonak-protocol/canonical";function ve(r){return typeof r=="object"&&r!==null&&Array.isArray(r.subjects)}import{CANONICAL_FORM_VERSION as yt}from"@kanonak-protocol/canonical";function lt(r){return Yn(ve(r)?r:ut(r))}function te(r){return Zn(ve(r)?r:ut(r))}function ut(r){let e=[];for(let t of r)t instanceof f&&e.push({uri:to(t),statements:Ke(t.statement)});return{subjects:e}}function Ke(r){let e=[];for(let t of r){let n=eo(t);if(!n)continue;let o=Xn(t);o&&e.push({predicate:n,value:o})}return e}function Xn(r){if(r instanceof pe&&r.carrier)return{lit:r.lexical??String(r.object),datatype:dt(r.carrier)};if(r instanceof de)return{raw:r.object};if(r instanceof me)return{raw:r.lexical??String(r.object)};if(r instanceof fe)return{raw:r.lexical??String(r.object)};if(r instanceof ye)return{ref:mt(r.object)};if(r instanceof ge)return pt(r.object);if(r instanceof ke)return{list:r.object.map(Qn)}}function pt(r){let e=Ke(r.statement);return r.name&&r.name.length>0?{embed:{name:r.name,statements:e}}:{embed:{statements:e}}}function Qn(r){if(r instanceof h)return{ref:mt(r)};if(r instanceof y)return pt(r);if(r instanceof ue){if(r.carrier)return{lit:r.lexical??String(r.value),datatype:dt(r.carrier)};let e=r.value;if(typeof e=="string")return{raw:e};if(typeof e=="number")return{raw:String(e)};if(typeof e=="boolean")return{raw:String(e)}}if(r instanceof le)return{embed:{statements:Ke(r.statement)}};throw new Error(`canonicalForm: list item of unrecognized kind (${r.constructor?.name??typeof r}); add canonicalization support before hashing data that contains it`)}function dt(r){return r===U.LangString?"kanonak.org/core-rdf/langString":`kanonak.org/core-xsd/${r}`}function eo(r){let e=r.predicate;if(e)return ft(e.subject)}function to(r){let e=r.namespace??"",t=r.name??"";return`${e}/${t}`}function mt(r){return ft(r.subject)}function ft(r){let e=r.version;return e&&typeof e.major=="number"?`${r.publisher}/${r.package_}@${e.major}.${e.minor}.${e.patch}/${r.name}`:`${r.publisher}/${r.package_}/${r.name}`}import{VersionOperator as gt}from"@kanonak-protocol/types/document/models/enums";var ro="0.0.0",w=class{constructor(e,t=new S,n){this.repository=e;this.parser=t;this.objectParser=n??new E(this.parser)}repository;parser;objectParser;imports(){return new O}serializeValue(e,t){return bt(e,t)}async buildContentAddressed(e){let t=e.book.toImports(),n=await this.hashBody(e.publisher,t,e.body),o=je(n),a={type:"EphemeralPackage",publisher:e.publisher,imports:t};e.contentHashProperty&&(a[e.contentHashProperty]=n),Object.assign(a,e.header??{}),a.imports=t;let i={[o]:a,...e.body},s=this.dump(i);return{yaml:s,byteCount:ht(s),contentHash:n,packageName:o,publisher:e.publisher,resourceCount:Object.keys(e.body).length}}async buildNamed(e){let t=e.book.toImports(),n={type:e.type??"Package",publisher:e.publisher,version:e.version,imports:t},o;e.contentHashProperty&&(o=await this.hashBody(e.publisher,t,e.body),n[e.contentHashProperty]=o),Object.assign(n,e.header??{}),n.imports=t;let a={[e.name]:n,...e.body},i=this.dump(a),s={yaml:i,byteCount:ht(i),packageName:e.name,publisher:e.publisher,resourceCount:Object.keys(e.body).length};return o!==void 0&&(s.contentHash=o),s}dump(e){return $e.dump(e,{lineWidth:-1})}async hashBody(e,t,n){let o={[kt]:{type:"EphemeralPackage",publisher:e,imports:t},...n},a=this.parser.parse($e.dump(o,{lineWidth:-1})),i=a.metadata.namespace_?.toString(),c=(await this.objectParser.parseKanonaks(new _e(a,this.repository))).filter(u=>u instanceof f&&u.namespace===i&&u.name!==kt);for(let u of c)u.namespace="ephemeral";return te(c)}},kt="__pkgbuilder_probe__";function ht(r){return new TextEncoder().encode(r).length}function je(r){let e="sha256:",t=r.startsWith(e)?e.length:0;return`q-${r.slice(t,t+16)}`}var O=class{byKey=new Map;aliases=new Set;ensure(e,t,n,o,a=gt.Major){let i=`${e}/${t}@${n}`,s=this.byKey.get(i);if(s)return s.alias;let c=this.uniqueAlias(o);return this.byKey.set(i,{publisher:e,package_:t,version:n,alias:c,match:a}),c}ref(e){if(!e.version||typeof e.version.major!="number")throw new Error(`Cannot serialize a reference to ${e.publisher}/${e.package_}/${e.name} without a version.`);return`${this.ensure(e.publisher,e.package_,k(e.version),e.package_)}.${e.name}`}refLatest(e,t,n,o){return`${this.ensure(e,t,ro,o??t,gt.Any)}.${n}`}toImports(){let e=new Map;for(let n of this.byKey.values()){let o=e.get(n.publisher)??[];o.push(n),e.set(n.publisher,o)}return[...e.keys()].sort().map(n=>({publisher:n,packages:e.get(n).sort((o,a)=>o.package_<a.package_?-1:1).map(o=>({package:o.package_,match:ce(o.match),version:o.version,alias:o.alias}))}))}uniqueAlias(e){let t=D(e)||"pkg",n=t,o=2;for(;this.aliases.has(n);)n=`${t}${o++}`;return this.aliases.add(n),n}};function bt(r,e){if(r!=null){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(r instanceof h)return e.ref(r.subject);if(Array.isArray(r)){let t=r.map(n=>bt(n,e)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(r instanceof y)throw new Error("Embedded values are not yet supported by PackageBuilder. Produce a literal or a reference, or compose the embedded shape into the output class.");if(no(r))throw new Error(`Value produced a bare URI without a version (${r.publisher}/${r.package_}/${r.name}); cannot serialize it as a reference.`)}}function D(r){return r.replace(/[^A-Za-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function no(r){return typeof r=="object"&&r!==null&&typeof r.publisher=="string"&&typeof r.package_=="string"&&typeof r.name=="string"}var re=class{constructor(e){this.producers=e}producers;produced=new Map;producerFor(e,t){return this.producers.find(n=>n.canProduce(e,t))}async produceCached(e,t,n,o){let a=`${t}/${n}@${k(o)}`,i=this.produced.get(a);if(i)return i;let{document:s}=await e.produce(t,n,o);return this.produced.set(a,s),s}async getHighestCompatibleVersionAsync(e,t){let n=this.producerFor(e,t.packageName);if(!n)return null;let o={operator:t.versionOperator,version:t.version},a=await n.resolveVersion(e,t.packageName,o);return a?this.produceCached(n,e,t.packageName,a):null}async getDocumentAsync(e){let t;try{t=be(e)}catch{return null}if(t.kind!=="package"||!t.version)return null;let n=this.producerFor(t.publisher,t.package_);return n?this.produceCached(n,t.publisher,t.package_,t.version):null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.produced.values()).filter(n=>{let o=n.metadata.namespace_;return o!=null&&o.publisher===e&&o.package_===t})}async getAllDocumentsAsync(){return Array.from(this.produced.values())}async saveDocumentAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async deleteDocumentAsync(e){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async clearNamespaceAsync(e,t){throw new Error("ProducerRepository is read-only: a producer is a source, not a store.")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return null}async getDocumentUriAsync(e){return null}};var Ae={async authorize(){return{allowed:!0}}},Ve={async record(){}},T=class extends Error{constructor(t,n){let o=`${t.publisher}/${t.package_}${t.version?`@${t.version.major}.${t.version.minor}.${t.version.patch}`:""}`;super(`Not entitled to produce ${o}${n?`: ${n}`:""}`);this.address=t;this.reason=n;this.name="EntitlementDeniedError"}address;reason},ne=class{inner;ctx;policy;meter;constructor(e,t,n=Ae,o=Ve){this.inner=e,this.ctx=t,this.policy=n,this.meter=o}canProduce(e,t){return this.inner.canProduce(e,t)}async resolveVersion(e,t,n){return await this.assertAllowed({publisher:e,package_:t,version:n.version}),this.inner.resolveVersion(e,t,n)}async produce(e,t,n){let o={publisher:e,package_:t,version:n};await this.assertAllowed(o);let a=await this.inner.produce(e,t,n);return await this.meter.record(this.ctx,o,a),a}async assertAllowed(e){let t=await this.policy.authorize(this.ctx,e);if(!t.allowed)throw new T(e,t.reason)}};var d="kanonak.org",m="view",Pt="core-kanonak",oo={publisher:d,package_:m,name:"rootView"},ao={publisher:d,package_:m,name:"bind"},io={publisher:d,package_:m,name:"produces"},so={publisher:d,package_:m,name:"projections"},co={publisher:d,package_:m,name:"where"},lo={publisher:d,package_:m,name:"value"},uo={publisher:d,package_:m,name:"as"},oe=class{constructor(e,t=new S){this.repository=e;this.parser=t;this.objectParser=new E(this.parser),this.builder=new w(this.repository,this.parser,this.objectParser)}repository;parser;objectParser;builder;async materialize(e,t={}){let n=await this.objectParser.parseKanonaks(this.repository),o=this.resolveView(n,e),a=x(o,ao);if(!a)throw new Error(`View ${o.namespace}/${o.name} declares no view.bind; cannot materialize.`);let i=x(o,io);if(!i)throw new Error(`View ${o.namespace}/${o.name} is a selection view (no view.produces). In-graph materialization of selection views is not yet supported \u2014 declare a view.produces output class to reshape the result.`);let s=po(o),c=wt(n,d,Pt),u=wt(n,d,m),p=this.builder.imports(),ae=p.ensure(d,Pt,c,"ck"),St=p.ensure(d,m,u,"v"),Rt=p.ref(i),Et=new Me(this.repository,this.parser,this.objectParser),Oe=new Le(Et,n),xt=this.readProjections(n,o),It=yo(o,co),vt=this.findInstances(n,a,await this.reason(t)),De={},Kt=new Set;for(let N of vt){if(!await this.passesWhere(Oe,n,It,N))continue;let se={type:Rt};for(let Ne of xt){let $t=await this.evaluateValue(Oe,n,Ne.value,N),Be=this.builder.serializeValue(Ct($t),p);Be!==void 0&&(se[p.ref(Ne.as)]=Be)}let Te=g(N);Te&&(se[`${St}.derivedFrom`]=p.ref(Te)),De[this.rowName(N,Kt)]=se}let ie={};t.resolvedAt&&(ie[`${ae}.resolvedAt`]=t.resolvedAt),t.invocationId&&(ie[`${ae}.id`]=t.invocationId);let C=await this.builder.buildContentAddressed({publisher:s,book:p,body:De,contentHashProperty:`${ae}.contentHash`,header:ie});return{yaml:C.yaml,contentHash:C.contentHash,packageName:C.packageName,publisher:C.publisher,rowCount:C.resourceCount}}resolveView(e,t){let n=_(e,t);if(!n)throw new Error(`View ${t.publisher}/${t.package_}/${t.name} not found in the catalog.`);let o=x(n,oo);if(o){let a=_(e,o);if(!a)throw new Error(`ViewPackage ${t.name} names rootView ${o.name}, which is not in the catalog.`);return a}return n}readProjections(e,t){let n=[];for(let o of we(t,so)){let a=o instanceof y?o:o instanceof h?_(e,o.subject):void 0;if(!a)continue;let i=Pe(a,lo),s=x(a,uo);i&&s&&n.push({value:i,as:s})}return n}async reason(e){return new he({profile:e.reasoningProfile??"owl-rl-classification"}).reason(this.repository)}findInstances(e,t,n){let o=fo(e),a=[],i=new Set;for(let s of n.getInstancesOfClass(t)){if(i.has(s))continue;i.add(s);let c=o.get(s);c&&a.push(c)}return a.sort((s,c)=>{let u=R(g(s)),p=R(g(c));return u<p?-1:u>p?1:0}),a}async passesWhere(e,t,n,o){for(let a of n){let i=await this.evaluateValue(e,t,a,o);if(!go(i))return!1}return!0}async evaluateValue(e,t,n,o){let a=Fe(n,"view-projection",{catalog:t,depth:0}),i=new Map([["input",o]]);return e.evaluate(a,i)}rowName(e,t){let n=D(e.name)||"row",o=n,a=2;for(;t.has(o);)o=`${n}-${a++}`;return t.add(o),o}};function Ct(r){return Ce(r)?r.value:Array.isArray(r)?r.map(Ct):r}function po(r){let e=g(r);if(!e)throw new Error(`Could not derive a publisher from view ${r.namespace}/${r.name}.`);return e.publisher}function wt(r,e,t){let n=mo(r,e,t);if(!n)throw new Error(`Package ${e}/${t} is not in the catalog; it must be importable to materialize a view.`);return n}function mo(r,e,t){let n;for(let o of r){if(!(o instanceof f))continue;let a=g(o);!a||a.publisher!==e||a.package_!==t||!a.version||(!n||B(a.version,n)>0)&&(n=a.version)}return n?k(n):void 0}function fo(r){let e=new Map,t=new Map;for(let n of r){if(!(n instanceof f))continue;let o=g(n);if(!o||!o.version)continue;let a=R(o),i=t.get(a);(!i||B(o.version,i)>0)&&(t.set(a,o.version),e.set(a,n))}return e}function yo(r,e){let t=Pe(r,e);return t?[t]:we(r,e).filter(n=>n instanceof y)}function go(r){return r===!0?!0:r===!1||r===void 0||r===null?!1:typeof r=="string"?r.length>0:typeof r=="number"?r!==0:Ce(r)?r.value.length>0:Array.isArray(r)?r.length>0:!!r}export{rn as AmbiguousReferenceRule,fe as BooleanStatement,yt as CANONICAL_FORM_VERSION,U as Carrier,ln as ClassDefinitionRule,Gr as ClassHierarchyCycleRule,Lt as CompositeKanonakDocumentRepository,ee as CredentialStore,le as DefinedKanonak,en as DefinitionPropertyReferenceRule,_t as DocumentLocation,yr as EdgeType,y as EmbeddedKanonak,Hr as EmbeddedKanonakTypeRule,ge as EmbeddedStatement,T as EntitlementDeniedError,ne as EntitlementProducer,Ut as FileSystemKanonakDocumentRepository,wr as GitIgnoreFilter,gr as GraphBuilder,Yt as HttpKanonakDocumentRepository,O as ImportBook,zr as ImportExistenceRule,Bt as InMemoryKanonakDocumentRepository,Ht as KANONAK_USER_AGENT,tr as Kanonak,Sr as KanonakDocumentPositions,E as KanonakObjectParser,pn as KanonakObjectValidator,S as KanonakParser,rr as KanonakUri,xr as KanonakUriBuilder,vr as KanonakUrlResolver,ur as KanonakVocabulary,ke as ListStatement,ue as LiteralKanonak,Zt as LocalFirstRepository,Xt as LockAwareRepository,fn as LookRenderer,un as MarkdownLinkRule,or as MarkdownStatement,Xr as NamespaceImportCycleRule,Ur as NamespacePrefixRule,fr as NodeType,me as NumberStatement,br as OWL_RL_CLASSIFICATION_RULES,on as ObjectPropertyImportRule,an as ObjectPropertyValueValidationRule,Tr as OntologyValidationError,Or as OntologyValidationResult,w as PackageBuilder,Mr as PackageHeaderRule,re as ProducerRepository,sn as PropertyDomainRule,Jr as PropertyHierarchyCycleRule,Cr as PropertyMetadata,nn as PropertyRangeReferenceRule,qr as PropertyRangeRequiredRule,Lr as PropertyTypeSpecificityRule,cn as PropertyValueTypeRule,Gt as PublisherConfigResolver,Jt as PublisherIndex,hr as RDFS_RULES,he as Reasoner,Pr as ReasoningResult,h as ReferenceKanonak,ye as ReferenceStatement,Mt as RepositoryFactory,_r as ResourceNamingRule,ar as ResourceResolver,mr as ResourceTypeClassifier,pe as ScalarStatement,nr as Statement,de as StringStatement,Yr as SubClassOfReferenceRule,Zr as SubPropertyOfReferenceRule,f as SubjectKanonak,Fr as SubjectKanonakTypeRequiredRule,kr as TripleStore,ir as TypeResolver,Qr as UnresolvedPredicateRule,Wr as UnresolvedReferenceRule,Br as ValidationCache,Nr as ValidationContext,Dr as ValidationSeverity,Si as VersionOperator,oe as ViewMaterializer,tn as XsdImportRule,Ae as allowAllPolicy,qt as assertPackageIdentity,er as buildLocalFirstRepository,yn as buildOntologyModel,lt as canonicalForm,te as canonicalHash,Ue as carrierOf,Qt as collectKanonakFiles,B as compareVersions,ct as computeIntegrity,je as contentAddressedName,Ar as contextTypesOf,nt as createAuthenticatedFetch,V as createDPoPProof,Vt as createVersion,dr as extractMarkdownLinks,dn as findDerivation,Vr as findInstancesByType,pr as findMalformedReferences,Er as findMarkdownLinkAt,Ir as formatKanonakAddress,k as formatVersion,tt as generateDPoPKeyPair,Ft as getGlobalCachePath,Wt as getKanonakUserAgent,F as hasValidToken,Dt as isCompatibleVersion,L as isExpired,Tt as isMajorCompatible,b as kanonakFetch,it as loadLockFile,sr as makeUriKey,Ve as noopMeter,l as normalizeHost,be as parseKanonakAddress,Ot as parseVersionString,Rr as parseWithPositions,Nt as pickHighestDocument,$r as propertiesInScope,mn as resolveDisplayValue,jr as resolvePropertyStep,D as sanitizeName,st as saveLockFile,rt as serverSupportsDPoP,zt as setKanonakUserAgent,g as subjectUri,Kr as superClassChain,cr as tripleKey,R as uriKey,lr as uriTriple,jt as versionOperatorFromChar,ce as versionOperatorToChar,At as versionsEqual};
|
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-RGOBWOBB.js";import{h as b}from"../chunk-BKVPSPG4.js";import{a}from"../chunk-NJ3AZYQD.js";import"../chunk-7HRKWTBB.js";import"../chunk-4UT2CLAT.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-CR55WXIN.js";import"../chunk-BKVPSPG4.js";import"../chunk-NJ3AZYQD.js";import{d as a,e as b,f as c,h as d,j as e,k as f}from"../chunk-7HRKWTBB.js";import"../chunk-4UT2CLAT.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};
|
package/dist/search/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as g}from"../chunk-
|
|
1
|
+
import{a as g}from"../chunk-V72IVYR4.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-BKVPSPG4.js";import"../chunk-NJ3AZYQD.js";import{d as m,h as S}from"../chunk-IEOSSSB5.js";import{a as p,f as E}from"../chunk-7TKJHKC2.js";import"../chunk-7HRKWTBB.js";import{c as v}from"../chunk-4UT2CLAT.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,4 +1,4 @@
|
|
|
1
|
-
import{j as ee}from"../chunk-E2FCKRB4.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as O,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{i as Q}from"../chunk-MFNVQSBW.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as X}from"../chunk-IEOSSSB5.js";import{g as Z}from"../chunk-7TKJHKC2.js";import"../chunk-7HRKWTBB.js";import{c as be}from"../chunk-4UT2CLAT.js";import"../chunk-FUUTGGJS.js";import{c as M,e as F,f as L,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as De,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";function Se(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function H(t,e){let n=new Set,r=[...t];for(;r.length>0;){let s=r.shift(),a=Se(s);if(!a||n.has(a))continue;n.add(a);let m=s.metadata?.imports;if(m)for(let[p,k]of Object.entries(m))for(let d of k)try{let u=await e.getHighestCompatibleVersionAsync(p,d);u&&r.push(u)}catch{}}return n}var V=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let r=Se(n);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var we=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function T(t){let e=t?.render;if(e&&e.length>0){let n=[];for(let r of e)try{let s=X(r);s.kind==="package"?n.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&n.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(n.length>0)return n}return we}function C(t){return`${t.publisher}/${t.package_}`}function W(t){let e={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},n=[];for(let r of t)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";n.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&n.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return n}function re(t){let{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,renderStack:p,producers:k}=t,d=new Map,u=new Map,o=new Map,h=new Set;for(let y of r){if(!(y instanceof be))continue;let b=y.namespace||"";if(!a.has(b))continue;d.set(`${b}/${y.name}`,y);let $=b.split("/")[1]??"",[w,_]=$.split("@");if(!w||!_)continue;let I=ue(_);I&&(h.has($)||(h.add($),u.has(w)||u.set(w,[]),u.get(w).push({verStr:_,version:I})),y.name===w&&o.set($,y))}for(let y of u.values())y.sort((b,$)=>M($.version,b.version));return{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,bySubject:d,pkgVersions:u,pkgSelfByVer:o,renderStack:p,...k?{producers:k}:{}}}async function se(t,e={}){let n=new E,r=new ge(n),s=[],a=[];for(let c of J(t)){let l;try{l=De(c,"utf-8")}catch{continue}let v;try{v=n.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:F(N),version:N,source:l})}a.sort((c,l)=>M(l.version,c.version));for(let c of a)await r.saveDocumentAsync(n.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),s.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(s.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!m.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)p=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let k=new Set,d=new Map;for(let c of s)c.publisher===p&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),o=new he(u,!0,n),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let y=e.repository??new ye(r,o,new Y(h)),b=e.log??(()=>{}),$=T(void 0),w=[],_=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>M(v,l)).map(F);if(!e.repository){b(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new O({fetchFn:e.fetchFn}):new O;for(let l of $){let v=C(l),N=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(N.length>0){let S=_(N);w.push({...l,origin:"workspace",versions:S}),b(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await o.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=_(U);w.push({...l,origin:"cache",versions:S}),b(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let f=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let j=await c.getPackageUrl(l.publisher,l.package_,S),i=await(e.fetchFn?e.fetchFn(j,l.publisher):me(j));if(!i.ok){let f=`fetch ${j} failed: HTTP ${i.status} ${i.statusText}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let g=await i.text();await r.saveDocumentAsync(n.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let f=$e(u,l.publisher);je(f,{recursive:!0}),_e($e(f,`${l.package_}@${S}.kan.yml`),g,"utf-8"),w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, installed to cache`)}catch(f){w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, but cache ${u} is NOT WRITABLE (${f.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let j=`fetch failed: ${S.message}`;w.push({...l,origin:"missing",reason:j}),b(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let I=y;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await H(c,y);for(let v of $)l.add(C(v));I=new V(y,l)}let B=await new Q(n).parseKanonaks(I),oe=new ee(B),G=(c,l)=>Z(B,{publisher:c,package_:l,name:l}).length>0,A;if(e.repository){A=[];for(let c of $){let l=await y.getDocumentsByNamespaceAsync(c.publisher,c.package_);A.push(l.length>0?{...c,origin:"repository",versions:_(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=w.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=W(A);for(let c of q)b(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:m,catalog:B,lookRenderer:oe,localNamespaces:k,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:A,warnings:q}})}import{existsSync as Ce,readFileSync as Ae,writeFileSync as Ie,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function ae(t,e={}){let n=new E,r=X(t),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),m=e.cacheRoot??z(),p=(i,g,f)=>Re(m,i,`${g}@${f}.kan.yml`),k=new Set,d=new Set,u=new Map,o=new Y({getFromCache:(i,g,f)=>{let D=p(i,g,f),R=Ce(D)?Ae(D,"utf-8"):null;return R!==null&&k.add(`${i}/${g}`),R},onFetch:(i,g,f,D)=>{d.add(`${i}/${g}`);try{let R=Re(m,i);Ne(R,{recursive:!0}),Ie(p(i,g,f),D,"utf-8")}catch(R){u.set(`${i}/${g}`,R.message),a(`[render] fetched ${i}/${g}@${f} but cache ${m} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new O(e.fetchFn?{fetchFn:e.fetchFn}:void 0),y;if(r.kind==="resource"){let i=r.uri.version;y=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;y=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else y=(await h.listLatestPackages(s)).map(g=>({package_:g.packageName}));let b=async(i,g,f)=>{try{let D=f?n.buildImport(g,"=",f,i):n.buildImport(g,"*","0.0.0",i),R=await o.getHighestCompatibleVersionAsync(i,D);return R?{doc:R}:{doc:null,error:`${i} did not resolve ${g}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(D){return{doc:null,error:D.message}}},$=[],w=[];for(let i of y){let{doc:g,error:f}=await b(s,i.package_,i.version);g?$.push(g):f&&w.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${s}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=await new ke(e.fetchFn).getConfig(s).catch(()=>{}),I=T(_),B=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,f)=>M(f,g)).map(F);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${B}); cache: ${m}`);let G=[],A=[];for(let i of I){let g=C(i),{doc:f,error:D}=await b(i.publisher,i.package_,void 0);if(f){G.push(f);let R=oe([f]),pe=d.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...i,origin:pe,versions:R}),a(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...i,origin:"missing",reason:D??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${D??"unresolved"}`)}let q=await H([...$,...G],o),de=new V(o,q),c=await new Q(n).parseKanonaks(de),l=new ee(c),v=A.map(i=>i.origin==="missing"||Z(c,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),N=W(v);for(let i of N)a(`[render-stack] WARNING: ${i}`);let U={contractSource:B,cachePath:m,packages:v,warnings:N},S=new Set,j=new Map;for(let i of await o.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==s)continue;let f=F(g.version),D=`${g.publisher}/${g.package_}@${f}`;S.add(D);let R=await o.getDocumentContentAsync(D);R!==null&&j.set(`${g.package_}@${f}`,R)}return re({publisher:s,availablePublishers:[s],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:j,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:n,renderStack:r,catalog:s}=t,a=e.explainStylesheet(e.publisherSubject(n)),m=[...a.tokens.entries()].map(([o,h])=>({name:o,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,k={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},d=new Map;for(let o of s){let h=o.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([o,h])=>({namespace:o,resources:h})).sort((o,h)=>o.namespace.localeCompare(h.namespace));return{publisher:n,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ie(t){let e=Fe,n=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
|
|
1
|
+
import{j as ee}from"../chunk-V72IVYR4.js";import"../chunk-QHABFCRC.js";import{a as he,d as z,f as ye,h as J}from"../chunk-GMEPM2QQ.js";import{d as me,e as fe,f as ke,g as O,h as Y}from"../chunk-JYBKSBB5.js";import{a as ge}from"../chunk-4NO7MHS7.js";import"../chunk-PEUTCG3B.js";import{a as ve}from"../chunk-PEJALHXK.js";import"../chunk-SC5M74NM.js";import"../chunk-SHDHMKMJ.js";import{h as Q}from"../chunk-BKVPSPG4.js";import{a as E}from"../chunk-NJ3AZYQD.js";import{b as X}from"../chunk-IEOSSSB5.js";import{g as Z}from"../chunk-7TKJHKC2.js";import"../chunk-7HRKWTBB.js";import{c as be}from"../chunk-4UT2CLAT.js";import"../chunk-FUUTGGJS.js";import{c as M,e as F,f as L,g as ue}from"../chunk-2ACBWC7K.js";import{readFileSync as De,writeFileSync as _e,mkdirSync as je}from"fs";import{join as $e}from"path";function Se(t){let e=t.metadata?.namespace_;return e?`${e.publisher}/${e.package_}`:void 0}async function H(t,e){let n=new Set,r=[...t];for(;r.length>0;){let s=r.shift(),a=Se(s);if(!a||n.has(a))continue;n.add(a);let m=s.metadata?.imports;if(m)for(let[p,k]of Object.entries(m))for(let d of k)try{let u=await e.getHighestCompatibleVersionAsync(p,d);u&&r.push(u)}catch{}}return n}var V=class{constructor(e,n){this.inner=e;this.scope=n}inner;scope;async getAllDocumentsAsync(){return(await this.inner.getAllDocumentsAsync()).filter(n=>{let r=Se(n);return r!==void 0&&this.scope.has(r)})}getDocumentAsync(e){return this.inner.getDocumentAsync(e)}getDocumentsByNamespaceAsync(e,n){return this.inner.getDocumentsByNamespaceAsync(e,n)}getHighestCompatibleVersionAsync(e,n){return this.inner.getHighestCompatibleVersionAsync(e,n)}saveDocumentAsync(e,n){return this.inner.saveDocumentAsync(e,n)}deleteDocumentAsync(e){return this.inner.deleteDocumentAsync(e)}clearNamespaceAsync(e,n){return this.inner.clearNamespaceAsync(e,n)}getAllDocumentReferencesAsync(){return this.inner.getAllDocumentReferencesAsync()}getDocumentContentAsync(e){return this.inner.getDocumentContentAsync(e)}getDocumentUriAsync(e){return this.inner.getDocumentUriAsync(e)}};var we=[{publisher:"kanonak.org",package_:"core-kanonak"},{publisher:"kanonak.org",package_:"site"},{publisher:"kanonak.org",package_:"link"},{publisher:"kanonak.org",package_:"look-tokens"},{publisher:"kanonak.org",package_:"look-styles"},{publisher:"kanonak.org",package_:"look"},{publisher:"kanonak.org",package_:"universal-look"}];function T(t){let e=t?.render;if(e&&e.length>0){let n=[];for(let r of e)try{let s=X(r);s.kind==="package"?n.push({publisher:s.publisher,package_:s.package_}):s.kind==="resource"&&n.push({publisher:s.uri.publisher,package_:s.uri.package_})}catch{}if(n.length>0)return n}return we}function C(t){return`${t.publisher}/${t.package_}`}function W(t){let e={"kanonak.org/look-styles":"pages render UNSTYLED \u2014 generated CSS stops at the :root token block","kanonak.org/look-tokens":"the :root block loses the universal design-token floor (colors, fonts, spacing)","kanonak.org/universal-look":"resources without their own look render as an empty HTML comment","kanonak.org/look":"band vocabulary (Hero, PropertyList, \u2026) is unresolvable \u2014 declared looks cannot render","kanonak.org/site":"the site vocabulary (content, navigation) is unresolvable \u2014 the base stylesheet cannot bind","kanonak.org/core-kanonak":"the Package/Publisher classes are unresolvable \u2014 package and publisher pages degrade","kanonak.org/link":"link vocabulary is unresolvable \u2014 cross-reference styling degrades"},n=[];for(let r of t)if(r.origin==="missing"){let s=C(r),a=e[s]??"whatever this package contributes to rendering is lost";n.push(`Render-stack package ${s} is MISSING (${r.reason??"unknown reason"}) \u2014 ${a}. Fix: kanonak install ${s} (as the user running the render), or restore network access to ${r.publisher}.`)}else r.resolvedButNotInCatalog&&n.push(`Render-stack package ${C(r)} resolved (${r.origin}) but is NOT in the parsed catalog \u2014 this is a closure-scoping bug; please report it.`);return n}function re(t){let{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,renderStack:p,producers:k}=t,d=new Map,u=new Map,o=new Map,h=new Set;for(let y of r){if(!(y instanceof be))continue;let b=y.namespace||"";if(!a.has(b))continue;d.set(`${b}/${y.name}`,y);let $=b.split("/")[1]??"",[w,_]=$.split("@");if(!w||!_)continue;let I=ue(_);I&&(h.has($)||(h.add($),u.has(w)||u.set(w,[]),u.get(w).push({verStr:_,version:I})),y.name===w&&o.set($,y))}for(let y of u.values())y.sort((b,$)=>M($.version,b.version));return{publisher:e,availablePublishers:n,catalog:r,lookRenderer:s,localNamespaces:a,rawByNsKey:m,bySubject:d,pkgVersions:u,pkgSelfByVer:o,renderStack:p,...k?{producers:k}:{}}}async function se(t,e={}){let n=new E,r=new ge(n),s=[],a=[];for(let c of J(t)){let l;try{l=De(c,"utf-8")}catch{continue}let v;try{v=n.parse(l).metadata?.namespace_}catch{continue}if(!v?.version)continue;let N=v.version;a.push({publisher:v.publisher,package_:v.package_,verStr:F(N),version:N,source:l})}a.sort((c,l)=>M(l.version,c.version));for(let c of a)await r.saveDocumentAsync(n.parse(c.source),`${c.publisher}/${c.package_}@${c.verStr}`),s.push({publisher:c.publisher,package_:c.package_,verStr:c.verStr,source:c.source});let m=[...new Set(s.map(c=>c.publisher))].sort(),p=e.publisher;if(p){if(!m.includes(p))throw new Error(`Publisher "${p}" not found in workspace. Available: ${m.join(", ")||"(none)"}`)}else if(m.length===1)p=m[0];else throw m.length===0?new Error(`No Kanonak packages found under ${t}`):new Error(`Workspace has multiple publishers (${m.join(", ")}). Pass --publisher <domain> to choose which one to serve.`);let k=new Set,d=new Map;for(let c of s)c.publisher===p&&(k.add(`${c.publisher}/${c.package_}@${c.verStr}`),d.set(`${c.package_}@${c.verStr}`,c.source));let u=z(),o=new he(u,!0,n),h={};e.httpCache&&(h.getFromCache=e.httpCache.getFromCache,h.onFetch=e.httpCache.onFetch),e.fetchFn&&(h.fetchFn=e.fetchFn);let y=e.repository??new ye(r,o,new Y(h)),b=e.log??(()=>{}),$=T(void 0),w=[],_=c=>c.map(l=>l.metadata.namespace_?.version).filter(l=>l!==void 0).sort((l,v)=>M(v,l)).map(F);if(!e.repository){b(`[render-stack] resolving ${$.length} ambient look-stack package(s); cache: ${u}`);let c=e.fetchFn?new O({fetchFn:e.fetchFn}):new O;for(let l of $){let v=C(l),N=await r.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(N.length>0){let S=_(N);w.push({...l,origin:"workspace",versions:S}),b(`[render-stack] ${v} \u2014 workspace (${S.join(", ")})`);continue}let U=await o.getDocumentsByNamespaceAsync(l.publisher,l.package_);if(U.length>0){let S=_(U);w.push({...l,origin:"cache",versions:S}),b(`[render-stack] ${v} \u2014 cache (${S.join(", ")})`);continue}try{let S=await c.getHighestVersion(l.publisher,l.package_);if(!S){let f=`publisher ${l.publisher} reachable but its index does not list ${l.package_}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let j=await c.getPackageUrl(l.publisher,l.package_,S),i=await(e.fetchFn?e.fetchFn(j,l.publisher):me(j));if(!i.ok){let f=`fetch ${j} failed: HTTP ${i.status} ${i.statusText}`;w.push({...l,origin:"missing",reason:f}),b(`[render-stack] ${v} \u2014 MISSING: ${f}`);continue}let g=await i.text();await r.saveDocumentAsync(n.parse(g),`${l.publisher}/${l.package_}@${S}`);try{let f=$e(u,l.publisher);je(f,{recursive:!0}),_e($e(f,`${l.package_}@${S}.kan.yml`),g,"utf-8"),w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, installed to cache`)}catch(f){w.push({...l,origin:"fetched",versions:[S]}),b(`[render-stack] ${v}@${S} \u2014 fetched from ${j}, but cache ${u} is NOT WRITABLE (${f.message}); usable for this load only \u2014 every load will re-fetch it`)}}catch(S){let j=`fetch failed: ${S.message}`;w.push({...l,origin:"missing",reason:j}),b(`[render-stack] ${v} \u2014 MISSING: ${j}`)}}}let I=y;if(!e.repository){let c=(await r.getAllDocumentsAsync()).filter(v=>v.metadata.namespace_?.publisher===p),l=await H(c,y);for(let v of $)l.add(C(v));I=new V(y,l)}let B=await new Q(n).parseKanonaks(I),oe=new ee(B),G=(c,l)=>Z(B,{publisher:c,package_:l,name:l}).length>0,A;if(e.repository){A=[];for(let c of $){let l=await y.getDocumentsByNamespaceAsync(c.publisher,c.package_);A.push(l.length>0?{...c,origin:"repository",versions:_(l)}:{...c,origin:"missing",reason:"not present in the caller-supplied repository"})}}else A=w.map(c=>c.origin==="missing"||G(c.publisher,c.package_)?c:{...c,resolvedButNotInCatalog:!0});let q=W(A);for(let c of q)b(`[render-stack] WARNING: ${c}`);return re({publisher:p,availablePublishers:m,catalog:B,lookRenderer:oe,localNamespaces:k,rawByNsKey:d,renderStack:{contractSource:"universal-default",cachePath:u,packages:A,warnings:q}})}import{existsSync as Ce,readFileSync as Ae,writeFileSync as Ie,mkdirSync as Ne}from"fs";import{join as Re}from"path";async function ae(t,e={}){let n=new E,r=X(t),s=r.kind==="resource"?r.uri.publisher:r.publisher,a=e.log??(()=>{}),m=e.cacheRoot??z(),p=(i,g,f)=>Re(m,i,`${g}@${f}.kan.yml`),k=new Set,d=new Set,u=new Map,o=new Y({getFromCache:(i,g,f)=>{let D=p(i,g,f),R=Ce(D)?Ae(D,"utf-8"):null;return R!==null&&k.add(`${i}/${g}`),R},onFetch:(i,g,f,D)=>{d.add(`${i}/${g}`);try{let R=Re(m,i);Ne(R,{recursive:!0}),Ie(p(i,g,f),D,"utf-8")}catch(R){u.set(`${i}/${g}`,R.message),a(`[render] fetched ${i}/${g}@${f} but cache ${m} is NOT WRITABLE (${R.message}); usable for this load only \u2014 every load will re-fetch it`)}},...e.fetchFn?{fetchFn:e.fetchFn}:{}}),h=new O(e.fetchFn?{fetchFn:e.fetchFn}:void 0),y;if(r.kind==="resource"){let i=r.uri.version;y=[i?{package_:r.uri.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.uri.package_}]}else if(r.kind==="package"){let i=r.version;y=[i?{package_:r.package_,version:`${i.major}.${i.minor}.${i.patch}`}:{package_:r.package_}]}else y=(await h.listLatestPackages(s)).map(g=>({package_:g.packageName}));let b=async(i,g,f)=>{try{let D=f?n.buildImport(g,"=",f,i):n.buildImport(g,"*","0.0.0",i),R=await o.getHighestCompatibleVersionAsync(i,D);return R?{doc:R}:{doc:null,error:`${i} did not resolve ${g}${f?`@${f}`:""} (not in its index, or unreachable)`}}catch(D){return{doc:null,error:D.message}}},$=[],w=[];for(let i of y){let{doc:g,error:f}=await b(s,i.package_,i.version);g?$.push(g):f&&w.push(f)}if($.length===0)throw new Error(`Could not fetch any package for address "${t}" from publisher "${s}".`+(w.length>0?` Reasons: ${w.join("; ")}`:""));let _=await new ke(e.fetchFn).getConfig(s).catch(()=>{}),I=T(_),B=_?.render&&_.render.length>0?"publisher-well-known":"universal-default",oe=i=>i.map(g=>g.metadata.namespace_?.version).filter(g=>g!==void 0).sort((g,f)=>M(f,g)).map(F);a(`[render-stack] resolving ${I.length} ambient look-stack package(s) (contract: ${B}); cache: ${m}`);let G=[],A=[];for(let i of I){let g=C(i),{doc:f,error:D}=await b(i.publisher,i.package_,void 0);if(f){G.push(f);let R=oe([f]),pe=d.has(g)?"fetched":k.has(g)?"cache":"fetched";A.push({...i,origin:pe,versions:R}),a(`[render-stack] ${g} \u2014 ${pe} (${R.join(", ")})`+(u.has(g)?" [cache write FAILED \u2014 will re-fetch next load]":""))}else A.push({...i,origin:"missing",reason:D??"unresolved"}),a(`[render-stack] ${g} \u2014 MISSING: ${D??"unresolved"}`)}let q=await H([...$,...G],o),de=new V(o,q),c=await new Q(n).parseKanonaks(de),l=new ee(c),v=A.map(i=>i.origin==="missing"||Z(c,{publisher:i.publisher,package_:i.package_,name:i.package_}).length>0?i:{...i,resolvedButNotInCatalog:!0}),N=W(v);for(let i of N)a(`[render-stack] WARNING: ${i}`);let U={contractSource:B,cachePath:m,packages:v,warnings:N},S=new Set,j=new Map;for(let i of await o.getAllDocumentsAsync()){let g=i.metadata.namespace_;if(!g?.version||g.publisher!==s)continue;let f=F(g.version),D=`${g.publisher}/${g.package_}@${f}`;S.add(D);let R=await o.getDocumentContentAsync(D);R!==null&&j.set(`${g.package_}@${f}`,R)}return re({publisher:s,availablePublishers:[s],catalog:c,lookRenderer:l,localNamespaces:S,rawByNsKey:j,renderStack:U})}import{VersionOperator as ne}from"@kanonak-protocol/types/document/models/enums";function te(t){let{lookRenderer:e,publisher:n,renderStack:r,catalog:s}=t,a=e.explainStylesheet(e.publisherSubject(n)),m=[...a.tokens.entries()].map(([o,h])=>({name:o,value:h.value,source:`${h.sourceNamespace}/${h.sourceName}`,level:h.level})),p=a.baseStylesheet,k={present:p.css!==void 0,...p.sourceNamespace!==void 0?{source:p.sourceNamespace}:{},...p.scope!==void 0?{scope:p.scope}:{},...p.css!==void 0?{bytes:p.css.length}:{},...p.problem!==void 0?{problem:p.problem}:{},candidates:p.candidates},d=new Map;for(let o of s){let h=o.namespace;h&&d.set(h,(d.get(h)??0)+1)}let u=[...d.entries()].map(([o,h])=>({namespace:o,resources:h})).sort((o,h)=>o.namespace.localeCompare(h.namespace));return{publisher:n,renderStack:{contractSource:r.contractSource,cachePath:r.cachePath,packages:r.packages.map(o=>({package_:C(o),origin:o.origin,...o.versions!==void 0?{versions:o.versions}:{},...o.reason!==void 0?{reason:o.reason}:{},...o.resolvedButNotInCatalog!==void 0?{resolvedButNotInCatalog:o.resolvedButNotInCatalog}:{}}))},stylesheet:{tokens:m,baseStylesheet:k,...a.look?{look:{sourceClass:`${a.look.sourceClass.publisher}/${a.look.sourceClass.package_}/${a.look.sourceClass.name}`}}:{}},catalog:u,warnings:[...r.warnings,...a.warnings.filter(o=>!r.warnings.includes(o))]}}function Fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ie(t){let e=Fe,n=t.warnings.length===0,r=t.warnings.length===0?'<p class="ok">\u2713 No problems detected \u2014 the render stack is fully resolved and pages should be styled.</p>':t.warnings.map(d=>`<div class="warn">\u26A0 ${e(d)}</div>`).join(`
|
|
2
2
|
`),s=t.renderStack.packages.map(d=>{let u=d.origin!=="missing"&&!d.resolvedButNotInCatalog,o=d.origin==="missing"?'<span class="bad">MISSING</span>':d.resolvedButNotInCatalog?`<span class="bad">${e(d.origin)} (not in catalog)</span>`:`<span class="good">${e(d.origin)}</span>`,h=d.reason?e(d.reason):e((d.versions??[]).join(", "));return`<tr class="${u?"":"row-bad"}"><td><code>${e(d.package_)}</code></td><td>${o}</td><td>${h}</td></tr>`}).join(`
|
|
3
3
|
`),a=t.stylesheet.baseStylesheet,m=a.present?`<p><span class="good">\u2713 present</span> \u2014 <code>${e(a.source??"")}</code> (${a.bytes} bytes, ${e(a.scope??"")})</p>`:`<p><span class="bad">\u2717 MISSING</span>${a.problem?` \u2014 ${e(a.problem)}`:""}${a.candidates.length>0?`<br>candidates considered: ${a.candidates.map(d=>`<code>${e(d)}</code>`).join(", ")}`:""}</p><p>Without the base stylesheet, generated CSS stops at the <code>:root</code> token block and pages appear unstyled.</p>`,p=t.stylesheet.tokens.map(d=>`<tr><td><code>--kan-${e(d.name)}</code></td><td><code>${e(d.value)}</code></td><td><code>${e(d.source)}</code></td><td>${e(d.level)}</td></tr>`).join(`
|
|
4
4
|
`),k=t.catalog.map(d=>`<tr><td><code>${e(d.namespace)}</code></td><td>${d.resources}</td></tr>`).join(`
|
|
@@ -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-V72IVYR4.js";import{a as se}from"../chunk-VWS25JH4.js";import"../chunk-QHABFCRC.js";import"../chunk-4NO7MHS7.js";import"../chunk-RGOBWOBB.js";import"../chunk-PEJALHXK.js";import{a as kn,b as bn,c as hn,d as Dn}from"../chunk-SHDHMKMJ.js";import{h as ie}from"../chunk-BKVPSPG4.js";import{a as ae}from"../chunk-NJ3AZYQD.js";import{b as L,c as A,f as S}from"../chunk-7TKJHKC2.js";import"../chunk-7HRKWTBB.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-4UT2CLAT.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-UBBZWWRB.js";import"../chunk-SHDHMKMJ.js";import"../chunk-BKVPSPG4.js";import"../chunk-NJ3AZYQD.js";import"../chunk-IEOSSSB5.js";import"../chunk-7TKJHKC2.js";import"../chunk-7HRKWTBB.js";import"../chunk-4UT2CLAT.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,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,t as UnresolvedPredicateRule,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.12.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,8 @@
|
|
|
125
125
|
"yaml-parser"
|
|
126
126
|
],
|
|
127
127
|
"dependencies": {
|
|
128
|
-
"@kanonak-protocol/
|
|
128
|
+
"@kanonak-protocol/canonical": "^0.1.1",
|
|
129
|
+
"@kanonak-protocol/types": "^4.12.0",
|
|
129
130
|
"ignore": "^7.0.5",
|
|
130
131
|
"js-yaml": "^4.1.0",
|
|
131
132
|
"yaml": "^2.7.0"
|
package/dist/chunk-MFNVQSBW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as U}from"./chunk-NJ3AZYQD.js";import{b as F,c as V,i as z,j as T}from"./chunk-7HRKWTBB.js";import{a as B,b as _,c as x,d as k,g as w,h as R,i as v,j as D,k as $,l as j}from"./chunk-4UT2CLAT.js";import{j as L}from"./chunk-2ACBWC7K.js";var S=class extends _{name};var I=class extends B{value;carrier;lexical};var K=class extends w{links=[]};var J=n=>({publisher:"kanonak.org",package_:"core-xsd",name:n}),Q=n=>({publisher:"kanonak.org",package_:"core-rdf",name:n}),Z=(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))(Z||{});function C(n){return`${n.publisher}/${n.package_}/${n.name}`}var ee=[["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"]],ne=new Map(ee.map(([n,e])=>[C(J(n)),e])),te=C(Q("langString"));function M(n){let e=C(n);return e===te?"langString":ne.get(e)}function re(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 ae(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",s=(t[3]??"").replace(/0+$/,""),o=s.length>0?`${r}.${s}`:r;return o==="0"?"0":`${a}${o}`}function H(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 oe(n){return H(n,e=>e,"Double")}function ie(n){return H(n,e=>Math.fround(e),"Float")}function se(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 Y(n){return n.normalize("NFC")}function ce(n){return n.normalize("NFC")}function fe(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 pe(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 P=n=>n<10?`0${n}`:`${n}`;function E(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 X(n){if(!n)return"";let e=n.replace(/^\./,"").replace(/0+$/,"");return e.length>0?`.${e}`:""}function G(n){return n?n==="Z"||n==="+00:00"||n==="-00:00"?"Z":n:""}function ue(n){return n==="Z"?0:(n[0]==="-"?-1:1)*(Number(n.slice(1,3))*60+Number(n.slice(4,6)))}var le=/^(-?\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,me=/^(-?\d{4,})-(\d{2})-(\d{2})(Z|[+-]\d{2}:\d{2})?$/,de=/^(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/;function ge(n){let e=le.exec(n.trim());if(!e)throw new Error(`canonicalDateTime: '${n}' is not a valid xsd:dateTime lexical`);let[,t,a,r,s,o,c,f,u]=e,g=X(f);if(!u)return`${E(t)}-${a}-${r}T${s}:${o}:${c}${g}`;let l=new Date(0);l.setUTCFullYear(Number(t),Number(a)-1,Number(r)),l.setUTCHours(Number(s),Number(o),Number(c),0);let i=new Date(l.getTime()-ue(u)*6e4);return`${E(String(i.getUTCFullYear()))}-${P(i.getUTCMonth()+1)}-${P(i.getUTCDate())}T${P(i.getUTCHours())}:${P(i.getUTCMinutes())}:${P(i.getUTCSeconds())}${g}Z`}function ye(n){let e=me.exec(n.trim());if(!e)throw new Error(`canonicalDate: '${n}' is not a valid xsd:date lexical`);let[,t,a,r,s]=e;return`${E(t)}-${a}-${r}${G(s)}`}function ke(n){let e=de.exec(n.trim());if(!e)throw new Error(`canonicalTime: '${n}' is not a valid xsd:time lexical`);let[,t,a,r,s,o]=e,c=X(s),f=t;return t==="24"&&a==="00"&&r==="00"&&c===""&&(f="00"),`${f}:${a}:${r}${c}${G(o)}`}function Pe(n,e){switch(n){case"integer":return re(e);case"decimal":return ae(e);case"double":return oe(e);case"float":return ie(e);case"boolean":return se(e);case"string":return Y(e);case"anyURI":return ce(e);case"langString":return Y(e);case"dateTime":return ge(e);case"date":return ye(e);case"time":return ke(e);case"hexBinary":return fe(e);case"base64Binary":return pe(e)}}var be=/\[\[([^\[\]\n]+)\]\]/g,he=/\[\[/g,q=/```[\s\S]*?```|`[^`\n]*`/g;function Se(n){let e=[];for(let t of n.matchAll(q))e.push([t.index,t.index+t[0].length]);return e}function ve(n){if(!n||!n.includes("[["))return[];let e=Se(n),t=s=>e.some(([o,c])=>s>=o&&s<c),a=new Set(N(n).map(s=>s.startOffset)),r=[];for(let s of n.matchAll(he)){let o=s.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 N(n){if(!n||!n.includes("[["))return[];let e=[];for(let r of n.matchAll(q))e.push([r.index,r.index+r[0].length]);let t=r=>e.some(([s,o])=>r>=s&&r<o),a=[];for(let r of n.matchAll(be)){let s=r.index;if(t(s))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(),g={reference:f,startOffset:s,endOffset:s+r[0].length};u.length>0&&(g.displayText=u),a.push(g)}return a}var W=class{constructor(e){}async parseKanonaks(e){let t=[],a=await e.getAllDocumentsAsync(),r=new F(e),s=new V(r);for(let i of a){let p=i.metadata.namespace_?.toString()??"";for(let[m,y]of Object.entries(i.body)){let d=new x,b=this.resolveCanonicalEntity(m,i,p);d.namespace=b.namespace,d.name=b.name,d.statement=[];let h=await this.parseStatements(y,i,r,s,e);d.statement.push(...h.statements),d.unresolvedPredicates=h.unresolved,t.push(d)}}let o=new Map,c=new Map,f=[];for(let i of t)if(i instanceof x){let p=`${i.namespace}/${i.name}`,m=o.get(p);if(m){let y=c.get(p);for(let d of i.statement){let b=O(d);y.has(b)||(y.add(b),m.statement.push(d))}for(let d of i.unresolvedPredicates)m.unresolvedPredicates.some(b=>b.key===d.key&&b.sourceDoc===d.sourceDoc)||m.unresolvedPredicates.push(d)}else{let y=new Set,d=[];for(let b of i.statement){let h=O(b);y.has(h)||(y.add(h),d.push(b))}i.statement=d,c.set(p,y),o.set(p,i),f.push(i)}}else f.push(i);let u=new Set;for(let i of f)if(i instanceof x){let p=i.namespace||"",m=p.indexOf("/"),y=m>=0?p.slice(0,m):"",d=m>=0?p.slice(m+1):"",b=d.indexOf("@"),h=b>=0?d.slice(0,b):d;u.add(`${y}/${h}/${i.name}`)}let g=i=>u.has(`${i.publisher}/${i.package_}/${i.name}`),l=new Map;for(let i of["core-rdf","core-owl","core-kanonak"]){let p=await e.getDocumentsByNamespaceAsync("kanonak.org",i);l.set(i,L(p).chosen?.metadata.namespace_?.version??void 0)}for(let i of f)i instanceof x&&this.canonicalizeStatementBuiltins(i.statement,g,l);return f}canonicalizeStatementBuiltins(e,t,a){for(let r of e){let s=r.predicate?.subject;if(T(s,t,a),r instanceof D)r.object instanceof k&&T(r.object.subject,t,a);else if(r instanceof $)r.object&&this.canonicalizeStatementBuiltins(r.object.statement,t,a);else if(r instanceof j)for(let o of r.object??[])o instanceof k?T(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("."),s=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)===s){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,s){let o=[],c=[];if(typeof e!="object"||e===null||Array.isArray(e))return{statements:o,unresolved:c};let f=t.metadata.namespace_?.toString()??"";for(let[u,g]of Object.entries(e))try{let l=await this.getPropertyMetadata(u,t,a,s,r);if(!l){let p=u.includes(".")?u.slice(u.lastIndexOf(".")+1):u;z(p)||c.push({key:u,sourceDoc:f});continue}let i=await this.parsePropertyValue(u,g,l,t,a,r,s);i&&o.push(i)}catch(l){throw new Error(`Failed to parse property '${u}': ${l.message}`,{cause:l})}return{statements:o,unresolved:c}}async getPropertyMetadata(e,t,a,r,s){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=s.getPropertyTypeClassification(f),i=c.range?.toString(),p;if(l==="ObjectProperty")p="ObjectProperty";else if(l==="DatatypeProperty")p="DatatypeProperty";else{let d=i&&i.includes(".")?i.substring(i.lastIndexOf(".")+1):i??"";(i?s.isKnownXsdDatatypeName(i):!1)||d==="Literal"?p="DatatypeProperty":p="ObjectProperty"}let m;if(i){let d=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.`);d=h}m=(await a.resolveEntityAsync(i,d))?.uri}return{propertyUri:o.uri.toString(),propertyType:p,range:i,rangeUri:m,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,a,r,s,o,c){let f=a.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(f,t,a,r,s,o,c);if(a.propertyType==="DatatypeProperty")return this.parseDatatypeValue(f,t,a,r,s,o);if(a.propertyType==="ObjectProperty")return this.parseObjectValue(f,t,a,r,s,o,c)}}async parseDatatypeValue(e,t,a,r,s,o){let c;if(typeof t=="string"){if(o.isSubstitutableDatatype(a.rangeUri))return await this.parseSubstitutableValue(e,t,r,s);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),s=a.rangeUri?M(a.rangeUri):void 0;if(s==="boolean"){let c=new v;return c.predicate=r,c.object=t==="true"||t==="1",c.carrier=s,c.lexical=t,c}if(s==="integer"||s==="decimal"||s==="double"||s==="float"){let c=new R;return c.predicate=r,c.object=Number(t),c.carrier=s,c.lexical=t,c}let o=w.parse(e,t);return s&&(o.carrier=s,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 s=new K;s.predicate=k.parse(e),s.object=t;for(let o of N(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),s.links.push(u)}return s}async parseObjectValue(e,t,a,r,s,o,c){if(typeof t=="string"){let f=await this.resolveReference(t,r,s);if(!f)return;let u=new D;return u.predicate=k.parse(e),u.object=f,u}if(typeof t=="object"&&!Array.isArray(t)){let f=await this.parseStatements(t,r,s,o,c);if(f.statements.length>0){let l=new S;l.statement=f.statements,l.unresolvedPredicates=f.unresolved;let i=new $;return i.predicate=k.parse(e),i.object=l,i}let u=[];for(let[l,i]of Object.entries(t))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let p=new S;p.name=l;let m=await this.parseStatements(i,r,s,o,c);p.statement=m.statements,p.unresolvedPredicates=m.unresolved,u.push(p)}else if(typeof i=="string"){let p=await this.resolveReference(i,r,s);p&&u.push(p)}if(u.length>0){let l=new j;return l.predicate=k.parse(e),l.object=u,l}let g=new $;return g.predicate=k.parse(e),g.object=new S,g}}async parseListValue(e,t,a,r,s,o,c){let f=[],u=a.propertyType==="DatatypeProperty",g=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 i of t){let p=typeof i=="string"||typeof i=="number"||typeof i=="boolean";if(u&&p){let m=typeof i=="string"?i:String(i);f.push(this.typedListLiteral(m,a));continue}if(g&&p){if(typeof i=="string"){let m=await s.resolveEntityAsync(i,r);if(m){let y=new k;y.subject=m.uri,f.push(y)}else{let y=new I;y.value=i,f.push(y)}}else{let m=new I;m.value=i,f.push(m)}continue}if(typeof i=="string"){let m=await this.resolveReference(i,r,s);m&&f.push(m)}else if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let m=new S,y=await this.parseStatements(i,r,s,o,c);m.statement=y.statements,m.unresolvedPredicates=y.unresolved,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 s=t.metadata?.namespace_;if(s){let{KanonakUri:o}=await import("./KanonakUri-4VJGV3FN.js");if(e.includes(".")){let f=e.indexOf("."),u=e.substring(0,f),g=e.substring(f+1);if(t.metadata?.imports){for(let[l,i]of Object.entries(t.metadata.imports))for(let p of i)if((p.alias??p.packageName)===u){let y=new k;return y.subject=new o(l,p.packageName,g,p.version),y}}}let c=new k;return c.subject=new o(s.publisher,s.package_,e,s.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,s]of a){let o=await this.convertKanonaksToDocument(r,s),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:{}},s=new Map;for(let o of t){let c={};for(let f of o.statement){let[u,g]=this.convertStatementToProperty(f);u&&g!==null&&g!==void 0&&(c[u]=g),this.collectImportsFromStatement(f,e,s)}r.body[o.name]=c}return r}convertStatementToProperty(e){if(e instanceof w)return[e.predicate.subject.name,e.object];if(e instanceof R)return[e.predicate.subject.name,e.object];if(e instanceof v)return[e.predicate.subject.name,e.object];if(e instanceof D)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 $){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,s]=this.convertStatementToProperty(a);r&&s!==null&&s!==void 0&&(t[r]=s)}return t}collectImportsFromStatement(e,t,a){}};function O(n){let e=n.predicate?.subject;return(e?`${e.publisher}/${e.package_}/${e.name}`:"?")+"="+xe(n)}function xe(n){return n instanceof K?"m:"+String(n.object):n instanceof w?"s:"+String(n.object):n instanceof R?"n:"+String(n.object):n instanceof v?"b:"+String(n.object):n instanceof D?"r:"+A(n.object):n instanceof $?"e:"+A(n.object):n instanceof j?"l:["+(n.object??[]).map(A).join("|")+"]":"x"}function A(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,K as c,Z as d,M as e,Pe as f,ve as g,N as h,W as i};
|