@kanonak-protocol/sdk 3.59.0 → 3.61.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/README.md +4 -117
- package/dist/browser.js +1 -1
- package/dist/chunk-2ACBWC7K.js +1 -0
- package/dist/{chunk-CYDDQF6S.js → chunk-7JZUJ2K4.js} +1 -1
- package/dist/chunk-CA2EATJR.js +1 -0
- package/dist/chunk-IL6VHYRU.js +148 -0
- package/dist/{chunk-IIODYDKS.js → chunk-IUCHSPLQ.js} +1 -1
- package/dist/{chunk-WDQONH3P.js → chunk-KSTGTV35.js} +1 -1
- package/dist/{chunk-BSJ6PEKE.js → chunk-OIVACCMQ.js} +9 -9
- package/dist/chunk-ORFSMEMM.js +1 -0
- package/dist/chunk-PEJALHXK.js +1 -0
- package/dist/{chunk-VJT6YUWK.js → chunk-Q6QTQWR2.js} +1 -1
- package/dist/{chunk-SD5QKNBC.js → chunk-QHJ6EY3Y.js} +1 -1
- package/dist/chunk-RSIZQAFL.js +2 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +20 -20
- package/dist/look/LookRenderer.d.ts +35 -0
- package/dist/parsing/KanonakParser.d.ts +10 -1
- package/dist/parsing/index.js +1 -1
- package/dist/reasoning/index.js +1 -1
- package/dist/repositories/PublisherConfig.d.ts +11 -0
- package/dist/repositories/browser.js +1 -1
- package/dist/repositories/index.js +1 -1
- package/dist/resolution/KanonakUrlResolver.d.ts +8 -0
- package/dist/resolution/VersionUtils.d.ts +12 -0
- package/dist/resolution/index.d.ts +1 -1
- package/dist/resolution/index.js +1 -1
- package/dist/search/index.js +1 -1
- package/dist/server/assembleModel.d.ts +21 -0
- package/dist/server/index.d.ts +6 -0
- package/dist/server/index.js +2 -2
- package/dist/server/loadResourceModel.d.ts +26 -0
- package/dist/server/renderStack.d.ts +42 -0
- package/dist/server/requestRouter.d.ts +53 -0
- package/dist/transformations/index.js +1 -1
- package/dist/validation/index.js +1 -1
- package/package.json +6 -4
- package/dist/chunk-4FZUKBBE.js +0 -2
- package/dist/chunk-7CUTGGH3.js +0 -1
- package/dist/chunk-7RAM5KZZ.js +0 -1
- package/dist/chunk-ESYVKB25.js +0 -148
- package/dist/chunk-FQHALFRR.js +0 -1
- package/dist/chunk-NIGFQYVA.js +0 -1
package/README.md
CHANGED
|
@@ -1,129 +1,16 @@
|
|
|
1
1
|
# @kanonak-protocol/sdk
|
|
2
2
|
|
|
3
|
-
TypeScript SDK for [Kanonak Protocol](https://kanonak.org) — parse, validate,
|
|
3
|
+
The TypeScript SDK for the [Kanonak Protocol](https://kanonak.org) — parse, resolve, validate, reason over, and render `.kan.yml` packages. It is the shared engine behind the [`@kanonak-protocol/cli`](https://www.npmjs.com/package/@kanonak-protocol/cli) and the Kanonak VS Code extension.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Install
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
8
|
npm install @kanonak-protocol/sdk
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## Usage
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
```typescript
|
|
16
|
-
import { KanonakParser } from '@kanonak-protocol/sdk';
|
|
17
|
-
|
|
18
|
-
const parser = new KanonakParser();
|
|
19
|
-
const doc = parser.parse(yamlContent);
|
|
20
|
-
|
|
21
|
-
// doc.metadata — package info, publisher, version, imports
|
|
22
|
-
// doc.body — all entities (classes, properties, instances) as key-value pairs
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
### Validate
|
|
26
|
-
|
|
27
|
-
```typescript
|
|
28
|
-
import { KanonakParser, KanonakObjectValidator, InMemoryKanonakDocumentRepository } from '@kanonak-protocol/sdk';
|
|
29
|
-
|
|
30
|
-
const parser = new KanonakParser();
|
|
31
|
-
const repo = new InMemoryKanonakDocumentRepository(parser);
|
|
32
|
-
|
|
33
|
-
// Load one or more documents
|
|
34
|
-
const doc = parser.parse(yamlContent);
|
|
35
|
-
await repo.saveDocumentAsync(doc, 'my-ontology');
|
|
36
|
-
|
|
37
|
-
// Validate
|
|
38
|
-
const validator = new KanonakObjectValidator(parser);
|
|
39
|
-
const result = await validator.validateAsync(doc, repo);
|
|
40
|
-
|
|
41
|
-
for (const error of result.errors) {
|
|
42
|
-
console.log(`${error.severity}: ${error.message}`);
|
|
43
|
-
}
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
### Extract a graph for visualization
|
|
47
|
-
|
|
48
|
-
Returns nodes and edges ready for D3, Cytoscape, React Flow, vis.js, or any graph library:
|
|
49
|
-
|
|
50
|
-
```typescript
|
|
51
|
-
import { GraphBuilder, KanonakParser, InMemoryKanonakDocumentRepository } from '@kanonak-protocol/sdk';
|
|
52
|
-
|
|
53
|
-
const parser = new KanonakParser();
|
|
54
|
-
const repo = new InMemoryKanonakDocumentRepository(parser);
|
|
55
|
-
const doc = parser.parse(yamlContent);
|
|
56
|
-
await repo.saveDocumentAsync(doc, 'contacts');
|
|
57
|
-
|
|
58
|
-
const graph = await GraphBuilder.buildFromRepository(repo);
|
|
59
|
-
|
|
60
|
-
// graph.nodes — each node has: id, label, type, namespace, properties
|
|
61
|
-
// type is one of: Class, ObjectProperty, DatatypeProperty, Instance, Datatype, Unknown
|
|
62
|
-
//
|
|
63
|
-
// graph.edges — each edge has: source, target, type, label
|
|
64
|
-
// type is one of: instanceOf, subClassOf, domain, range, objectRelationship, subPropertyOf
|
|
65
|
-
|
|
66
|
-
// Quick single-document graph (no repository needed):
|
|
67
|
-
const simpleGraph = GraphBuilder.buildFromDocument(doc);
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
### Resolve entity references across imports
|
|
71
|
-
|
|
72
|
-
```typescript
|
|
73
|
-
import { ResourceResolver, KanonakParser, InMemoryKanonakDocumentRepository } from '@kanonak-protocol/sdk';
|
|
74
|
-
|
|
75
|
-
const parser = new KanonakParser();
|
|
76
|
-
const repo = new InMemoryKanonakDocumentRepository(parser);
|
|
77
|
-
// ... load documents into repo ...
|
|
78
|
-
|
|
79
|
-
const resolver = new ResourceResolver(repo);
|
|
80
|
-
const entity = await resolver.resolveEntityAsync('Person', doc);
|
|
81
|
-
// entity.uri — fully qualified Kanonak URI
|
|
82
|
-
// entity.entity — the raw entity definition
|
|
83
|
-
// entity.isImported — whether it came from an imported package
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
## Browser usage
|
|
87
|
-
|
|
88
|
-
For browser applications (no Node.js APIs), import from the browser entry point:
|
|
89
|
-
|
|
90
|
-
```typescript
|
|
91
|
-
import {
|
|
92
|
-
KanonakParser,
|
|
93
|
-
GraphBuilder,
|
|
94
|
-
InMemoryKanonakDocumentRepository,
|
|
95
|
-
HttpKanonakDocumentRepository,
|
|
96
|
-
KanonakObjectValidator,
|
|
97
|
-
} from '@kanonak-protocol/sdk/browser';
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
This includes parsing, validation, graph building, resolution, and HTTP/in-memory repositories. It excludes filesystem access, OS credential stores, and other Node.js-specific modules.
|
|
101
|
-
|
|
102
|
-
Works with Vite, webpack, esbuild, Rollup, or any browser bundler.
|
|
103
|
-
|
|
104
|
-
## Document repositories
|
|
105
|
-
|
|
106
|
-
```typescript
|
|
107
|
-
import {
|
|
108
|
-
InMemoryKanonakDocumentRepository, // In-memory — for testing, browser, or single-document work
|
|
109
|
-
FileSystemKanonakDocumentRepository, // Filesystem — scan a directory of .kan.yml files (Node.js only)
|
|
110
|
-
HttpKanonakDocumentRepository, // HTTP — fetch packages from publisher domains
|
|
111
|
-
} from '@kanonak-protocol/sdk';
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
## Key modules
|
|
115
|
-
|
|
116
|
-
| Module | Description | Browser-safe |
|
|
117
|
-
|--------|-------------|:---:|
|
|
118
|
-
| `KanonakParser` | Parse `.kan.yml` YAML into `KanonakDocument` objects | Yes |
|
|
119
|
-
| `KanonakObjectValidator` | Validate documents against ontology rules | Yes |
|
|
120
|
-
| `GraphBuilder` | Extract nodes and edges for graph visualization | Yes |
|
|
121
|
-
| `ResourceResolver` | Resolve entity references across imports | Yes |
|
|
122
|
-
| `InMemoryKanonakDocumentRepository` | In-memory document store | Yes |
|
|
123
|
-
| `HttpKanonakDocumentRepository` | Fetch packages from publisher HTTP endpoints | Yes |
|
|
124
|
-
| `PublisherIndex` | Discover and resolve package versions from publishers | Yes |
|
|
125
|
-
| `FileSystemKanonakDocumentRepository` | Read/write `.kan.yml` files on disk | No |
|
|
126
|
-
| `CredentialStore` | OS-native credential storage (Keychain, CredMan, etc.) | No |
|
|
13
|
+
All reading and traversal of Kanonak documents goes through the SDK rather than ad-hoc YAML handling, so every consumer shares one verified object model (identifiers, aliases, versions, and references resolved the same way). Start from the type definitions shipped with the package; guides and the protocol specification are at **[kanonak.org](https://kanonak.org)**.
|
|
127
14
|
|
|
128
15
|
## License
|
|
129
16
|
|
package/dist/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-
|
|
1
|
+
import{a as ge,b as fe,c as me,d as C,e as E,f as d}from"./chunk-KSTGTV35.js";import{a as Qe}from"./chunk-IUCHSPLQ.js";import"./chunk-3NEUHF7E.js";import{a as H,c as L,d as W,e as F}from"./chunk-RSIZQAFL.js";import{a as Pe,b as we,c as he}from"./chunk-7JZUJ2K4.js";import{a as ke,b as be}from"./chunk-PEUTCG3B.js";import"./chunk-PEJALHXK.js";import"./chunk-SC5M74NM.js";import{A as We,B as Fe,C as Ge,E as Xe,a as Ke,b as xe,c as Se,d as Re,f as De,g as Be,h as Ce,i as Ee,j as je,k as ve,l as _e,m as Ie,n as Ae,o as Te,p as Oe,q as Ve,r as $e,s as Ue,t as ze,u as Me,v as Ne,w as Je,x as He,y as qe,z as Le}from"./chunk-OIVACCMQ.js";import{c as pe}from"./chunk-Q6QTQWR2.js";import{a as Y,c as le}from"./chunk-H2LEQLVD.js";import{a as q}from"./chunk-ORFSMEMM.js";import{a as ye}from"./chunk-N224PFBI.js";import"./chunk-Q4DKP5DO.js";import{b as ue,c as de}from"./chunk-64TVBQFR.js";import{a as G,b as X,c as Q,d as ee,e as re,f as te,g as ne,h as oe,i as se,j as ie,k as ae,l as ce}from"./chunk-W6T7MOKY.js";import{a as Z}from"./chunk-FUUTGGJS.js";import{c as O,d as V,e as $,f as U,g as z,h as M,i as N,j as J}from"./chunk-2ACBWC7K.js";var j="kanonak-credentials",u="credentials",Ye=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,Ye);e.onupgradeneeded=()=>{let t=e.result;t.objectStoreNames.contains(u)||t.createObjectStore(u)},e.onsuccess=()=>n(e.result),e.onerror=()=>r(new Error(`Failed to open IndexedDB '${j}': ${e.error?.message}
|
|
2
2
|
Credential storage requires IndexedDB support in your browser.`))})}async function _(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey);return{signingKey:n.privateKey,publicKeyJwk:r}}async function k(){let n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),r=await crypto.subtle.exportKey("jwk",n.publicKey),e=await crypto.subtle.exportKey("jwk",n.privateKey);return{keys:{signingKey:n.privateKey,publicKeyJwk:r},dpopKeyPair:{publicKey:r,privateKey:e}}}async function b(n){return{signingKey:await crypto.subtle.importKey("jwk",n.privateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),publicKeyJwk:n.publicKey}}async function K(n,r,e,t,o){let a={alg:"ES256",typ:"dpop+jwt",jwk:{kty:n.publicKeyJwk.kty,crv:n.publicKeyJwk.crv,x:n.publicKeyJwk.x,y:n.publicKeyJwk.y}},s={jti:crypto.randomUUID(),htm:r.toUpperCase(),htu:e,iat:Math.floor(Date.now()/1e3)};return t&&(s.ath=await er(t)),o&&(s.nonce=o),await Ze(a,s,n.signingKey)}function x(n){return!n||n.length===0?!1:n.some(r=>r.toUpperCase()==="ES256")}async function Ze(n,r,e){let t=v(JSON.stringify(n)),o=v(JSON.stringify(r)),a=new TextEncoder().encode(`${t}.${o}`),s=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,a),l=D(s);return`${t}.${o}.${l}`}async function er(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return D(e)}function v(n){let r=new TextEncoder().encode(n);return D(r.buffer)}function D(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var rr=300*1e3,S=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=x(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=tr(),p=await nr(m),R=or(),A=sr(t.authorizationEndpoint,i,this.callbackUrl,R,p),y=await this.openAuthPopup(A,R);if(!y)return{success:!1,error:"Authorization timed out or was cancelled."};if(y.error)return{success:!1,error:`Authorization failed: ${y.error}`};if(!y.code)return{success:!1,error:"No authorization code received."};if(y.state!==R)return{success:!1,error:"State mismatch \u2014 possible CSRF attack."};let P=await this.exchangeCode(t.tokenEndpoint,i,c,y.code,this.callbackUrl,m,a);if(!P)return{success:!1,error:"Token exchange failed."};let T={clientId:i,clientSecret:c,accessToken:P.accessToken??null,refreshToken:P.refreshToken??null,expiresAt:P.expiresIn?new Date(Date.now()+P.expiresIn*1e3).toISOString():null,tokenEndpoint:t.tokenEndpoint,dpopKeyPair:s};return await this.credentialBackend.store(e,T),{success:!0,host:e}}async getCredentialWithKeys(r){let e=await this.credentialBackend.get(r);if(!e)return null;let t=null;return e.dpopKeyPair&&(t=await b(e.dpopKeyPair)),{credential:e,dpopKeys:t}}async logout(r){let e=d(r);return await this.credentialBackend.remove(e),{success:!0,host:e}}async listAuthenticated(){return this.credentialBackend.list()}async discover(r){for(let e of[`https://${r}/.well-known/oauth-authorization-server`,`https://${r}/.well-known/openid-configuration`])try{let t=await fetch(e);if(!t.ok)continue;let o=await t.json();return{issuer:w(o.issuer),authorizationEndpoint:w(o.authorization_endpoint),tokenEndpoint:w(o.token_endpoint),registrationEndpoint:w(o.registration_endpoint),revocationEndpoint:w(o.revocation_endpoint),dpopSigningAlgValuesSupported:I(o.dpop_signing_alg_values_supported),codeChallengeMethodsSupported:I(o.code_challenge_methods_supported)}}catch{continue}return null}async registerClient(r){try{let e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak Browser",redirect_uris:[this.callbackUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})});if(!e.ok)return null;let t=await e.json(),o=t.client_id;return o?{clientId:o,clientSecret:t.client_secret}:null}catch{return null}}openAuthPopup(r,e){return new Promise(t=>{let o=window.open(r,"kanonak-auth","width=500,height=700,menubar=no,toolbar=no,location=yes,status=no");if(!o){t(null);return}let a=setTimeout(()=>{i(),t(null)},rr),s=c=>{c.origin===window.location.origin&&(!c.data||c.data.type!=="kanonak-auth-callback"||(i(),t({code:c.data.code??void 0,state:c.data.state??void 0,error:c.data.error??void 0})))},l=setInterval(()=>{o.closed&&(i(),t(null))},500),i=()=>{clearTimeout(a),clearInterval(l),window.removeEventListener("message",s);try{o.close()}catch{}};window.addEventListener("message",s)})}async exchangeCode(r,e,t,o,a,s,l){let i=new URLSearchParams({grant_type:"authorization_code",client_id:e,code:o,redirect_uri:a,code_verifier:s});t&&i.set("client_secret",t);let c={"Content-Type":"application/x-www-form-urlencoded"};l&&(c.DPoP=await K(l,"POST",r));try{let m=await fetch(r,{method:"POST",headers:c,body:i.toString()});if(!m.ok)return null;let p=await m.json();return{accessToken:p.access_token,refreshToken:p.refresh_token,expiresIn:typeof p.expires_in=="number"?p.expires_in:void 0}}catch{return null}}};function tr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),B(n.buffer)}async function nr(n){let r=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",r);return B(e)}function or(){let n=new Uint8Array(16);return crypto.getRandomValues(n),B(n.buffer)}function sr(n,r,e,t,o){let a=new URLSearchParams({client_id:r,response_type:"code",redirect_uri:e,state:t,code_challenge:o,code_challenge_method:"S256"});return`${n}?${a}`}function B(n){let r=new Uint8Array(n),e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(n){return typeof n=="string"?n:null}function I(n){return Array.isArray(n)?n.filter(r=>typeof r=="string"):null}export{Ne as AmbiguousReferenceRule,se as BooleanStatement,f as BrowserCredentialBackend,S as BrowserOAuthFlow,Fe as ClassDefinitionRule,Ie as ClassHierarchyCycleRule,X as DefinedKanonak,ze as DefinitionPropertyReferenceRule,fe as EdgeType,Y as EmbeddedKanonak,je as EmbeddedKanonakTypeRule,ae as EmbeddedStatement,me as GraphBuilder,F as HttpKanonakDocumentRepository,ve as ImportExistenceRule,H as InMemoryKanonakDocumentRepository,Ue as InstancePropertyReferenceRule,G as Kanonak,we as KanonakDocumentPositions,pe as KanonakObjectParser,Xe as KanonakObjectValidator,q as KanonakParser,Z as KanonakUri,ke as KanonakUriBuilder,ce as ListStatement,Ge as MarkdownLinkRule,le as MarkdownStatement,$e as NamespaceImportCycleRule,De as NamespacePrefixRule,ge as NodeType,oe as NumberStatement,He as ObjectPropertyImportRule,qe as ObjectPropertyValueValidationRule,Se as OntologyValidationError,Ke as OntologyValidationResult,Le as PropertyDomainRule,Ae as PropertyHierarchyCycleRule,Pe as PropertyMetadata,Je as PropertyRangeReferenceRule,Te as PropertyRangeRequiredRule,Ce as PropertyTypeSpecificityRule,We as PropertyValueTypeRule,L as PublisherConfigResolver,W as PublisherIndex,ee as ReferenceKanonak,ie as ReferenceStatement,Be as ResourceNamingRule,ue as ResourceResolver,ye as ResourceTypeClassifier,te as ScalarStatement,re as Statement,ne as StringStatement,Oe as SubClassOfReferenceRule,Ve as SubPropertyOfReferenceRule,Q as SubjectKanonak,Ee as SubjectKanonakTypeRequiredRule,de as TypeResolver,_e as UnresolvedReferenceRule,Re as ValidationContext,xe as ValidationSeverity,Me as XsdImportRule,x as browserServerSupportsDPoP,O as compareVersions,K as createBrowserDPoPProof,U as createVersion,Qe as findDerivation,be as findInstancesByType,$ as formatVersion,k as generateBrowserDPoPKeyPair,_ as generateBrowserDPoPKeys,E as hasValidToken,b as importDPoPKeys,M as isCompatibleVersion,C as isExpired,N as isMajorCompatible,d as normalizeHost,z as parseVersionString,he as parseWithPositions,J as pickHighestDocument,V as versionsEqual};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{VersionOperator as o}from"@kanonak-protocol/types/document/models/enums";function f(e){switch(e){case"=":return o.Exact;case"~":return o.Compatible;case"^":return o.Major;case"*":return o.Any;default:return o.Compatible}}function V(e){switch(e){case o.Exact:return"=";case o.Compatible:return"~";case o.Major:return"^";case o.Any:return"*";default:return"~"}}function u(e,n){return e.major!==n.major?e.major-n.major:e.minor!==n.minor?e.minor-n.minor:e.patch-n.patch}function x(e,n){return e.major===n.major&&e.minor===n.minor&&e.patch===n.patch}function l(e){return`${e.major}.${e.minor}.${e.patch}`}function c(e,n,t){let a=`${e}.${n}.${t}`;return{major:e,minor:n,patch:t,toString:()=>a,equals:r=>r?.major===e&&r?.minor===n&&r?.patch===t,getHashCode:()=>e<<20|n<<10|t,compareTo:r=>e!==r.major?e-r.major:n!==r.minor?n-r.minor:t-r.patch}}function g(e){let n=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);return n?c(Number(n[1]),Number(n[2]),Number(n[3])):null}function h(e,n){return u(e,n)>=0&&e.major===n.major&&e.minor===n.minor}function v(e,n){return n.major===0?u(e,n)>=0&&e.major===0&&e.minor===n.minor:u(e,n)>=0&&e.major===n.major}function j(e,n={}){let{requestedVersion:t}=n;if(e.length===0)return{chosen:null,alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!!t};if(t){let r=e.find(i=>{let s=i.metadata.namespace_?.version;return!!s&&l(s)===t});return r?{chosen:r,alternatives:e.filter(i=>i!==r),multipleVersionsPresent:e.length>1,exactRequestedVersionMissing:!1}:{chosen:null,alternatives:e,multipleVersionsPresent:e.length>1,exactRequestedVersionMissing:!0}}if(e.length===1)return{chosen:e[0],alternatives:[],multipleVersionsPresent:!1,exactRequestedVersionMissing:!1};let a=[...e].sort((r,i)=>{let s=r.metadata.namespace_?.version,m=i.metadata.namespace_?.version;return!s&&!m?0:s?m?u(m,s):-1:1});return{chosen:a[0],alternatives:a.slice(1),multipleVersionsPresent:!0,exactRequestedVersionMissing:!1}}export{f as a,V as b,u as c,x as d,l as e,c as f,g,h,v as i,j};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as V}from"./chunk-
|
|
1
|
+
import{b as V}from"./chunk-Q6QTQWR2.js";import{a as E}from"./chunk-ORFSMEMM.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as A,e as v}from"./chunk-RSIZQAFL.js";import{a as f}from"./chunk-ORFSMEMM.js";import{c as w,d as I,h as R,i as F}from"./chunk-2ACBWC7K.js";import*as i from"fs/promises";import*as c from"path";import{pathToFileURL as b}from"url";import{VersionOperator as P}from"@kanonak-protocol/types/document/models/enums";var y=class{rootPath;recursive;parser;documentCache;filePathsByIdentifier;cacheInitialized=!1;cacheInitPromise=null;parsingErrors=new Map;constructor(e,t=!0,n){if(!e||e.trim().length===0)throw new Error("Root path cannot be null or empty");this.rootPath=c.resolve(e),this.recursive=t,this.parser=n??new f,this.documentCache=new Map,this.filePathsByIdentifier=new Map}async getAllDocumentsAsync(){await this.ensureCacheInitialized();let e=new Set(this.documentCache.values());return Array.from(e)}async getDocumentAsync(e){await this.ensureCacheInitialized();let t=this.documentCache.get(e);if(t)return t;let n=c.join(this.rootPath,e);if(t=this.documentCache.get(n),t)return t;for(let o of[".kan.yml",".yml",".yaml"])if(!e.endsWith(o)){let s=e+o;if(t=this.documentCache.get(s),t)return t;let a=c.join(this.rootPath,s);if(t=this.documentCache.get(a),t)return t}return null}async getDocumentsByNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values());return Array.from(n).filter(o=>o.metadata.namespace_?.publisher===e&&o.metadata.namespace_?.package_===t)}async getHighestCompatibleVersionAsync(e,t){await this.ensureCacheInitialized();let n=new Set(this.documentCache.values()),o=Array.from(n).filter(a=>a.metadata?.namespace_?.publisher===e&&a.metadata?.namespace_?.package_===t.packageName&&a.metadata?.namespace_?.version!==void 0);if(o.length===0)return null;let s=o.filter(a=>{let r=a.metadata.namespace_.version;switch(t.versionOperator){case P.Exact:return I(r,t.version);case P.Compatible:return R(r,t.version);case P.Major:return F(r,t.version);case P.Any:return w(r,t.minVersion)>=0;default:return!1}});return s.length===0?null:(s.sort((a,r)=>{let m=a.metadata.namespace_.version,l=r.metadata.namespace_.version;return w(l,m)}),s[0])}async saveDocumentAsync(e,t){let n,o=e.metadata.namespace_?.toString();if(o&&o.includes("@")&&o.includes("/")){let m=o.split("/"),l=m[0],p=m[1].replace("@","@")+".kan.yml";n=c.join(this.rootPath,l,p)}else n=c.join(this.rootPath,t),!n.endsWith(".yml")&&!n.endsWith(".yaml")&&!n.endsWith(".kan.yml")&&(n+=".kan.yml");let s=c.dirname(n);await i.mkdir(s,{recursive:!0});let a=this.parser.save(e);await i.writeFile(n,a,"utf8"),o&&this.documentCache.set(o,e),this.documentCache.set(n,e);let r=c.relative(this.rootPath,n);this.documentCache.set(r,e)}async deleteDocumentAsync(e){let t=await this.getDocumentAsync(e);if(!t)return;let n=this.filePathsByIdentifier.get(e);if(!n)return;try{await i.unlink(n)}catch{}let o=t.metadata.namespace_?.toString();o&&this.documentCache.delete(o),this.documentCache.delete(e),this.documentCache.delete(n);let s=c.relative(this.rootPath,n);this.documentCache.delete(s)}async clearNamespaceAsync(e,t){await this.ensureCacheInitialized();let n=[];for(let[s,a]of this.documentCache.entries()){let r=a.metadata.namespace_?.toString()||"";r.includes(e)&&r.includes(t)&&n.push([s,a])}let o=c.join(this.rootPath,e);try{let s=await i.readdir(o);for(let a of s)a.includes(t)&&a.endsWith(".kan.yml")&&await i.unlink(c.join(o,a))}catch{}for(let[s]of n)this.documentCache.delete(s)}async getAllDocumentReferencesAsync(){await this.ensureCacheInitialized();let e=new Set(this.filePathsByIdentifier.values()),t=[];for(let n of e){let o=b(n).toString(),s;for(let[m,l]of this.documentCache.entries())if(this.filePathsByIdentifier.get(m)===n&&l.metadata.namespace_){s=l.metadata.namespace_.toString();break}let a=s??c.relative(this.rootPath,n),r=this.parsingErrors.has(n);t.push({identifier:a,uri:o,hasParseError:r})}return t}async getDocumentContentAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}try{return await i.readFile(t,"utf8")}catch{return null}}async getDocumentUriAsync(e){await this.ensureCacheInitialized();let t=this.filePathsByIdentifier.get(e);if(!t)try{await i.access(e),t=e}catch{let n=c.join(this.rootPath,e);try{await i.access(n),t=n}catch{return null}}return b(t).toString()}async refreshAsync(){this.documentCache.clear(),this.filePathsByIdentifier.clear(),this.parsingErrors.clear(),this.cacheInitialized=!1,this.cacheInitPromise=null,await this.ensureCacheInitialized()}async ensureCacheInitialized(){if(!this.cacheInitialized){if(this.cacheInitPromise){await this.cacheInitPromise;return}this.cacheInitPromise=this.loadDocuments(),await this.cacheInitPromise,this.cacheInitialized=!0}}async loadDocuments(){try{await i.mkdir(this.rootPath,{recursive:!0})}catch{}let t=(await this.findYamlFiles(this.rootPath,this.recursive)).map(async o=>{try{let s=await i.readFile(o,"utf8"),a=this.parser.parse(s);return{filePath:o,document:a,error:null}}catch(s){return{filePath:o,document:null,error:s instanceof Error?s.message:String(s)}}}),n=await Promise.all(t);for(let{filePath:o,document:s,error:a}of n){let r=c.relative(this.rootPath,o);if(s&&s.metadata.namespace_){let m=s.metadata.namespace_.toString();this.documentCache.set(m,s),this.documentCache.set(o,s),this.documentCache.set(r,s),this.filePathsByIdentifier.set(m,o),this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o)}else this.filePathsByIdentifier.set(o,o),this.filePathsByIdentifier.set(r,o);a&&this.parsingErrors.set(o,a)}}async findYamlFiles(e,t){let n=[];try{let o=await i.readdir(e,{withFileTypes:!0});for(let s of o){let a=c.join(e,s.name);if(s.isDirectory()&&t){let r=await this.findYamlFiles(a,t);n.push(...r)}else s.isFile()&&s.name.endsWith(".kan.yml")&&n.push(a)}}catch{}return n}};import*as d from"fs";var S=(n=>(n.NotFound="NotFound",n.Workspace="Workspace",n.Cache="Cache",n))(S||{}),k=class{cache;workspace;constructor(e,t,n){let o=n??new f;d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(t)||d.mkdirSync(t,{recursive:!0}),this.cache=new y(e,!0,o),this.workspace=new y(t,!0,o)}getCache(){return this.cache}getWorkspace(){return this.workspace}async getAllDocumentsAsync(){let e=await this.workspace.getAllDocumentsAsync(),t=await this.cache.getAllDocumentsAsync(),n=new Map;for(let o of t)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}for(let o of e)if(o.metadata.namespace_){let s=o.metadata.namespace_.toString();n.set(s,o)}return Array.from(n.values())}async getDocumentAsync(e){let t=await this.workspace.getDocumentAsync(e);return t||await this.cache.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){let n=await this.workspace.getDocumentsByNamespaceAsync(e,t),o=await this.cache.getDocumentsByNamespaceAsync(e,t),s=new Map;for(let a of o)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}for(let a of n)if(a.metadata.namespace_?.version){let r=a.metadata.namespace_.version.toString();s.set(r,a)}return Array.from(s.values())}async getHighestCompatibleVersionAsync(e,t){let n=await this.workspace.getHighestCompatibleVersionAsync(e,t);return n||await this.cache.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(e,t){await this.workspace.saveDocumentAsync(e,t)}async saveToCacheAsync(e,t){await this.cache.saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.workspace.deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.workspace.clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){let e=await this.workspace.getAllDocumentReferencesAsync(),t=await this.cache.getAllDocumentReferencesAsync(),n=[];return n.push(...e),n.push(...t),n}async getDocumentContentAsync(e){let t=await this.workspace.getDocumentContentAsync(e);return t||await this.cache.getDocumentContentAsync(e)}async getDocumentUriAsync(e){let t=await this.workspace.getDocumentUriAsync(e);return t||await this.cache.getDocumentUriAsync(e)}async getDocumentLocationAsync(e){return await this.workspace.getDocumentAsync(e)?"Workspace":await this.cache.getDocumentAsync(e)?"Cache":"NotFound"}};import{homedir as _}from"os";import{join as N}from"path";function g(){let u=process.env.KANONAK_PACKAGE_CACHE;return u||N(_(),".kanonak","packages")}var C=class u{static createComposite(e,t,n){let o=e??g(),s=t??".";return new k(o,s,n)}static createFromEnvironment(e){let t=g(),n=process.env.KANONAK_WORKSPACE_PATH??".";return u.createComposite(t,n,e)}};var D=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let n of this.repos)try{let o=await n.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[],t=new Set;for(let n of this.repos)try{for(let o of await n.getAllDocumentsAsync()){let s=o.metadata?.namespace_,a=s?s.version?`${s.publisher}/${s.package_}@${s.version.major}.${s.version.minor}.${s.version.patch}`:`${s.publisher}/${s.package_}`:void 0;if(a!==void 0){if(t.has(a))continue;t.add(a)}e.push(o)}}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentAsync(e);if(n)return n}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let n of this.repos)try{let o=await n.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let n=await t.getDocumentContentAsync(e);if(n)return n}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let n=await t.getDocumentUriAsync(e);if(n)return n}catch{}return null}};import{readFileSync as B,readdirSync as H}from"fs";import{join as x}from"path";var $=new Set(["node_modules",".kanonak",".git","_site","build",".stage"]);function K(u,e=[]){for(let t of H(u,{withFileTypes:!0}))t.isDirectory()?$.has(t.name)||K(x(u,t.name),e):t.name.endsWith(".kan.yml")&&e.push(x(u,t.name));return e}async function j(u,e=new f,t={}){let n=new A(e);for(let m of K(u))try{let l=e.parse(B(m,"utf-8")),h=l.metadata?.namespace_,p=h?.version;h&&p&&await n.saveDocumentAsync(l,`${h.publisher}/${h.package_}@${p.major}.${p.minor}.${p.patch}`)}catch{}let o=new y(g(),!0,e),s=new Map,a=t.httpCache??{getFromCache:(m,l,h)=>s.get(`${m}|${l}|${h}`)??null,onFetch:(m,l,h,p)=>{s.set(`${m}|${l}|${h}`,p)}},r=new v({getFromCache:a.getFromCache,onFetch:a.onFetch});return new D(n,o,r)}export{y as a,S as b,k as c,g as d,C as e,D as f,K as g,j as h};
|