@kanonak-protocol/sdk 2.1.0 → 2.2.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/LICENSE +201 -0
- package/dist/browser.d.ts +4 -4
- package/dist/browser.js +17 -17
- package/dist/index.d.ts +6 -4
- package/dist/index.js +44 -43
- package/dist/lock/LockFile.d.ts +14 -0
- package/dist/lock/index.d.ts +2 -0
- package/dist/parsing/KanonakDocumentPositions.d.ts +185 -0
- package/dist/parsing/index.d.ts +4 -0
- package/dist/parsing/index.js +1 -1
- package/dist/parsing/parseWithPositions.d.ts +41 -0
- package/dist/repositories/FileSystemKanonakDocumentRepository.d.ts +0 -4
- package/dist/repositories/InMemoryKanonakDocumentRepository.d.ts +0 -4
- package/dist/repositories/browser.js +2 -2
- package/dist/repositories/index.js +2 -2
- package/dist/resolution/VersionUtils.d.ts +40 -0
- package/dist/resolution/index.d.ts +2 -0
- package/dist/resolution/index.js +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface LockEntry {
|
|
2
|
+
version: string;
|
|
3
|
+
resolved: string;
|
|
4
|
+
integrity: string;
|
|
5
|
+
dependencies: Record<string, string>;
|
|
6
|
+
}
|
|
7
|
+
export interface LockFile {
|
|
8
|
+
version: string;
|
|
9
|
+
lastUpdated: string;
|
|
10
|
+
packages: Record<string, LockEntry>;
|
|
11
|
+
}
|
|
12
|
+
export declare function loadLockFile(path?: string): LockFile | null;
|
|
13
|
+
export declare function saveLockFile(lock: LockFile, path?: string): void;
|
|
14
|
+
export declare function computeIntegrity(content: string): string;
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One entry in an entity's `imports:` block, paired with the source
|
|
3
|
+
* position of its `package:` value. Used by the VS Code extension's
|
|
4
|
+
* DocumentLinkProvider to make each import line a Ctrl-clickable
|
|
5
|
+
* link to the imported package's file.
|
|
6
|
+
*/
|
|
7
|
+
export interface ImportPackageEntry {
|
|
8
|
+
/** `publisher` from the outer import block (`publisher: kanonak.org`). */
|
|
9
|
+
publisher: string;
|
|
10
|
+
/** `package: <name>` of this entry. */
|
|
11
|
+
package_: string;
|
|
12
|
+
/** `version: <x.y.z>` of this entry, if present (empty string otherwise). */
|
|
13
|
+
version: string;
|
|
14
|
+
/** `alias: <prefix>` of this entry, if present. */
|
|
15
|
+
alias?: string;
|
|
16
|
+
/**
|
|
17
|
+
* Source range of the `<name>` token after `package:` — i.e. just
|
|
18
|
+
* the scalar value, not including the `package:` key. Diagnostic
|
|
19
|
+
* and click-target friendly.
|
|
20
|
+
*/
|
|
21
|
+
position: SourcePosition;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A source-position range within a `.kan.yml` document.
|
|
25
|
+
*
|
|
26
|
+
* All values are **0-indexed**, matching VS Code's `Position`/`Range`
|
|
27
|
+
* conventions. The yaml package's `LineCounter` is 1-indexed; the
|
|
28
|
+
* conversion happens inside `KanonakDocumentPositions` so callers
|
|
29
|
+
* never see the off-by-one.
|
|
30
|
+
*
|
|
31
|
+
* Range semantics: half-open. `endLine`/`endColumn` point one past
|
|
32
|
+
* the last character that belongs to the node. A single-line key
|
|
33
|
+
* `MyClass:` at line 5 col 0 of length 8 (excluding the colon) has
|
|
34
|
+
* `line=4, column=0, endLine=4, endColumn=7`.
|
|
35
|
+
*/
|
|
36
|
+
export interface SourcePosition {
|
|
37
|
+
line: number;
|
|
38
|
+
column: number;
|
|
39
|
+
endLine: number;
|
|
40
|
+
endColumn: number;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Position lookup over a parsed Kanonak document. Built by walking
|
|
44
|
+
* the `yaml` package's CST in parallel with the SDK's existing
|
|
45
|
+
* js-yaml-based `KanonakParser`. The two parsers operate on the same
|
|
46
|
+
* source bytes and produce consistent positions for any well-formed
|
|
47
|
+
* Kanonak YAML — they're both YAML 1.1/1.2 compliant.
|
|
48
|
+
*
|
|
49
|
+
* Three lookup levels, mirroring the structure of a Kanonak document:
|
|
50
|
+
*
|
|
51
|
+
* 1. **Entity** — the top-level key in `body` (e.g. `MyClass:`).
|
|
52
|
+
* The position covers the key itself (where to underline a
|
|
53
|
+
* "this entity has issue X" diagnostic).
|
|
54
|
+
* 2. **Property** — a nested key under an entity (e.g.
|
|
55
|
+
* `subClassOf:`). Position covers the property's key.
|
|
56
|
+
* 3. **Value** — a specific value within a property. For scalar
|
|
57
|
+
* values, the value's range. For list values, the indexed
|
|
58
|
+
* list-item's range.
|
|
59
|
+
*
|
|
60
|
+
* Callers fall back from value → property → entity → undefined as
|
|
61
|
+
* specificity decreases. The diagnostic provider in the VS Code
|
|
62
|
+
* extension uses this fall-through to land at the most precise
|
|
63
|
+
* available position for each `OntologyValidationError`.
|
|
64
|
+
*/
|
|
65
|
+
export declare class KanonakDocumentPositions {
|
|
66
|
+
private readonly entities;
|
|
67
|
+
/**
|
|
68
|
+
* entity name → range covering the entity's whole block (key plus
|
|
69
|
+
* value, including nested properties). Used by reverse-lookup
|
|
70
|
+
* helpers to answer "what entity is the cursor inside?" — the
|
|
71
|
+
* foundation for symbol-intelligence providers (DefinitionProvider,
|
|
72
|
+
* HoverProvider, etc.).
|
|
73
|
+
*/
|
|
74
|
+
private readonly entityBlocks;
|
|
75
|
+
/** entity name → property name → position of property key. */
|
|
76
|
+
private readonly properties;
|
|
77
|
+
/** entity name → property name → position of property value (scalar or full sequence). */
|
|
78
|
+
private readonly propertyValues;
|
|
79
|
+
/** entity name → property name → array of per-list-item positions (for list-valued properties). */
|
|
80
|
+
private readonly valueListItems;
|
|
81
|
+
/** entity name → list of import-package entries with source positions. */
|
|
82
|
+
private readonly importPackages;
|
|
83
|
+
/**
|
|
84
|
+
* Parse `content` as YAML and build the position index.
|
|
85
|
+
*
|
|
86
|
+
* If the document fails to parse via the yaml package, returns an
|
|
87
|
+
* empty index. Callers fall through to file-scope ranges. This is
|
|
88
|
+
* not a fallback that masks failure — empty positions is the
|
|
89
|
+
* factual answer to "where is X in this document?" when the
|
|
90
|
+
* document isn't parseable. Diagnostics produced for the same
|
|
91
|
+
* document via the SDK's `KanonakParser` will surface the parse
|
|
92
|
+
* error itself; the position index doesn't need to duplicate that.
|
|
93
|
+
*/
|
|
94
|
+
static fromContent(content: string): KanonakDocumentPositions;
|
|
95
|
+
/**
|
|
96
|
+
* Position of the entity's top-level key (e.g. the colon-key
|
|
97
|
+
* `MyClass:` at the start of its block).
|
|
98
|
+
*/
|
|
99
|
+
getEntityPosition(entityName: string): SourcePosition | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* Position spanning the entire entity block — its key plus all its
|
|
102
|
+
* property declarations and values, up to (but not including) the
|
|
103
|
+
* next top-level entity. Use for "is the cursor inside this entity?"
|
|
104
|
+
* style lookups.
|
|
105
|
+
*/
|
|
106
|
+
getEntityBlockPosition(entityName: string): SourcePosition | undefined;
|
|
107
|
+
/**
|
|
108
|
+
* The entity name whose block range contains the given position,
|
|
109
|
+
* or `undefined` if the position falls outside every entity block
|
|
110
|
+
* (e.g. blank lines between entities).
|
|
111
|
+
*/
|
|
112
|
+
findEntityAtPosition(line: number, column: number): string | undefined;
|
|
113
|
+
/**
|
|
114
|
+
* The (entityName, propertyName) pair whose property-value range
|
|
115
|
+
* (or, failing that, property-key range) contains the position.
|
|
116
|
+
* Returns `undefined` for either field that isn't matched, e.g.
|
|
117
|
+
* a position inside an entity but on a blank line returns the
|
|
118
|
+
* entity name only.
|
|
119
|
+
*/
|
|
120
|
+
findPropertyAtPosition(line: number, column: number): {
|
|
121
|
+
entityName: string;
|
|
122
|
+
propertyName?: string;
|
|
123
|
+
} | undefined;
|
|
124
|
+
/**
|
|
125
|
+
* Position of a property's key within an entity (e.g. the
|
|
126
|
+
* `subClassOf:` token within `MyClass:`).
|
|
127
|
+
*/
|
|
128
|
+
getPropertyPosition(entityName: string, propertyName: string): SourcePosition | undefined;
|
|
129
|
+
/**
|
|
130
|
+
* Position of a property's value (the scalar or the full
|
|
131
|
+
* sequence/map after the `propertyName:` token).
|
|
132
|
+
*/
|
|
133
|
+
getPropertyValuePosition(entityName: string, propertyName: string): SourcePosition | undefined;
|
|
134
|
+
/**
|
|
135
|
+
* Imports declared by the entity's `imports:` block, each with the
|
|
136
|
+
* source position of its `package:` token. Empty array when the
|
|
137
|
+
* entity has no imports (e.g., it's not a Package). Used by the
|
|
138
|
+
* extension's DocumentLinkProvider to make import lines
|
|
139
|
+
* Ctrl-clickable links to the imported package's file.
|
|
140
|
+
*/
|
|
141
|
+
getImportPackages(entityName: string): ImportPackageEntry[];
|
|
142
|
+
/**
|
|
143
|
+
* All import-package entries across every entity in the document.
|
|
144
|
+
* Convenience for callers that want to iterate every clickable
|
|
145
|
+
* import without first knowing which entity is the Package.
|
|
146
|
+
*/
|
|
147
|
+
getAllImportPackages(): Array<{
|
|
148
|
+
entityName: string;
|
|
149
|
+
entry: ImportPackageEntry;
|
|
150
|
+
}>;
|
|
151
|
+
/**
|
|
152
|
+
* Resolve the source-name key for a property by its **bare** local
|
|
153
|
+
* name — i.e., the segment after the last dot in an aliased form.
|
|
154
|
+
* Returns the actual source key as authored (`subClassOf` or
|
|
155
|
+
* `rdfs.subClassOf`) so callers can use it for downstream
|
|
156
|
+
* `getPropertyValuePosition` / `getListItemPosition` lookups.
|
|
157
|
+
*
|
|
158
|
+
* `subClassOf:` source → `findPropertySourceName(entity, 'subClassOf')`
|
|
159
|
+
* returns `'subClassOf'`.
|
|
160
|
+
*
|
|
161
|
+
* `rdfs.subClassOf:` source → same call returns `'rdfs.subClassOf'`.
|
|
162
|
+
*
|
|
163
|
+
* Used by reference-style providers that work from resolved
|
|
164
|
+
* predicate URIs (which only carry the bare local name) and need
|
|
165
|
+
* to find the corresponding position-index entry regardless of
|
|
166
|
+
* whether the author wrote the property with or without an alias
|
|
167
|
+
* prefix.
|
|
168
|
+
*/
|
|
169
|
+
findPropertySourceName(entityName: string, bareName: string): string | undefined;
|
|
170
|
+
/**
|
|
171
|
+
* Position of a specific list item within a list-valued property,
|
|
172
|
+
* or `undefined` if the property is not a sequence or the index
|
|
173
|
+
* is out of range. Use this for diagnostics that point at a
|
|
174
|
+
* particular bad entry inside a list (e.g. one bad URI in a
|
|
175
|
+
* `subClassOf: [GoodA, BadB, GoodC]` list).
|
|
176
|
+
*/
|
|
177
|
+
getListItemPosition(entityName: string, propertyName: string, listIndex: number): SourcePosition | undefined;
|
|
178
|
+
/**
|
|
179
|
+
* Most-specific available position for a diagnostic, falling
|
|
180
|
+
* through from list-item → property-value → property-key → entity.
|
|
181
|
+
* Returns `undefined` only when none of those are available, in
|
|
182
|
+
* which case the caller should use a file-scope range.
|
|
183
|
+
*/
|
|
184
|
+
getMostSpecificPosition(entityName?: string, propertyName?: string, listIndex?: number): SourcePosition | undefined;
|
|
185
|
+
}
|
package/dist/parsing/index.d.ts
CHANGED
|
@@ -2,5 +2,9 @@ export { KanonakParser } from './KanonakParser.js';
|
|
|
2
2
|
export { KanonakObjectParser } from './KanonakObjectParser.js';
|
|
3
3
|
export type { IKanonakObjectParser } from './IKanonakObjectParser.js';
|
|
4
4
|
export { PropertyMetadata } from './PropertyMetadata.js';
|
|
5
|
+
export { KanonakDocumentPositions } from './KanonakDocumentPositions.js';
|
|
6
|
+
export type { SourcePosition, ImportPackageEntry } from './KanonakDocumentPositions.js';
|
|
7
|
+
export { parseWithPositions } from './parseWithPositions.js';
|
|
8
|
+
export type { ParsedDocumentWithPositions } from './parseWithPositions.js';
|
|
5
9
|
export type { IKanonakParser } from '@kanonak-protocol/types/document/parsing';
|
|
6
10
|
export type { KanonakDocument, KanonakMetadata, Namespace, Import, Version, ParseResult, ParseError } from '@kanonak-protocol/types/document/models/types';
|
package/dist/parsing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var H=(u,e)=>()=>(u&&(e=u(u=0)),e);var U=(u,e)=>{for(var t in e)q(u,t,{get:e[t],enumerable:!0})};var F={};U(F,{KanonakUri:()=>v});var v,x=H(()=>{"use strict";v=class u{constructor(e,t,n,a){this.publisher=e;this.package_=t;this.name=n;this.version=a}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let n=t[0],a=t[1],r=n.split("/");if(r.length!==3)throw new Error(`Invalid kanonak URI path format: ${n}. Expected format: publisher/package/name`);let o=a.split(".").map(Number),i={major:o[0]||0,minor:o[1]||0,patch:o[2]||0,toString:()=>`${o[0]||0}.${o[1]||0}.${o[2]||0}`,equals:s=>!s||typeof s!="object"?!1:s.major===(o[0]||0)&&s.minor===(o[1]||0)&&s.patch===(o[2]||0),getHashCode:()=>(o[0]||0)<<20|(o[1]||0)<<10|(o[2]||0),compareTo:s=>(o[0]||0)!==s.major?(o[0]||0)-s.major:(o[1]||0)!==s.minor?(o[1]||0)-s.minor:(o[2]||0)-s.patch};return new u(r[0],r[1],r[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as D from"js-yaml";var j=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let a=D.load(e);if(!a||typeof a!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let r=this.extractMetadata(a),o=this.extractBody(a,r);return n={metadata:r,body:o,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(a){let r=a,o={message:r.message||"Unknown parse error",line:r.mark?.line??0,column:r.mark?.column??0,errorType:r.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${r.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${r.mark?.line??0}: ${r.message||"Unknown parse error"}`};return t.push(o),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,a={type:"Package",publisher:n.publisher};n.version&&(a.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(a.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=a}return Object.assign(t,e.body),D.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let a of Object.values(t))n.push(...a);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:r=>!r||typeof r!="object"?!1:r.major===e&&r.minor===t&&r.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:r=>e!==r.major?e-r.major:t!==r.minor?t-r.minor:n-r.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){t.type_="Package";let r=n,o=a.publisher,i=a.version?this.parseVersion(a.version):void 0;return o&&r&&(t.namespace_={publisher:o,package_:r,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===o&&s.package_===r&&(!i||!s.version||i.equals(s.version)),getHashCode:()=>{let s=0;for(let c=0;c<o.length;c++)s=(s<<5)-s+o.charCodeAt(c);for(let c=0;c<r.length;c++)s=(s<<5)-s+r.charCodeAt(c);return s|0}}),a.imports&&Array.isArray(a.imports)&&(t.imports=this.parseImportsV3(a.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},a;for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){a=r;break}for(let[r,o]of Object.entries(e))r!==a&&r!=="kanonak"&&r!=="namespace"&&r!=="imports"&&(n[r]=o);return n}parseNamespace(e){if(typeof e=="string"){let r=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(r){let o=r[3]?this.parseVersion(r[3]):this.createVersion(1,0,0);return{publisher:r[1],package_:r[2],version:o,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===r[1]&&i.package_===r[2]&&(!o||!i.version||o.equals(i.version)),getHashCode:()=>{let i=0;for(let s=0;s<r[1].length;s++)i=(i<<5)-i+r[1].charCodeAt(s);for(let s=0;s<r[2].length;s++)i=(i<<5)-i+r[2].charCodeAt(s);return i|0}}}}let t=e.publisher||"",n=e.package||"",a=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:a,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:r=>!r||typeof r!="object"?!1:r.publisher===t&&r.package_===n&&(!a||!r.version||a.equals(r.version)),getHashCode:()=>{let r=0;for(let o=0;o<t.length;o++)r=(r<<5)-r+t.charCodeAt(o);for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o);return r|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let a=n.publisher;if(!a)throw new Error("PublisherImport requires 'publisher' property");t[a]||(t[a]=[]);for(let r of n.packages){if(!r||typeof r!="object")continue;let o=this.parseImportFromEmbeddedObject(r,a);t[a].push(o)}}else{let a=this.parseImportFromEmbeddedObject(n,n.publisher),r=a.publisher||"";t[r]||(t[r]=[]),t[r].push(a)}return t}parseImportsLegacy(e){let t={};for(let[n,a]of Object.entries(e))Array.isArray(a)&&(t[n]=a.map(r=>this.parseImport(r,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let a=e.match;if(!a)throw new Error("Import requires 'match' property");let r=e.version;if(!r)throw new Error("Import requires 'version' property");let o=this.parseVersion(r),i=this.parseVersionOperator(a),s=this.calculateMaxVersion(a,o),c=e.alias;return{package_:`${n} ${a} ${o.toString()}`,publisher:t,packageName:n,versionOperator:i,version:o,alias:c,minVersion:o,maxVersion:s,toEmbeddedObject:()=>{let p={package:n,match:a,version:o.toString()};return c&&(p.alias=c),p},toString:()=>c?`${n} ${a} ${o.toString()} as ${c}`:`${n} ${a} ${o.toString()}`}}parseImport(e,t){if(typeof e=="string"){let s=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(s){let p=s[1].trim(),m=s[2],l=this.parseVersion(s[3].trim()),d=s[4].trim(),y=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:y,version:l,alias:d,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let k={package:p,match:m,version:l.toString()};return d&&(k.alias=d),k},toString:()=>`${p} ${m} ${l.toString()} as ${d}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),d=this.parseVersionOperator(m),y=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:l,alias:void 0,minVersion:l,maxVersion:y,toEmbeddedObject:()=>({package:p,match:m,version:l.toString()}),toString:()=>`${p} ${m} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),a=this.parseVersion(e.version||"1.0.0"),r=e.packageName||e.package||"",o=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",a);return{package_:e.package||"",publisher:t,packageName:r,versionOperator:n,version:a,alias:e.alias,minVersion:a,maxVersion:i,toEmbeddedObject:()=>{let s={package:r,match:o,version:a.toString()};return e.alias&&(s.alias=e.alias),s},toString:()=>`${r} ${o} ${a.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,a]of Object.entries(e)){let r={publisher:n,packages:a.map(o=>{let i=["=","~","^","*"][o.versionOperator],s={package:o.packageName,match:i,version:`${o.version.major}.${o.version.minor}.${o.version.patch}`};return o.alias&&(s.alias=o.alias),s})};t.push(r)}return t}};var b=class{};var R=class extends b{statement=[]};var I=class extends R{namespace;name;icon};var S=class extends R{};x();var f=class u extends b{subject;static parse(e){let t=new u;return t.subject=v.parse(e),t}};var A=class extends b{value};var g=class{predicate;object};var K=class extends g{};var P=class u extends K{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var E=class u extends K{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=t,n}};var O=class extends K{};var V=class u extends g{static parse(e,t){let n=new u;return n.predicate=f.parse(e),n.object=f.parse(t),n}};var w=class extends g{};var $=class extends g{};x();function N(u){if(Array.isArray(u))return u.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=u?.toString();return e?[e]:[]}var _=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let n=t.metadata?.namespace_?.toString()??"unknown",a=this.cache.get(n);if(a){let o=a.get(e);if(o)return o}let r=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(n,r),r.get(e)??null}async resolveAllEntitiesAsync(e,t){let n=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let a=e.split("."),r=a[0],o=a[1],i=await this.findDocumentForAlias(t,r);return i?await this.resolveAllEntitiesAsync(o,i):[]}return n.filter(a=>a.entityName===e)}async buildAllEntitiesIndexAsync(e,t,n){let a=[],r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`;for(let[i,s]of Object.entries(e.body))if(s&&typeof s=="object"&&!Array.isArray(s)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.push({entityName:i,uri:new v(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:s,definedInNamespace:r,isImported:n.length>0,importPath:o})}if(this.logger?.debug?.(`Collected ${a.length} entities from ${r}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((s,c)=>s+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${r}`);for(let[s,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${s}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(s,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,o);a.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${s}/${p.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${s}/${p.packageName} for namespace ${r}. Error: ${l.message}`,l),new Error(`Failed to process import ${s}/${p.packageName} for namespace ${r}. See inner exception for details.`,{cause:m})}}return a}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,n){let a=new Map,r=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${r}`),t.has(r))return this.logger?.debug?.(`Skipping ${r} - already visited (circular import prevention)`),a;t.add(r);let o=n.length===0?r:`${n} \u2192 ${r}`,i=0;for(let[s,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!a.has(s)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};a.set(s,{entityName:s,uri:new v(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,s,p),entity:c,definedInNamespace:r,isImported:n.length>0,importPath:o}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${r}`),e.metadata?.imports){let s=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${s} import(s) for ${r}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let d=await this.buildEntityIndexAsyncInternal(l,t,o),y=0;for(let[h,k]of d.entries())if(a.has(h)||(a.set(h,k),y++),m.alias&&!h.includes(".")){let T=`${m.alias}.${h}`;a.has(T)||(a.set(T,k),y++)}this.logger?.debug?.(`Merged ${y} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let d=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${r}. Error: ${d.message}`,d),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${r}. See inner exception for details.`,{cause:l})}}return a}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[n,a]of Object.entries(e.metadata.imports))for(let r of a){if(r.alias===t)return await this.repository.getHighestCompatibleVersionAsync(n,r);if(!r.alias&&r.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(n,r)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubclassOfRecursiveAsync(e,t,n,a)}async isSubclassOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subClassOf;if(o){let i=N(o);for(let s of i)if(s===t||await this.isSubclassOfRecursiveAsync(s,t,n,a))return!0}return!1}async isSubpropertyOfAsync(e,t,n){if(e===t)return!0;let a=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,n,a)}async isSubpropertyOfRecursiveAsync(e,t,n,a){if(a.has(e))return!1;a.add(e);let r=await this.resolveEntityAsync(e,n);if(!r?.entity)return!1;let o=r.entity.subPropertyOf;if(o){let i=N(o);for(let s of i)if(s===t||await this.isSubpropertyOfRecursiveAsync(s,t,n,a))return!0}return!1}};var M=class u{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&u.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return u.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let n=await this.resourceResolver.resolveEntityAsync(e,t);if(n){let a=n.entity.type;if(a){let r=String(a);return r==="Class"||r==="rdfs.Class"||r.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var C=class{constructor(e){}async parseKanonaks(e){let t=[],n=await e.getAllDocumentsAsync(),a=new _(e),r=new M(a);for(let o of n)for(let[i,s]of Object.entries(o.body)){let c=new I;c.namespace=o.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(s,o,a,r,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,n,a,r){let o=[];if(typeof e!="object"||e===null||Array.isArray(e))return o;for(let[i,s]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,n,r,a);if(!c)continue;let p=await this.parsePropertyValue(i,s,c,t,n,a);p&&o.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return o}async getPropertyMetadata(e,t,n,a,r){let o=await n.resolveEntityAsync(e,t);if(!o)return;let i=o.entity,s=i.type?.toString()??"",c=s.includes(".")?s.substring(s.lastIndexOf(".")+1):s;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=r.getPropertyTypeClassification(s),l=i.range?.toString(),d;if(m==="ObjectProperty")d="ObjectProperty";else if(m==="DatatypeProperty")d="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?r.isKnownXsdDatatypeName(l):!1)||h==="Literal"?d="DatatypeProperty":d="ObjectProperty"}return{propertyUri:o.uri.toString(),propertyType:d,range:l,isImported:o.isImported,definedInNamespace:o.definedInNamespace}}async parsePropertyValue(e,t,n,a,r,o){let i=n.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,n,a,r,o);if(n.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,n);if(n.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,n,a,r,o)}}parseDatatypeValue(e,t,n){if(t instanceof Date)return P.parse(e,t.toISOString());if(typeof t=="string")return P.parse(e,t);if(typeof t=="number")return E.parse(e,t);if(typeof t=="boolean"){let a=new O;return a.predicate=f.parse(e),a.object=t,a}}async parseObjectValue(e,t,n,a,r,o){if(typeof t=="string"){let i=await this.resolveReference(t,a,r);if(!i)return;let s=new V;return s.predicate=f.parse(e),s.object=i,s}if(typeof t=="object"&&!Array.isArray(t)){let i=new S;if(i.statement=await this.parseStatements(t,a,r,o,{}),i.statement.length>0){let p=new w;return p.predicate=f.parse(e),p.object=i,p}let s=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new S;m.statement=await this.parseStatements(p,a,r,o,{}),s.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&s.push(m)}if(s.length>0){let p=new $;return p.predicate=f.parse(e),p.object=s,p}let c=new w;return c.predicate=f.parse(e),c.object=i,c}}async parseListValue(e,t,n,a,r,o){let i=[],s=n.propertyType==="DatatypeProperty";for(let p of t){if(s&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let m=new A;m.value=p,i.push(m);continue}if(s&&p instanceof Date){let m=new A;m.value=p.toISOString(),i.push(m);continue}if(typeof p=="string"){let m=await this.resolveReference(p,a,r);m&&i.push(m)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new S;m.statement=await this.parseStatements(p,a,r,o,{}),i.push(m)}}let c=new $;return c.predicate=f.parse(e),c.object=i,c}async resolveReference(e,t,n){let a=await n.resolveEntityAsync(e,t);if(a){let o=new f;return o.subject=a.uri,o}let r=t.metadata?.namespace_;if(r){let{KanonakUri:o}=await Promise.resolve().then(()=>(x(),F)),i=r.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,d]of Object.entries(t.metadata.imports))for(let y of d)if((y.alias??y.packageName)===p){let k=new f;return k.subject=new o(l,y.packageName,m,y.version),k}}}let s=new f;return s.subject=new o(r.publisher,r.package_,e,i),s}return null}async saveKanonaks(e,t){let n=new Map;for(let a of e)a instanceof I&&a.namespace&&(n.has(a.namespace)||n.set(a.namespace,[]),n.get(a.namespace).push(a));for(let[a,r]of n){let o=await this.convertKanonaksToDocument(a,r),i=`${a.split("@")[0]}.yml`;await t.saveDocumentAsync(o,i)}}async serializeToYaml(e,t){let n=e.filter(o=>o instanceof I&&o.namespace===t);if(n.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let a=await this.convertKanonaksToDocument(t,n);return new j().save(a)}async convertKanonaksToDocument(e,t){let a={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let o=[];for(let i of Object.values(this.imports))o.push(...i);return o}},body:{}},r=new Map;for(let o of t){let i={};for(let s of o.statement){let[c,p]=this.convertStatementToProperty(s);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(s,e,r)}a.body[o.name]=i}return a}convertStatementToProperty(e){if(e instanceof P)return[e.predicate.subject.name,e.object];if(e instanceof E)return[e.predicate.subject.name,e.object];if(e instanceof O)return[e.predicate.subject.name,e.object];if(e instanceof V)return[e.predicate.subject.name,e.object.subject.name];if(e instanceof $){let t=this.convertKanonakListToValue(e.object);return[e.predicate.subject.name,t]}else if(e instanceof w){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let n of e)n instanceof f?t.push(n.subject.name):n instanceof S&&t.push(this.convertEmbeddedKanonakToValue(n));return t}convertEmbeddedKanonakToValue(e){let t={};for(let n of e.statement){let[a,r]=this.convertStatementToProperty(n);a&&r!==null&&r!==void 0&&(t[a]=r)}return t}collectImportsFromStatement(e,t,n){}};var L=class{propertyUri;propertyType;range;isImported;definedInNamespace};export{C as KanonakObjectParser,j as KanonakParser,L as PropertyMetadata};
|
|
1
|
+
var Q=Object.defineProperty;var Z=(u,e)=>()=>(u&&(e=u(u=0)),e);var ee=(u,e)=>{for(var t in e)Q(u,t,{get:e[t],enumerable:!0})};var G={};ee(G,{KanonakUri:()=>K});var K,q=Z(()=>{"use strict";K=class u{constructor(e,t,r,o){this.publisher=e;this.package_=t;this.name=r;this.version=o}publisher;package_;name;version;static parse(e){if(!e||e.trim().length===0)throw new Error("Kanonak URI string cannot be null or empty");let t=e.split("@");if(t.length!==2)throw new Error(`Invalid kanonak URI format: ${e}. Expected format: publisher/package/name@version`);let r=t[0],o=t[1],n=r.split("/");if(n.length!==3)throw new Error(`Invalid kanonak URI path format: ${r}. Expected format: publisher/package/name`);let s=o.split(".").map(Number),i={major:s[0]||0,minor:s[1]||0,patch:s[2]||0,toString:()=>`${s[0]||0}.${s[1]||0}.${s[2]||0}`,equals:a=>!a||typeof a!="object"?!1:a.major===(s[0]||0)&&a.minor===(s[1]||0)&&a.patch===(s[2]||0),getHashCode:()=>(s[0]||0)<<20|(s[1]||0)<<10|(s[2]||0),compareTo:a=>(s[0]||0)!==a.major?(s[0]||0)-a.major:(s[1]||0)!==a.minor?(s[1]||0)-a.minor:(s[2]||0)-a.patch};return new u(n[0],n[1],n[2],i)}toString(){return`${this.publisher}/${this.package_}/${this.name}@${this.version.major}.${this.version.minor}.${this.version.patch}`}}});import*as F from"js-yaml";var w=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let o=F.load(e);if(!o||typeof o!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let n=this.extractMetadata(o),s=this.extractBody(o,n);return r={metadata:n,body:s,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(o){let n=o,s={message:n.message||"Unknown parse error",line:n.mark?.line??0,column:n.mark?.column??0,errorType:n.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${n.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${n.mark?.line??0}: ${n.message||"Unknown parse error"}`};return t.push(s),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,o={type:"Package",publisher:r.publisher};r.version&&(o.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(o.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=o}return Object.assign(t,e.body),F.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let o of Object.values(t))r.push(...o);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:n=>!n||typeof n!="object"?!1:n.major===e&&n.minor===t&&n.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:n=>e!==n.major?e-n.major:t!==n.minor?t-n.minor:r-n.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,o]of Object.entries(e))if(o&&typeof o=="object"&&o.type==="Package"){t.type_="Package";let n=r,s=o.publisher,i=o.version?this.parseVersion(o.version):void 0;return s&&n&&(t.namespace_={publisher:s,package_:n,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:a=>!a||typeof a!="object"?!1:a.publisher===s&&a.package_===n&&(!i||!a.version||i.equals(a.version)),getHashCode:()=>{let a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c);for(let c=0;c<n.length;c++)a=(a<<5)-a+n.charCodeAt(c);return a|0}}),o.imports&&Array.isArray(o.imports)&&(t.imports=this.parseImportsV3(o.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},o;for(let[n,s]of Object.entries(e))if(s&&typeof s=="object"&&s.type==="Package"){o=n;break}for(let[n,s]of Object.entries(e))n!==o&&n!=="kanonak"&&n!=="namespace"&&n!=="imports"&&(r[n]=s);return r}parseNamespace(e){if(typeof e=="string"){let n=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(n){let s=n[3]?this.parseVersion(n[3]):this.createVersion(1,0,0);return{publisher:n[1],package_:n[2],version:s,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===n[1]&&i.package_===n[2]&&(!s||!i.version||s.equals(i.version)),getHashCode:()=>{let i=0;for(let a=0;a<n[1].length;a++)i=(i<<5)-i+n[1].charCodeAt(a);for(let a=0;a<n[2].length;a++)i=(i<<5)-i+n[2].charCodeAt(a);return i|0}}}}let t=e.publisher||"",r=e.package||"",o=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:o,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:n=>!n||typeof n!="object"?!1:n.publisher===t&&n.package_===r&&(!o||!n.version||o.equals(n.version)),getHashCode:()=>{let n=0;for(let s=0;s<t.length;s++)n=(n<<5)-n+t.charCodeAt(s);for(let s=0;s<r.length;s++)n=(n<<5)-n+r.charCodeAt(s);return n|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let o=r.publisher;if(!o)throw new Error("PublisherImport requires 'publisher' property");t[o]||(t[o]=[]);for(let n of r.packages){if(!n||typeof n!="object")continue;let s=this.parseImportFromEmbeddedObject(n,o);t[o].push(s)}}else{let o=this.parseImportFromEmbeddedObject(r,r.publisher),n=o.publisher||"";t[n]||(t[n]=[]),t[n].push(o)}return t}parseImportsLegacy(e){let t={};for(let[r,o]of Object.entries(e))Array.isArray(o)&&(t[r]=o.map(n=>this.parseImport(n,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let o=e.match;if(!o)throw new Error("Import requires 'match' property");let n=e.version;if(!n)throw new Error("Import requires 'version' property");let s=this.parseVersion(n),i=this.parseVersionOperator(o),a=this.calculateMaxVersion(o,s),c=e.alias;return{package_:`${r} ${o} ${s.toString()}`,publisher:t,packageName:r,versionOperator:i,version:s,alias:c,minVersion:s,maxVersion:a,toEmbeddedObject:()=>{let p={package:r,match:o,version:s.toString()};return c&&(p.alias=c),p},toString:()=>c?`${r} ${o} ${s.toString()} as ${c}`:`${r} ${o} ${s.toString()}`}}parseImport(e,t){if(typeof e=="string"){let a=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(a){let p=a[1].trim(),m=a[2],l=this.parseVersion(a[3].trim()),f=a[4].trim(),d=this.parseVersionOperator(m),h=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:d,version:l,alias:f,minVersion:l,maxVersion:h,toEmbeddedObject:()=>{let g={package:p,match:m,version:l.toString()};return f&&(g.alias=f),g},toString:()=>`${p} ${m} ${l.toString()} as ${f}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let p=c[1].trim(),m=c[2],l=this.parseVersion(c[3].trim()),f=this.parseVersionOperator(m),d=this.calculateMaxVersion(m,l);return{package_:e,publisher:t,packageName:p,versionOperator:f,version:l,alias:void 0,minVersion:l,maxVersion:d,toEmbeddedObject:()=>({package:p,match:m,version:l.toString()}),toString:()=>`${p} ${m} ${l.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),o=this.parseVersion(e.version||"1.0.0"),n=e.packageName||e.package||"",s=["=","~","^","*"][r],i=this.calculateMaxVersion(e.operator||"~",o);return{package_:e.package||"",publisher:t,packageName:n,versionOperator:r,version:o,alias:e.alias,minVersion:o,maxVersion:i,toEmbeddedObject:()=>{let a={package:n,match:s,version:o.toString()};return e.alias&&(a.alias=e.alias),a},toString:()=>`${n} ${s} ${o.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,o]of Object.entries(e)){let n={publisher:r,packages:o.map(s=>{let i=["=","~","^","*"][s.versionOperator],a={package:s.packageName,match:i,version:`${s.version.major}.${s.version.minor}.${s.version.patch}`};return s.alias&&(a.alias=s.alias),a})};t.push(n)}return t}};var S=class{};var E=class extends S{statement=[]};var j=class extends E{namespace;name;icon};var $=class extends E{};q();var y=class u extends S{subject;static parse(e){let t=new u;return t.subject=K.parse(e),t}};var M=class extends S{value};var v=class{predicate;object};var I=class extends v{};var A=class u extends I{static parse(e,t){let r=new u;return r.predicate=y.parse(e),r.object=t,r}};var _=class u extends I{static parse(e,t){let r=new u;return r.predicate=y.parse(e),r.object=t,r}};var N=class extends I{};var L=class u extends v{static parse(e,t){let r=new u;return r.predicate=y.parse(e),r.object=y.parse(t),r}};var D=class extends v{};var V=class extends v{};q();function H(u){if(Array.isArray(u))return u.map(t=>t?.toString()??"").filter(t=>t.length>0);let e=u?.toString();return e?[e]:[]}var W=class{cache=new Map;repository;logger;constructor(e,t){this.repository=e,this.logger=t}async resolveEntityAsync(e,t){let r=t.metadata?.namespace_?.toString()??"unknown",o=this.cache.get(r);if(o){let s=o.get(e);if(s)return s}let n=await this.buildEntityIndexAsyncInternal(t,new Set,"");return this.cache.set(r,n),n.get(e)??null}async resolveAllEntitiesAsync(e,t){let r=await this.buildAllEntitiesIndexAsync(t,new Set,"");if(e.includes(".")){let o=e.split("."),n=o[0],s=o[1],i=await this.findDocumentForAlias(t,n);return i?await this.resolveAllEntitiesAsync(s,i):[]}return r.filter(o=>o.entityName===e)}async buildAllEntitiesIndexAsync(e,t,r){let o=[],n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building ALL entities index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let s=r.length===0?n:`${r} \u2192 ${n}`;for(let[i,a]of Object.entries(e.body))if(a&&typeof a=="object"&&!Array.isArray(a)){let c=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.push({entityName:i,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,i,c),entity:a,definedInNamespace:n,isImported:r.length>0,importPath:s})}if(this.logger?.debug?.(`Collected ${o.length} entities from ${n}`),e.metadata?.imports){let i=Object.values(e.metadata.imports).reduce((a,c)=>a+c.length,0);this.logger?.debug?.(`Processing ${i} import(s) for ${n}`);for(let[a,c]of Object.entries(e.metadata.imports))for(let p of c)try{this.logger?.debug?.(`Resolving import: ${a}/${p.packageName}`);let m=await this.repository.getHighestCompatibleVersionAsync(a,p);if(m){this.logger?.debug?.(`Successfully loaded import: ${m.metadata?.namespace_?.toString()}`);let l=await this.buildAllEntitiesIndexAsync(m,t,s);o.push(...l),this.logger?.debug?.(`Added ${l.length} entities from import ${m.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${a}/${p.packageName}`)}catch(m){let l=m;throw this.logger?.error?.(`Failed to process import ${a}/${p.packageName} for namespace ${n}. Error: ${l.message}`,l),new Error(`Failed to process import ${a}/${p.packageName} for namespace ${n}. See inner exception for details.`,{cause:m})}}return o}async buildEntityIndexAsync(e){return await this.buildEntityIndexAsyncInternal(e,new Set,"")}async buildEntityIndexAsyncInternal(e,t,r){let o=new Map,n=e.metadata?.namespace_?.toString()??"unknown";if(this.logger?.debug?.(`Building entity index for namespace: ${n}`),t.has(n))return this.logger?.debug?.(`Skipping ${n} - already visited (circular import prevention)`),o;t.add(n);let s=r.length===0?n:`${r} \u2192 ${n}`,i=0;for(let[a,c]of Object.entries(e.body))if(c&&typeof c=="object"&&!Array.isArray(c)&&!o.has(a)){let p=e.metadata.namespace_?.version??{major:1,minor:0,patch:0,toString:()=>"1.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};o.set(a,{entityName:a,uri:new K(e.metadata.namespace_.publisher,e.metadata.namespace_.package_,a,p),entity:c,definedInNamespace:n,isImported:r.length>0,importPath:s}),i++}if(this.logger?.debug?.(`Indexed ${i} entities from ${n}`),e.metadata?.imports){let a=Object.values(e.metadata.imports).reduce((c,p)=>c+p.length,0);this.logger?.debug?.(`Processing ${a} import(s) for ${n}`);for(let[c,p]of Object.entries(e.metadata.imports))for(let m of p)try{this.logger?.debug?.(`Resolving import: ${c}/${m.packageName}`);let l=await this.repository.getHighestCompatibleVersionAsync(c,m);if(l){this.logger?.debug?.(`Successfully loaded import: ${l.metadata?.namespace_?.toString()}`);let f=await this.buildEntityIndexAsyncInternal(l,t,s),d=0;for(let[h,g]of f.entries())if(o.has(h)||(o.set(h,g),d++),m.alias&&!h.includes(".")){let P=`${m.alias}.${h}`;o.has(P)||(o.set(P,g),d++)}this.logger?.debug?.(`Merged ${d} entities from import ${l.metadata?.namespace_?.toString()}`)}else this.logger?.warn?.(`Failed to load import: ${c}/${m.packageName}`)}catch(l){let f=l;throw this.logger?.error?.(`Failed to process import ${c}/${m.packageName} for namespace ${n}. Error: ${f.message}`,f),new Error(`Failed to process import ${c}/${m.packageName} for namespace ${n}. See inner exception for details.`,{cause:l})}}return o}async findDocumentForAlias(e,t){if(!e.metadata?.imports)return null;for(let[r,o]of Object.entries(e.metadata.imports))for(let n of o){if(n.alias===t)return await this.repository.getHighestCompatibleVersionAsync(r,n);if(!n.alias&&n.packageName===t)return await this.repository.getHighestCompatibleVersionAsync(r,n)}return null}clearCache(){this.cache.clear()}clearCacheForDocument(e){this.cache.delete(e)}async isSubclassOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubclassOfRecursiveAsync(e,t,r,o)}async isSubclassOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let s=n.entity.subClassOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubclassOfRecursiveAsync(a,t,r,o))return!0}return!1}async isSubpropertyOfAsync(e,t,r){if(e===t)return!0;let o=new Set;return await this.isSubpropertyOfRecursiveAsync(e,t,r,o)}async isSubpropertyOfRecursiveAsync(e,t,r,o){if(o.has(e))return!1;o.add(e);let n=await this.resolveEntityAsync(e,r);if(!n?.entity)return!1;let s=n.entity.subPropertyOf;if(s){let i=H(s);for(let a of i)if(a===t||await this.isSubpropertyOfRecursiveAsync(a,t,r,o))return!0}return!1}};var X=class u{static KNOWN_XSD_DATATYPES=new Set(["string","integer","int","boolean","bool","decimal","float","double","date","datetime","time","duration","anyuri","base64binary","hexbinary","long","short","byte","nonnegativeinteger","positiveinteger","negativeinteger","nonpositiveinteger","unsignedint","unsignedlong","unsignedshort","unsignedbyte"]);resourceResolver;constructor(e){this.resourceResolver=e}isXsdDatatype(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.xsd"&&u.KNOWN_XSD_DATATYPES.has(e.name.toLowerCase()):!1}isLiteralType(e){return e?e.publisher==="kanonak.org"&&e.package_==="core.rdf"&&e.name==="Literal":!1}isKnownXsdDatatypeName(e){let t=e.includes(".")?e.split(".")[1]:e;return u.KNOWN_XSD_DATATYPES.has(t.toLowerCase())}async isClassTypeAsync(e,t){if(this.isKnownXsdDatatypeName(e))return!1;let r=await this.resourceResolver.resolveEntityAsync(e,t);if(r){let o=r.entity.type;if(o){let n=String(o);return n==="Class"||n==="rdfs.Class"||n.endsWith(".Class")}}return!0}getPropertyTypeClassification(e){if(!e||e.trim().length===0)return"Property";switch(e.includes(".")?e.split(".")[1]:e){case"DatatypeProperty":return"DatatypeProperty";case"ObjectProperty":return"ObjectProperty";case"AnnotationProperty":return"AnnotationProperty";case"Property":return"Property";default:return"Property"}}isEffectiveDatatypeProperty(e,t){return!!(e==="DatatypeProperty"||e==="Property"&&this.isXsdDatatype(t)||e==="Property"&&this.isLiteralType(t))}isEffectiveObjectProperty(e,t){return!!(e==="ObjectProperty"||e==="Property"&&t&&!this.isXsdDatatype(t)&&!this.isLiteralType(t))}};var U=class{constructor(e){}async parseKanonaks(e){let t=[],r=await e.getAllDocumentsAsync(),o=new W(e),n=new X(o);for(let s of r)for(let[i,a]of Object.entries(s.body)){let c=new j;c.namespace=s.metadata.namespace_?.toString()??"",c.name=i,c.statement=[];let p=await this.parseStatements(a,s,o,n,e);c.statement.push(...p),t.push(c)}return t}async parseStatements(e,t,r,o,n){let s=[];if(typeof e!="object"||e===null||Array.isArray(e))return s;for(let[i,a]of Object.entries(e))try{let c=await this.getPropertyMetadata(i,t,r,n,o);if(!c)continue;let p=await this.parsePropertyValue(i,a,c,t,r,o);p&&s.push(p)}catch(c){console.error(`Error parsing property ${i}:`,c)}return s}async getPropertyMetadata(e,t,r,o,n){let s=await r.resolveEntityAsync(e,t);if(!s)return;let i=s.entity,a=i.type?.toString()??"",c=a.includes(".")?a.substring(a.lastIndexOf(".")+1):a;if(!new Set(["Property","DatatypeProperty","ObjectProperty","AnnotationProperty"]).has(c))return;let m=n.getPropertyTypeClassification(a),l=i.range?.toString(),f;if(m==="ObjectProperty")f="ObjectProperty";else if(m==="DatatypeProperty")f="DatatypeProperty";else{let h=l&&l.includes(".")?l.substring(l.lastIndexOf(".")+1):l??"";(l?n.isKnownXsdDatatypeName(l):!1)||h==="Literal"?f="DatatypeProperty":f="ObjectProperty"}return{propertyUri:s.uri.toString(),propertyType:f,range:l,isImported:s.isImported,definedInNamespace:s.definedInNamespace}}async parsePropertyValue(e,t,r,o,n,s){let i=r.propertyUri;if(t!=null){if(Array.isArray(t))return this.parseListValue(i,t,r,o,n,s);if(r.propertyType==="DatatypeProperty")return this.parseDatatypeValue(i,t,r);if(r.propertyType==="ObjectProperty")return this.parseObjectValue(i,t,r,o,n,s)}}parseDatatypeValue(e,t,r){if(t instanceof Date)return A.parse(e,t.toISOString());if(typeof t=="string")return A.parse(e,t);if(typeof t=="number")return _.parse(e,t);if(typeof t=="boolean"){let o=new N;return o.predicate=y.parse(e),o.object=t,o}}async parseObjectValue(e,t,r,o,n,s){if(typeof t=="string"){let i=await this.resolveReference(t,o,n);if(!i)return;let a=new L;return a.predicate=y.parse(e),a.object=i,a}if(typeof t=="object"&&!Array.isArray(t)){let i=new $;if(i.statement=await this.parseStatements(t,o,n,s,{}),i.statement.length>0){let p=new D;return p.predicate=y.parse(e),p.object=i,p}let a=[];for(let[,p]of Object.entries(t))if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new $;m.statement=await this.parseStatements(p,o,n,s,{}),a.push(m)}else if(typeof p=="string"){let m=await this.resolveReference(p,o,n);m&&a.push(m)}if(a.length>0){let p=new V;return p.predicate=y.parse(e),p.object=a,p}let c=new D;return c.predicate=y.parse(e),c.object=i,c}}async parseListValue(e,t,r,o,n,s){let i=[],a=r.propertyType==="DatatypeProperty";for(let p of t){if(a&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")){let m=new M;m.value=p,i.push(m);continue}if(a&&p instanceof Date){let m=new M;m.value=p.toISOString(),i.push(m);continue}if(typeof p=="string"){let m=await this.resolveReference(p,o,n);m&&i.push(m)}else if(typeof p=="object"&&p!==null&&!Array.isArray(p)){let m=new $;m.statement=await this.parseStatements(p,o,n,s,{}),i.push(m)}}let c=new V;return c.predicate=y.parse(e),c.object=i,c}async resolveReference(e,t,r){let o=await r.resolveEntityAsync(e,t);if(o){let s=new y;return s.subject=o.uri,s}let n=t.metadata?.namespace_;if(n){let{KanonakUri:s}=await Promise.resolve().then(()=>(q(),G)),i=n.version??{major:0,minor:0,patch:0,toString:()=>"0.0.0",equals:()=>!1,getHashCode:()=>0,compareTo:()=>0};if(e.includes(".")){let c=e.indexOf("."),p=e.substring(0,c),m=e.substring(c+1);if(t.metadata?.imports){for(let[l,f]of Object.entries(t.metadata.imports))for(let d of f)if((d.alias??d.packageName)===p){let g=new y;return g.subject=new s(l,d.packageName,m,d.version),g}}}let a=new y;return a.subject=new s(n.publisher,n.package_,e,i),a}return null}async saveKanonaks(e,t){let r=new Map;for(let o of e)o instanceof j&&o.namespace&&(r.has(o.namespace)||r.set(o.namespace,[]),r.get(o.namespace).push(o));for(let[o,n]of r){let s=await this.convertKanonaksToDocument(o,n),i=`${o.split("@")[0]}.yml`;await t.saveDocumentAsync(s,i)}}async serializeToYaml(e,t){let r=e.filter(s=>s instanceof j&&s.namespace===t);if(r.length===0)throw new Error(`No kanonaks found with namespace '${t}'`);let o=await this.convertKanonaksToDocument(t,r);return new w().save(o)}async convertKanonaksToDocument(e,t){let o={metadata:{namespace_:e,get allImports(){if(!this.imports)return[];let s=[];for(let i of Object.values(this.imports))s.push(...i);return s}},body:{}},n=new Map;for(let s of t){let i={};for(let a of s.statement){let[c,p]=this.convertStatementToProperty(a);c&&p!==null&&p!==void 0&&(i[c]=p),this.collectImportsFromStatement(a,e,n)}o.body[s.name]=i}return o}convertStatementToProperty(e){if(e instanceof A)return[e.predicate.subject.name,e.object];if(e instanceof _)return[e.predicate.subject.name,e.object];if(e instanceof N)return[e.predicate.subject.name,e.object];if(e instanceof L)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 D){let t=this.convertEmbeddedKanonakToValue(e.object);return[e.predicate.subject.name,t]}return[null,null]}convertKanonakListToValue(e){let t=[];for(let r of e)r instanceof y?t.push(r.subject.name):r instanceof $&&t.push(this.convertEmbeddedKanonakToValue(r));return t}convertEmbeddedKanonakToValue(e){let t={};for(let r of e.statement){let[o,n]=this.convertStatementToProperty(r);o&&n!==null&&n!==void 0&&(t[o]=n)}return t}collectImportsFromStatement(e,t,r){}};var Y=class{propertyUri;propertyType;range;isImported;definedInNamespace};import{parseDocument as te,LineCounter as re,isMap as T,isPair as k,isScalar as b,isSeq as z}from"yaml";var C=class u{entities=new Map;entityBlocks=new Map;properties=new Map;propertyValues=new Map;valueListItems=new Map;importPackages=new Map;static fromContent(e){let t=new u,r=new re,o=te(e,{lineCounter:r});if(o.errors.length>0||!T(o.contents))return t;for(let n of o.contents.items){if(!k(n)||!b(n.key))continue;let s=String(n.key.value),i=n.key.range;if(!i)continue;t.entities.set(s,R(i,r));let a=n.value,c=a&&typeof a=="object"&&"range"in a?a.range:void 0;if(c?t.entityBlocks.set(s,R([i[0],i[1],c[2]],r)):t.entityBlocks.set(s,R(i,r)),T(n.value)){let p=new Map,m=new Map,l=new Map;for(let d of n.value.items){if(!k(d)||!b(d.key))continue;let h=String(d.key.value),g=d.key.range;g&&p.set(h,R(g,r));let P=d.value;if(P&&typeof P=="object"&&"range"in P&&Array.isArray(P.range)){let x=P.range;m.set(h,R(x,r))}if(z(P)){let x=[];for(let O of P.items)O&&typeof O=="object"&&"range"in O&&Array.isArray(O.range)&&x.push(R(O.range,r));x.length>0&&l.set(h,x)}}p.size>0&&t.properties.set(s,p),m.size>0&&t.propertyValues.set(s,m),l.size>0&&t.valueListItems.set(s,l);let f=ne(n.value,r);f.length>0&&t.importPackages.set(s,f)}}return t}getEntityPosition(e){return this.entities.get(e)}getEntityBlockPosition(e){return this.entityBlocks.get(e)}findEntityAtPosition(e,t){for(let[r,o]of this.entityBlocks)if(B(o,e,t))return r}findPropertyAtPosition(e,t){let r=this.findEntityAtPosition(e,t);if(!r)return;let o=this.properties.get(r),n=this.propertyValues.get(r);if(!o&&!n)return{entityName:r};let s,i;if(n)for(let[a,c]of n)B(c,e,t)&&(!i||J(c,i))&&(s=a,i=c);if(o)for(let[a,c]of o)B(c,e,t)&&(!i||J(c,i))&&(s=a,i=c);return s?{entityName:r,propertyName:s}:{entityName:r}}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,r]of this.importPackages)for(let o of r)e.push({entityName:t,entry:o});return e}findPropertySourceName(e,t){let r=this.properties.get(e);if(r){if(r.has(t))return t;for(let o of r.keys()){let n=o.lastIndexOf(".");if((n===-1?o:o.substring(n+1))===t)return o}}}getListItemPosition(e,t,r){let o=this.valueListItems.get(e)?.get(t);if(!(!o||r<0||r>=o.length))return o[r]}getMostSpecificPosition(e,t,r){if(e){if(t!==void 0){if(r!==void 0){let s=this.getListItemPosition(e,t,r);if(s)return s}let o=this.getPropertyValuePosition(e,t);if(o)return o;let n=this.getPropertyPosition(e,t);if(n)return n}return this.getEntityPosition(e)}}};function ne(u,e){let t=[];if(!T(u))return t;let r=u.items.find(o=>k(o)&&b(o.key)&&String(o.key.value)==="imports");if(!r||!k(r)||!z(r.value))return t;for(let o of r.value.items){if(!T(o))continue;let n=o.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="publisher");if(!n||!k(n)||!b(n.value))continue;let s=String(n.value.value),i=o.items.find(a=>k(a)&&b(a.key)&&String(a.key.value)==="packages");if(!(!i||!k(i)||!z(i.value)))for(let a of i.value.items){if(!T(a))continue;let c=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="package");if(!c||!k(c)||!b(c.value)||!c.value.range)continue;let p=String(c.value.value),m=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="version"),l=m&&k(m)&&b(m.value)?String(m.value.value):"",f=a.items.find(g=>k(g)&&b(g.key)&&String(g.key.value)==="alias"),d=f&&k(f)&&b(f.value)?String(f.value.value):void 0,h=d!==void 0?{publisher:s,package_:p,version:l,alias:d,position:R(c.value.range,e)}:{publisher:s,package_:p,version:l,position:R(c.value.range,e)};t.push(h)}}return t}function B(u,e,t){return!(e<u.line||e>u.endLine||e===u.line&&t<u.column||e===u.endLine&&t>u.endColumn)}function J(u,e){let t=u.endLine-u.line,r=e.endLine-e.line;if(t!==r)return t<r;let o=u.endLine===u.line?u.endColumn-u.column:Number.MAX_SAFE_INTEGER,n=e.endLine===e.line?e.endColumn-e.column:Number.MAX_SAFE_INTEGER;return o<n}function R(u,e){let t=e.linePos(u[0]),r=e.linePos(u[2]);return{line:t.line-1,column:t.col-1,endLine:r.line-1,endColumn:r.col-1}}function oe(u,e){let r=(e??new w).parse(u),o=C.fromContent(u);return{document:r,positions:o}}export{C as KanonakDocumentPositions,U as KanonakObjectParser,w as KanonakParser,Y as PropertyMetadata,oe as parseWithPositions};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { KanonakDocument } from '@kanonak-protocol/types/document/models/types';
|
|
2
|
+
import { KanonakParser } from './KanonakParser.js';
|
|
3
|
+
import { KanonakDocumentPositions } from './KanonakDocumentPositions.js';
|
|
4
|
+
/**
|
|
5
|
+
* Result of `parseWithPositions`: the parsed document object model
|
|
6
|
+
* (built by the SDK's existing `KanonakParser`) plus a parallel
|
|
7
|
+
* source-position index (built by walking the yaml package's CST
|
|
8
|
+
* over the same source bytes).
|
|
9
|
+
*
|
|
10
|
+
* Both halves come from the same input string. They are consistent
|
|
11
|
+
* for any well-formed Kanonak document. Edge cases where the two
|
|
12
|
+
* parsers might disagree (rare YAML features like custom tags or
|
|
13
|
+
* merge keys) cause the position index to be empty rather than
|
|
14
|
+
* incorrect — the document still parses cleanly into its object
|
|
15
|
+
* model; consumers fall back to file-scope ranges for that document.
|
|
16
|
+
*/
|
|
17
|
+
export interface ParsedDocumentWithPositions {
|
|
18
|
+
document: KanonakDocument;
|
|
19
|
+
positions: KanonakDocumentPositions;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Parse a `.kan.yml` source string into the SDK object model and
|
|
23
|
+
* build a position index in parallel.
|
|
24
|
+
*
|
|
25
|
+
* Two parses run on the same content:
|
|
26
|
+
*
|
|
27
|
+
* 1. `KanonakParser.parse(content)` — produces the typed
|
|
28
|
+
* `KanonakDocument` consumers already know how to walk.
|
|
29
|
+
* 2. `KanonakDocumentPositions.fromContent(content)` — walks the
|
|
30
|
+
* yaml package's CST to produce per-entity / per-property /
|
|
31
|
+
* per-list-item source positions.
|
|
32
|
+
*
|
|
33
|
+
* The two passes are intentionally decoupled. The object-model parse
|
|
34
|
+
* remains the source of truth for document shape; the position index
|
|
35
|
+
* is purely informational, used for diagnostic ranges and
|
|
36
|
+
* symbol-intelligence providers (Definition, Hover, etc.).
|
|
37
|
+
*
|
|
38
|
+
* Pass an existing `KanonakParser` instance to share its caches with
|
|
39
|
+
* other call sites; otherwise a fresh one is constructed.
|
|
40
|
+
*/
|
|
41
|
+
export declare function parseWithPositions(content: string, parser?: KanonakParser): ParsedDocumentWithPositions;
|
|
@@ -24,9 +24,5 @@ export declare class FileSystemKanonakDocumentRepository implements IKanonakDocu
|
|
|
24
24
|
refreshAsync(): Promise<void>;
|
|
25
25
|
private ensureCacheInitialized;
|
|
26
26
|
private loadDocuments;
|
|
27
|
-
private versionsEqual;
|
|
28
|
-
private compareVersions;
|
|
29
|
-
private isCompatibleVersion;
|
|
30
|
-
private isMajorCompatible;
|
|
31
27
|
private findYamlFiles;
|
|
32
28
|
}
|
|
@@ -16,8 +16,4 @@ export declare class InMemoryKanonakDocumentRepository implements IKanonakDocume
|
|
|
16
16
|
getAllDocumentReferencesAsync(): Promise<DocumentReference[]>;
|
|
17
17
|
getDocumentContentAsync(identifier: string): Promise<string | null>;
|
|
18
18
|
getDocumentUriAsync(identifier: string): Promise<string | null>;
|
|
19
|
-
private versionsEqual;
|
|
20
|
-
private compareVersions;
|
|
21
|
-
private isCompatibleVersion;
|
|
22
|
-
private isMajorCompatible;
|
|
23
19
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var b=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let r=[];for(let n of this.documents.values())n.metadata?.namespace_?.publisher===e&&n.metadata?.namespace_?.package_===t&&r.push(n);return r}async getHighestCompatibleVersionAsync(e,t){let r=[];for(let s of this.documents.values())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0&&r.push(s);if(r.length===0)return null;let n=r.filter(s=>{let a=s.metadata.namespace_.version;if(!a)return!1;switch(t.versionOperator){case 0:return this.versionsEqual(a,t.version);case 1:return this.isCompatibleVersion(a,t.version);case 2:return this.isMajorCompatible(a,t.version);case 3:return this.compareVersions(a,t.minVersion)>=0;default:return!1}});return n.length===0?null:(n.sort((s,a)=>{let i=s.metadata.namespace_.version,o=a.metadata.namespace_.version;return!i&&!o?0:i?o?this.compareVersions(o,i):-1:1}),n[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let r=this.parser.save(e);this.documentContents.set(t,r)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let r=[];for(let[n,s]of this.documents.entries())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t&&r.push(n);for(let n of r)this.documents.delete(n),this.documentContents.delete(n)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let r=this.documents.get(e);return r!==void 0?this.parser.save(r):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}versionsEqual(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}compareVersions(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}isCompatibleVersion(e,t){return this.compareVersions(e,t)>=0&&e.major===t.major&&e.minor===t.minor}isMajorCompatible(e,t){return t.major===0?this.compareVersions(e,t)>=0&&e.major===0&&e.minor===t.minor:this.compareVersions(e,t)>=0&&e.major===t.major}};import*as y from"js-yaml";var d=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let r=t.errors[0];throw new Error(`YAML parse error at line ${r.line}, column ${r.column}: ${r.message}`)}return t.document}parseWithErrors(e){let t=[],r;try{e=e.replace(/^\uFEFF/,"");let n=y.load(e);if(!n||typeof n!="object")return r={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:r,errors:t,isValid:!0};let s=this.extractMetadata(n),a=this.extractBody(n,s);return r={metadata:s,body:a,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:r,errors:t,isValid:!0}}catch(n){let s=n,a={message:s.message||"Unknown parse error",line:s.mark?.line??0,column:s.mark?.column??0,errorType:s.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${s.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${s.mark?.line??0}: ${s.message||"Unknown parse error"}`};return t.push(a),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let r=e.metadata.namespace_,n={type:"Package",publisher:r.publisher};r.version&&(n.version=`${r.version.major}.${r.version.minor}.${r.version.patch}`),e.metadata.imports&&(n.imports=this.serializeImports(e.metadata.imports)),t[r.package_]=n}return Object.assign(t,e.body),y.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let r=[];for(let n of Object.values(t))r.push(...n);return r},enumerable:!0,configurable:!0}),e}createVersion(e,t,r){return{major:e,minor:t,patch:r,toString:()=>`${e}.${t}.${r}`,equals:s=>!s||typeof s!="object"?!1:s.major===e&&s.minor===t&&s.patch===r,getHashCode:()=>e<<20|t<<10|r,compareTo:s=>e!==s.major?e-s.major:t!==s.minor?t-s.minor:r-s.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&n.type==="Package"){t.type_="Package";let s=r,a=n.publisher,i=n.version?this.parseVersion(n.version):void 0;return a&&s&&(t.namespace_={publisher:a,package_:s,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===a&&o.package_===s&&(!i||!o.version||i.equals(o.version)),getHashCode:()=>{let o=0;for(let c=0;c<a.length;c++)o=(o<<5)-o+a.charCodeAt(c);for(let c=0;c<s.length;c++)o=(o<<5)-o+s.charCodeAt(c);return o|0}}),n.imports&&Array.isArray(n.imports)&&(t.imports=this.parseImportsV3(n.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let r=e.kanonak;return(r.publisher||r.package||r.version)&&(t.namespace_=this.parseNamespace(r)),r.imports&&typeof r.imports=="object"&&(t.imports=this.parseImportsLegacy(r.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let r={},n;for(let[s,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){n=s;break}for(let[s,a]of Object.entries(e))s!==n&&s!=="kanonak"&&s!=="namespace"&&s!=="imports"&&(r[s]=a);return r}parseNamespace(e){if(typeof e=="string"){let s=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(s){let a=s[3]?this.parseVersion(s[3]):this.createVersion(1,0,0);return{publisher:s[1],package_:s[2],version:a,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===s[1]&&i.package_===s[2]&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let o=0;o<s[1].length;o++)i=(i<<5)-i+s[1].charCodeAt(o);for(let o=0;o<s[2].length;o++)i=(i<<5)-i+s[2].charCodeAt(o);return i|0}}}}let t=e.publisher||"",r=e.package||"",n=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:r,version:n,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===t&&s.package_===r&&(!n||!s.version||n.equals(s.version)),getHashCode:()=>{let s=0;for(let a=0;a<t.length;a++)s=(s<<5)-s+t.charCodeAt(a);for(let a=0;a<r.length;a++)s=(s<<5)-s+r.charCodeAt(a);return s|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let r of e)if(!(!r||typeof r!="object"))if(r.packages&&Array.isArray(r.packages)){let n=r.publisher;if(!n)throw new Error("PublisherImport requires 'publisher' property");t[n]||(t[n]=[]);for(let s of r.packages){if(!s||typeof s!="object")continue;let a=this.parseImportFromEmbeddedObject(s,n);t[n].push(a)}}else{let n=this.parseImportFromEmbeddedObject(r,r.publisher),s=n.publisher||"";t[s]||(t[s]=[]),t[s].push(n)}return t}parseImportsLegacy(e){let t={};for(let[r,n]of Object.entries(e))Array.isArray(n)&&(t[r]=n.map(s=>this.parseImport(s,r)));return t}parseImportFromEmbeddedObject(e,t){let r=e.package;if(!r)throw new Error("Import requires 'package' property");let n=e.match;if(!n)throw new Error("Import requires 'match' property");let s=e.version;if(!s)throw new Error("Import requires 'version' property");let a=this.parseVersion(s),i=this.parseVersionOperator(n),o=this.calculateMaxVersion(n,a),c=e.alias;return{package_:`${r} ${n} ${a.toString()}`,publisher:t,packageName:r,versionOperator:i,version:a,alias:c,minVersion:a,maxVersion:o,toEmbeddedObject:()=>{let m={package:r,match:n,version:a.toString()};return c&&(m.alias=c),m},toString:()=>c?`${r} ${n} ${a.toString()} as ${c}`:`${r} ${n} ${a.toString()}`}}parseImport(e,t){if(typeof e=="string"){let o=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(o){let m=o[1].trim(),p=o[2],l=this.parseVersion(o[3].trim()),h=o[4].trim(),v=this.parseVersionOperator(p),x=this.calculateMaxVersion(p,l);return{package_:e,publisher:t,packageName:m,versionOperator:v,version:l,alias:h,minVersion:l,maxVersion:x,toEmbeddedObject:()=>{let V={package:m,match:p,version:l.toString()};return h&&(V.alias=h),V},toString:()=>`${m} ${p} ${l.toString()} as ${h}`}}let c=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(c){let m=c[1].trim(),p=c[2],l=this.parseVersion(c[3].trim()),h=this.parseVersionOperator(p),v=this.calculateMaxVersion(p,l);return{package_:e,publisher:t,packageName:m,versionOperator:h,version:l,alias:void 0,minVersion:l,maxVersion:v,toEmbeddedObject:()=>({package:m,match:p,version:l.toString()}),toString:()=>`${m} ${p} ${l.toString()}`}}}let r=this.parseVersionOperator(e.operator||"~"),n=this.parseVersion(e.version||"1.0.0"),s=e.packageName||e.package||"",a=["=","~","^","*"][r],i=this.calculateMaxVersion(e.operator||"~",n);return{package_:e.package||"",publisher:t,packageName:s,versionOperator:r,version:n,alias:e.alias,minVersion:n,maxVersion:i,toEmbeddedObject:()=>{let o={package:s,match:a,version:n.toString()};return e.alias&&(o.alias=e.alias),o},toString:()=>`${s} ${a} ${n.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[r,n]of Object.entries(e)){let s={publisher:r,packages:n.map(a=>{let i=["=","~","^","*"][a.versionOperator],o={package:a.packageName,match:i,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(o.alias=a.alias),o})};t.push(s)}return t}};import{VersionOperator as k}from"@kanonak-protocol/types/document/models/enums";var C="https://{publisher}/index.txt",w="https://{publisher}/{package}/{version}.kan.yml",$={version:1},f=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let r=await this.fetchConfig(e);return this.cache.set(e,r),r}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,r;try{r=await fetch(t)}catch{return $}if(r.status===404)return $;if(!r.ok)throw new Error(`Failed to fetch publisher config: ${t} (${r.status} ${r.statusText})`);let n=await r.json();if(typeof n.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:n.version};return typeof n.index=="string"&&(s.index=n.index),typeof n.package=="string"&&(s.package=n.package),(n.auth==="none"||n.auth==="oauth"||n.auth==="bearer")&&(s.auth=n.auth),s}resolveIndexUrl(e,t){let r=t.index??C;return I(r,{publisher:e})}resolvePackageUrl(e,t,r,n){let s=n.package??w;return I(s,{publisher:e,package:t,version:r})}};function I(u,e){let t=u;for(let[n,s]of Object.entries(e))t=t.replaceAll(`{${n}}`,s);let r=t.match(/\{[a-z]+\}/);if(r)throw new Error(`Unresolved variable ${r[0]} in URL template: ${u}`);return t}var g=class u{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new f,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let r=await this.getPackageVersions(e,t.packageName);if(r.length===0)return null;let n=r.filter(s=>this.isVersionCompatible(s,t.version,t.versionOperator));return n.length===0?null:(n.sort((s,a)=>this.compareVersionStrings(a,s)),n[0])}async getHighestVersion(e,t){let r=await this.getPackageVersions(e,t);return r.length===0?null:[...r].sort((s,a)=>this.compareVersionStrings(a,s))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let r=[];for(let[n,s]of t){if(s.length===0)continue;let a=[...s].sort((i,o)=>this.compareVersionStrings(o,i));r.push({packageName:n,version:a[0]})}return r.sort((n,s)=>n.packageName.localeCompare(s.packageName)),r}async getPackageUrl(e,t,r){let n=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,r,n)}async getPackageVersions(e,t){let r=this.indexCache.get(e);return r||(r=await this.fetchIndex(e),this.indexCache.set(e,r)),r.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),r=this.configResolver.resolveIndexUrl(e,t),n=this.fetchFn?await this.fetchFn(r,e):await fetch(r);if(!n.ok)throw new Error(`Failed to fetch publisher index: ${r} (${n.status} ${n.statusText})`);let s=await n.text();return u.parseIndex(s)}static parseIndex(e){let t=new Map;for(let r of e.split(`
|
|
2
|
-
`)){let n
|
|
1
|
+
function h(c,e){return c.major!==e.major?c.major-e.major:c.minor!==e.minor?c.minor-e.minor:c.patch-e.patch}function $(c,e){return c.major===e.major&&c.minor===e.minor&&c.patch===e.patch}function I(c,e){return h(c,e)>=0&&c.major===e.major&&c.minor===e.minor}function C(c,e){return e.major===0?h(c,e)>=0&&c.major===0&&c.minor===e.minor:h(c,e)>=0&&c.major===e.major}var V=class{documents=new Map;documentContents=new Map;parser;constructor(e){this.parser=e}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){let n=[];for(let r of this.documents.values())r.metadata?.namespace_?.publisher===e&&r.metadata?.namespace_?.package_===t&&n.push(r);return n}async getHighestCompatibleVersionAsync(e,t){let n=[];for(let s of this.documents.values())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t.packageName&&s.metadata?.namespace_?.version!==void 0&&n.push(s);if(n.length===0)return null;let r=n.filter(s=>{let a=s.metadata.namespace_.version;if(!a)return!1;switch(t.versionOperator){case 0:return $(a,t.version);case 1:return I(a,t.version);case 2:return C(a,t.version);case 3:return h(a,t.minVersion)>=0;default:return!1}});return r.length===0?null:(r.sort((s,a)=>{let i=s.metadata.namespace_.version,o=a.metadata.namespace_.version;return!i&&!o?0:i?o?h(o,i):-1:1}),r[0])}async saveDocumentAsync(e,t){this.documents.set(t,e);let n=this.parser.save(e);this.documentContents.set(t,n)}async deleteDocumentAsync(e){this.documents.delete(e),this.documentContents.delete(e)}async clearNamespaceAsync(e,t){let n=[];for(let[r,s]of this.documents.entries())s.metadata?.namespace_?.publisher===e&&s.metadata?.namespace_?.package_===t&&n.push(r);for(let r of n)this.documents.delete(r),this.documentContents.delete(r)}async getAllDocumentReferencesAsync(){let e=[];for(let t of this.documents.values())t.metadata?.namespace_&&e.push({identifier:t.metadata.namespace_.toString(),uri:`kanonak://${t.metadata.namespace_}`,hasParseError:!1});return e}async getDocumentContentAsync(e){let t=this.documentContents.get(e);if(t!==void 0)return t;let n=this.documents.get(e);return n!==void 0?this.parser.save(n):null}async getDocumentUriAsync(e){let t=this.documents.get(e);return t?t.metadata?.namespace_?`kanonak://${t.metadata.namespace_}`:`kanonak://${e}`:null}};import*as k from"js-yaml";var y=class{parse(e){let t=this.parseWithErrors(e);if(!t.isValid){let n=t.errors[0];throw new Error(`YAML parse error at line ${n.line}, column ${n.column}: ${n.message}`)}return t.document}parseWithErrors(e){let t=[],n;try{e=e.replace(/^\uFEFF/,"");let r=k.load(e);if(!r||typeof r!="object")return n={metadata:this.createEmptyMetadata(),body:{},toString:()=>"KanonakDocument(empty)"},{document:n,errors:t,isValid:!0};let s=this.extractMetadata(r),a=this.extractBody(r,s);return n={metadata:s,body:a,toString:function(){return this.metadata.namespace_?`KanonakDocument(${this.metadata.namespace_.publisher}/${this.metadata.namespace_.package_})`:"KanonakDocument(no namespace)"}},{document:n,errors:t,isValid:!0}}catch(r){let s=r,a={message:s.message||"Unknown parse error",line:s.mark?.line??0,column:s.mark?.column??0,errorType:s.name==="YAMLException"?"SyntaxError":"Unknown",toString:()=>`${s.name==="YAMLException"?"SyntaxError":"Unknown"} at line ${s.mark?.line??0}: ${s.message||"Unknown parse error"}`};return t.push(a),{document:void 0,errors:t,isValid:!1}}}save(e){let t={};if(e.metadata.namespace_){let n=e.metadata.namespace_,r={type:"Package",publisher:n.publisher};n.version&&(r.version=`${n.version.major}.${n.version.minor}.${n.version.patch}`),e.metadata.imports&&(r.imports=this.serializeImports(e.metadata.imports)),t[n.package_]=r}return Object.assign(t,e.body),k.dump(t,{indent:2,noRefs:!0,sortKeys:!1})}createEmptyMetadata(){return{get allImports(){return[]}}}addAllImportsGetter(e){let t=e.imports;return Object.defineProperty(e,"allImports",{get:function(){if(!t)return[];let n=[];for(let r of Object.values(t))n.push(...r);return n},enumerable:!0,configurable:!0}),e}createVersion(e,t,n){return{major:e,minor:t,patch:n,toString:()=>`${e}.${t}.${n}`,equals:s=>!s||typeof s!="object"?!1:s.major===e&&s.minor===t&&s.patch===n,getHashCode:()=>e<<20|t<<10|n,compareTo:s=>e!==s.major?e-s.major:t!==s.minor?t-s.minor:n-s.patch}}extractMetadata(e){let t=this.createEmptyMetadata();for(let[n,r]of Object.entries(e))if(r&&typeof r=="object"&&r.type==="Package"){t.type_="Package";let s=n,a=r.publisher,i=r.version?this.parseVersion(r.version):void 0;return a&&s&&(t.namespace_={publisher:a,package_:s,version:i,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:o=>!o||typeof o!="object"?!1:o.publisher===a&&o.package_===s&&(!i||!o.version||i.equals(o.version)),getHashCode:()=>{let o=0;for(let m=0;m<a.length;m++)o=(o<<5)-o+a.charCodeAt(m);for(let m=0;m<s.length;m++)o=(o<<5)-o+s.charCodeAt(m);return o|0}}),r.imports&&Array.isArray(r.imports)&&(t.imports=this.parseImportsV3(r.imports)),this.addAllImportsGetter(t)}if(e.kanonak&&typeof e.kanonak=="object"){let n=e.kanonak;return(n.publisher||n.package||n.version)&&(t.namespace_=this.parseNamespace(n)),n.imports&&typeof n.imports=="object"&&(t.imports=this.parseImportsLegacy(n.imports)),this.addAllImportsGetter(t)}return t}extractBody(e,t){let n={},r;for(let[s,a]of Object.entries(e))if(a&&typeof a=="object"&&a.type==="Package"){r=s;break}for(let[s,a]of Object.entries(e))s!==r&&s!=="kanonak"&&s!=="namespace"&&s!=="imports"&&(n[s]=a);return n}parseNamespace(e){if(typeof e=="string"){let s=e.match(/^([^/]+)\/([^@]+)(?:@(.+))?$/);if(s){let a=s[3]?this.parseVersion(s[3]):this.createVersion(1,0,0);return{publisher:s[1],package_:s[2],version:a,toString:()=>e,equals:i=>!i||typeof i!="object"?!1:i.publisher===s[1]&&i.package_===s[2]&&(!a||!i.version||a.equals(i.version)),getHashCode:()=>{let i=0;for(let o=0;o<s[1].length;o++)i=(i<<5)-i+s[1].charCodeAt(o);for(let o=0;o<s[2].length;o++)i=(i<<5)-i+s[2].charCodeAt(o);return i|0}}}}let t=e.publisher||"",n=e.package||"",r=e.version?this.parseVersion(e.version):this.createVersion(1,0,0);return{publisher:t,package_:n,version:r,toString:function(){return`${this.publisher}/${this.package_}@${this.version?.major??1}.${this.version?.minor??0}.${this.version?.patch??0}`},equals:s=>!s||typeof s!="object"?!1:s.publisher===t&&s.package_===n&&(!r||!s.version||r.equals(s.version)),getHashCode:()=>{let s=0;for(let a=0;a<t.length;a++)s=(s<<5)-s+t.charCodeAt(a);for(let a=0;a<n.length;a++)s=(s<<5)-s+n.charCodeAt(a);return s|0}}}parseVersion(e){if(typeof e=="string"){let t=e.split(".").map(Number);return this.createVersion(t[0]||0,t[1]||0,t[2]||0)}return this.createVersion(e.major||0,e.minor||0,e.patch||0)}parseImportsV3(e){let t={};for(let n of e)if(!(!n||typeof n!="object"))if(n.packages&&Array.isArray(n.packages)){let r=n.publisher;if(!r)throw new Error("PublisherImport requires 'publisher' property");t[r]||(t[r]=[]);for(let s of n.packages){if(!s||typeof s!="object")continue;let a=this.parseImportFromEmbeddedObject(s,r);t[r].push(a)}}else{let r=this.parseImportFromEmbeddedObject(n,n.publisher),s=r.publisher||"";t[s]||(t[s]=[]),t[s].push(r)}return t}parseImportsLegacy(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.map(s=>this.parseImport(s,n)));return t}parseImportFromEmbeddedObject(e,t){let n=e.package;if(!n)throw new Error("Import requires 'package' property");let r=e.match;if(!r)throw new Error("Import requires 'match' property");let s=e.version;if(!s)throw new Error("Import requires 'version' property");let a=this.parseVersion(s),i=this.parseVersionOperator(r),o=this.calculateMaxVersion(r,a),m=e.alias;return{package_:`${n} ${r} ${a.toString()}`,publisher:t,packageName:n,versionOperator:i,version:a,alias:m,minVersion:a,maxVersion:o,toEmbeddedObject:()=>{let u={package:n,match:r,version:a.toString()};return m&&(u.alias=m),u},toString:()=>m?`${n} ${r} ${a.toString()} as ${m}`:`${n} ${r} ${a.toString()}`}}parseImport(e,t){if(typeof e=="string"){let o=e.match(/^(.+?)\s*([~^=*])\s*(\S+)\s+as\s+(\S+)$/);if(o){let u=o[1].trim(),p=o[2],l=this.parseVersion(o[3].trim()),g=o[4].trim(),b=this.parseVersionOperator(p),A=this.calculateMaxVersion(p,l);return{package_:e,publisher:t,packageName:u,versionOperator:b,version:l,alias:g,minVersion:l,maxVersion:A,toEmbeddedObject:()=>{let P={package:u,match:p,version:l.toString()};return g&&(P.alias=g),P},toString:()=>`${u} ${p} ${l.toString()} as ${g}`}}let m=e.match(/^(.+?)\s*([~^=*])\s*(.+)$/);if(m){let u=m[1].trim(),p=m[2],l=this.parseVersion(m[3].trim()),g=this.parseVersionOperator(p),b=this.calculateMaxVersion(p,l);return{package_:e,publisher:t,packageName:u,versionOperator:g,version:l,alias:void 0,minVersion:l,maxVersion:b,toEmbeddedObject:()=>({package:u,match:p,version:l.toString()}),toString:()=>`${u} ${p} ${l.toString()}`}}}let n=this.parseVersionOperator(e.operator||"~"),r=this.parseVersion(e.version||"1.0.0"),s=e.packageName||e.package||"",a=["=","~","^","*"][n],i=this.calculateMaxVersion(e.operator||"~",r);return{package_:e.package||"",publisher:t,packageName:s,versionOperator:n,version:r,alias:e.alias,minVersion:r,maxVersion:i,toEmbeddedObject:()=>{let o={package:s,match:a,version:r.toString()};return e.alias&&(o.alias=e.alias),o},toString:()=>`${s} ${a} ${r.toString()}`}}parseVersionOperator(e){switch(e){case"=":return 0;case"~":return 1;case"^":return 2;case"*":return 3;default:return 1}}calculateMaxVersion(e,t){switch(e){case"~":return this.createVersion(t.major,t.minor+1,0);case"^":return t.major===0?this.createVersion(0,t.minor+1,0):this.createVersion(t.major+1,0,0);default:return this.createVersion(999,999,999)}}serializeImports(e){let t=[];for(let[n,r]of Object.entries(e)){let s={publisher:n,packages:r.map(a=>{let i=["=","~","^","*"][a.versionOperator],o={package:a.packageName,match:i,version:`${a.version.major}.${a.version.minor}.${a.version.patch}`};return a.alias&&(o.alias=a.alias),o})};t.push(s)}return t}};import{VersionOperator as v}from"@kanonak-protocol/types/document/models/enums";var R="https://{publisher}/index.txt",F="https://{publisher}/{package}/{version}.kan.yml",D={version:1},d=class{cache=new Map;async getConfig(e){let t=this.cache.get(e);if(t)return t;let n=await this.fetchConfig(e);return this.cache.set(e,n),n}async fetchConfig(e){let t=`https://${e}/.well-known/kanonak.json`,n;try{n=await fetch(t)}catch{return D}if(n.status===404)return D;if(!n.ok)throw new Error(`Failed to fetch publisher config: ${t} (${n.status} ${n.statusText})`);let r=await n.json();if(typeof r.version!="number")throw new Error(`Invalid publisher config at ${t}: missing or invalid "version" field`);let s={version:r.version};return typeof r.index=="string"&&(s.index=r.index),typeof r.package=="string"&&(s.package=r.package),(r.auth==="none"||r.auth==="oauth"||r.auth==="bearer")&&(s.auth=r.auth),s}resolveIndexUrl(e,t){let n=t.index??R;return w(n,{publisher:e})}resolvePackageUrl(e,t,n,r){let s=r.package??F;return w(s,{publisher:e,package:t,version:n})}};function w(c,e){let t=c;for(let[r,s]of Object.entries(e))t=t.replaceAll(`{${r}}`,s);let n=t.match(/\{[a-z]+\}/);if(n)throw new Error(`Unresolved variable ${n[0]} in URL template: ${c}`);return t}var f=class c{indexCache=new Map;configResolver;fetchFn;constructor(e){this.configResolver=e?.configResolver??new d,this.fetchFn=e?.fetchFn}async resolveVersion(e,t){let n=await this.getPackageVersions(e,t.packageName);if(n.length===0)return null;let r=n.filter(s=>this.isVersionCompatible(s,t.version,t.versionOperator));return r.length===0?null:(r.sort((s,a)=>this.compareVersionStrings(a,s)),r[0])}async getHighestVersion(e,t){let n=await this.getPackageVersions(e,t);return n.length===0?null:[...n].sort((s,a)=>this.compareVersionStrings(a,s))[0]}async listLatestPackages(e){let t=this.indexCache.get(e);t||(t=await this.fetchIndex(e),this.indexCache.set(e,t));let n=[];for(let[r,s]of t){if(s.length===0)continue;let a=[...s].sort((i,o)=>this.compareVersionStrings(o,i));n.push({packageName:r,version:a[0]})}return n.sort((r,s)=>r.packageName.localeCompare(s.packageName)),n}async getPackageUrl(e,t,n){let r=await this.configResolver.getConfig(e);return this.configResolver.resolvePackageUrl(e,t,n,r)}async getPackageVersions(e,t){let n=this.indexCache.get(e);return n||(n=await this.fetchIndex(e),this.indexCache.set(e,n)),n.get(t)??[]}async fetchIndex(e){let t=await this.configResolver.getConfig(e),n=this.configResolver.resolveIndexUrl(e,t),r=this.fetchFn?await this.fetchFn(n,e):await fetch(n);if(!r.ok)throw new Error(`Failed to fetch publisher index: ${n} (${r.status} ${r.statusText})`);let s=await r.text();return c.parseIndex(s)}static parseIndex(e){let t=new Map;for(let n of e.split(`
|
|
2
|
+
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("/");if(s===-1)continue;let a=r.substring(0,s),i=r.substring(s+1);if(!a||!i)continue;let o=t.get(a);o?o.push(i):t.set(a,[i])}return t}isVersionCompatible(e,t,n){let r=c.parseVersion(e);if(!r)return!1;switch(n){case v.Any:return!0;case v.Exact:return r.major===t.major&&r.minor===t.minor&&r.patch===t.patch;case v.Compatible:return r.major===t.major&&r.minor===t.minor&&r.patch>=t.patch;case v.Major:return r.major!==t.major?!1:r.minor>t.minor?!0:r.minor===t.minor?r.patch>=t.patch:!1;default:return!1}}static parseVersion(e){let t=e.split(".");if(t.length<2)return null;let n=parseInt(t[0],10),r=parseInt(t[1],10),s=t.length>=3?parseInt(t[2],10):0;return isNaN(n)||isNaN(r)||isNaN(s)?null:{major:n,minor:r,patch:s}}compareVersionStrings(e,t){let n=c.parseVersion(e),r=c.parseVersion(t);return!n&&!r?0:n?r?n.major!==r.major?n.major-r.major:n.minor!==r.minor?n.minor-r.minor:n.patch-r.patch:1:-1}};var x=class{parser=new y;publisherIndex;documents=new Map;contentCache=new Map;fetchFn;onFetch;getFromCache;constructor(e){this.onFetch=e?.onFetch,this.getFromCache=e?.getFromCache,this.fetchFn=e?.fetchFn,this.publisherIndex=e?.fetchFn?new f({fetchFn:e.fetchFn}):new f}async getHighestCompatibleVersionAsync(e,t){let n=await this.publisherIndex.resolveVersion(e,t);if(!n)return null;let r=`${e}/${t.packageName}@${n}`,s=this.documents.get(r);if(s)return s;if(this.getFromCache){let u=this.getFromCache(e,t.packageName,n);if(u){let p=this.parser.parse(u);return this.documents.set(r,p),this.contentCache.set(r,u),p}}let a=await this.publisherIndex.getPackageUrl(e,t.packageName,n),i=this.fetchFn?await this.fetchFn(a,e):await fetch(a);if(!i.ok)throw new Error(`Failed to fetch Kanonak package: ${a} (${i.status} ${i.statusText})`);let o=await i.text();this.onFetch&&this.onFetch(e,t.packageName,n,o);let m=this.parser.parse(o);return this.documents.set(r,m),this.contentCache.set(r,o),m}async getAllDocumentsAsync(){return Array.from(this.documents.values())}async getDocumentAsync(e){return this.documents.get(e)??null}async getDocumentsByNamespaceAsync(e,t){return Array.from(this.documents.values()).filter(n=>{let r=n.metadata.namespace_;return r&&r.publisher===e&&r.package_===t})}async saveDocumentAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async deleteDocumentAsync(e){throw new Error("HttpKanonakDocumentRepository is read-only")}async clearNamespaceAsync(e,t){throw new Error("HttpKanonakDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.contentCache.get(e)??null}async getDocumentUriAsync(e){let t=e.match(/^(.+?)\/(.+?)@(.+)$/);if(!t)return null;let[,n,r,s]=t;return this.publisherIndex.getPackageUrl(n,r,s)}};export{x as HttpKanonakDocumentRepository,V as InMemoryKanonakDocumentRepository,d as PublisherConfigResolver,f as PublisherIndex};
|