@kanonak-protocol/cli 3.5.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/derive.d.ts +18 -0
- package/dist/commands/site.d.ts +19 -0
- package/dist/index.js +80 -66
- package/dist/transformations/FormatOverride.d.ts +13 -0
- package/dist/transformations/v3/CompiledTransformationV3.d.ts +47 -1
- package/dist/transformations/v3/TransformationUriConstantsV3.d.ts +18 -0
- package/package.json +3 -3
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `kanonak derive` command.
|
|
3
|
+
*
|
|
4
|
+
* Materializes a derived artifact from a Kanonak resource using the
|
|
5
|
+
* polymorphic discovery walk: the SDK's `findDerivation` looks up
|
|
6
|
+
* the binding for the requested (format, variant) by walking the
|
|
7
|
+
* resource's class hierarchy, the universal-derivations augmentations
|
|
8
|
+
* on rdfs.Resource provide the floor, and the runner produces the
|
|
9
|
+
* artifact.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* kanonak derive <resource-uri> [--format <name>] [--variant <name>] [--out <dir>]
|
|
13
|
+
*
|
|
14
|
+
* The resource URI form is the standard publisher/package[@version]/name
|
|
15
|
+
* — same as transform's --scope, with a required instance name segment.
|
|
16
|
+
*/
|
|
17
|
+
import { Command } from 'commander';
|
|
18
|
+
export declare function deriveCommand(): Command;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `kanonak site` command group.
|
|
3
|
+
*
|
|
4
|
+
* Materializes a publisher's site from declarative `StaticPage` and
|
|
5
|
+
* `AggregateView` instances in the workspace. Replaces the per-page
|
|
6
|
+
* workflow steps (and `cat <<HTML` heredocs) that publishers
|
|
7
|
+
* hand-author today.
|
|
8
|
+
*
|
|
9
|
+
* Two subcommands:
|
|
10
|
+
*
|
|
11
|
+
* - `site build` walks the workspace, finds every StaticPage and
|
|
12
|
+
* AggregateView, resolves each to its declared transformation
|
|
13
|
+
* (via the polymorphic discovery walk for static pages, via the
|
|
14
|
+
* direct transformation reference for aggregates), runs them,
|
|
15
|
+
* and writes the artifacts to the declared output paths under
|
|
16
|
+
* the `--out` directory.
|
|
17
|
+
*/
|
|
18
|
+
import { Command } from 'commander';
|
|
19
|
+
export declare function siteCommand(): Command;
|
package/dist/index.js
CHANGED
|
@@ -1,98 +1,101 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as
|
|
3
|
-
`).some(o=>o.trim()===t||o.trim()===t+"/"))return;
|
|
2
|
+
import{Command as tl}from"commander";import{readFileSync as rl}from"fs";import{fileURLToPath as ol}from"url";import{dirname as al,join as il}from"path";import{KanonakParser as sl,PublisherIndex as cl,CredentialStore as ll,createAuthenticatedFetch as ul}from"@kanonak-protocol/sdk";import{readFileSync as Po,statSync as Ko}from"fs";import{resolve as Do,dirname as Eo}from"path";import{KanonakParser as Co,KanonakObjectValidator as Ao,ValidationSeverity as Zn}from"@kanonak-protocol/sdk";import{readFileSync as ko,readdirSync as ho}from"fs";import{join as yo,dirname as bo,basename as Yn}from"path";import{InMemoryKanonakDocumentRepository as wo,FileSystemKanonakDocumentRepository as $o,HttpKanonakDocumentRepository as So,getGlobalCachePath as vo}from"@kanonak-protocol/sdk";import{mkdirSync as lo,readFileSync as Jn,writeFileSync as Xn,existsSync as an,appendFileSync as uo}from"fs";import{join as fo,dirname as mo,isAbsolute as po}from"path";import{getGlobalCachePath as go}from"@kanonak-protocol/sdk";var V=class{constructor(e=go()){this.cacheDir=e;this.isProjectLocal=!po(e)}cacheDir;gitignoreChecked=!1;isProjectLocal;get(e,t,r){let o=this.getPath(e,t,r);return an(o)?Jn(o,"utf-8"):null}put(e,t,r,o){let a=this.getPath(e,t,r);lo(mo(a),{recursive:!0}),Xn(a,o,"utf-8"),this.isProjectLocal&&this.ensureGitignore()}has(e,t,r){return an(this.getPath(e,t,r))}ensureGitignore(){if(this.gitignoreChecked)return;this.gitignoreChecked=!0;let e=".gitignore",t=this.cacheDir;if(an(e)){if(Jn(e,"utf-8").split(`
|
|
3
|
+
`).some(o=>o.trim()===t||o.trim()===t+"/"))return;uo(e,`
|
|
4
4
|
${t}/
|
|
5
|
-
`)}else
|
|
6
|
-
`)}getPath(e,t,r){return
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
${w}:`);for(let $ of
|
|
10
|
-
${
|
|
11
|
-
Installed ${Object.keys(
|
|
12
|
-
Installed ${
|
|
5
|
+
`)}else Xn(e,`${t}/
|
|
6
|
+
`)}getPath(e,t,r){return fo(this.cacheDir,e,`${t}@${r}.kan.yml`)}};function he(n){let e=n;for(;;){let t=bo(e);if(t===e)break;if(Yn(e).includes(".")||Yn(t).includes(".")){e=t;continue}break}return e}function Ce(n,e){for(let t of ho(n,{withFileTypes:!0})){let r=yo(n,t.name);t.isDirectory()&&t.name!=="node_modules"&&t.name!==".kanonak"?Ce(r,e):t.name.endsWith(".kan.yml")&&e.push(r)}}var sn=class{repos;constructor(...e){this.repos=e}async getHighestCompatibleVersionAsync(e,t){for(let r of this.repos)try{let o=await r.getHighestCompatibleVersionAsync(e,t);if(o)return o}catch{}return null}async getAllDocumentsAsync(){let e=[];for(let t of this.repos)try{e.push(...await t.getAllDocumentsAsync())}catch{}return e}async getDocumentAsync(e){for(let t of this.repos)try{let r=await t.getDocumentAsync(e);if(r)return r}catch{}return null}async getDocumentsByNamespaceAsync(e,t){for(let r of this.repos)try{let o=await r.getDocumentsByNamespaceAsync(e,t);if(o.length>0)return o}catch{}return[]}async saveDocumentAsync(e,t){await this.repos[0].saveDocumentAsync(e,t)}async deleteDocumentAsync(e){await this.repos[0].deleteDocumentAsync(e)}async clearNamespaceAsync(e,t){await this.repos[0].clearNamespaceAsync(e,t)}async getAllDocumentReferencesAsync(){return this.repos[0].getAllDocumentReferencesAsync()}async getDocumentContentAsync(e){for(let t of this.repos)try{let r=await t.getDocumentContentAsync(e);if(r)return r}catch{}return null}async getDocumentUriAsync(e){for(let t of this.repos)try{let r=await t.getDocumentUriAsync(e);if(r)return r}catch{}return null}};async function j(n,e){let t=[];Ce(n,t);let r=new wo(e);for(let s of t)try{let c=ko(s,"utf-8"),l=e.parse(c),d=l.metadata.namespace_;if(d){let f=`${d.publisher}/${d.package_}@${d.version}`;await r.saveDocumentAsync(l,f)}}catch{}let o=new $o(vo(),!0,e),a=new V,i=new So({getFromCache:(s,c,l)=>a.get(s,c,l),onFetch:(s,c,l,d)=>a.put(s,c,l,d)});return new sn(r,o,i)}async function Qn(n){let e=Do(n),t=Ko(e),r=t.isDirectory()?he(e):he(Eo(e)),o=new Co,a=new Ao(o),i=await j(r,o),s=[];if(t.isDirectory()?Ce(e,s):s.push(e),s.length===0){console.log("No .kan.yml files found.");return}let c=0,l=0;for(let d of s){let f=Po(d,"utf-8"),p=o.parseWithErrors(f);if(p.errors&&p.errors.length>0){console.log(`
|
|
7
|
+
${d}:`);for(let h of p.errors)console.log(` ERROR (parse): ${h.message} [line ${h.line}:${h.column}]`),c++;continue}let k=p.document;if(!k){console.log(`
|
|
8
|
+
${d}:`),console.log(" ERROR: Failed to parse document"),c++;continue}let b=await a.validateAsync(k,i),g=b.errors.filter(h=>h.severity===Zn.Error),y=b.errors.filter(h=>h.severity===Zn.Warning);if(g.length>0||y.length>0){let h=k.metadata.namespace_,w=h?`${h.publisher}/${h.package_}@${h.version}`:d;console.log(`
|
|
9
|
+
${w}:`);for(let $ of g)console.log(` ERROR: ${$.message}`),$.suggestion&&console.log(` -> ${$.suggestion}`);for(let $ of y)console.log(` WARN: ${$.message}`)}c+=g.length,l+=y.length}console.log(`
|
|
10
|
+
${s.length} file(s) validated. ${c} error(s), ${l} warning(s).`),c>0&&process.exit(1)}import{KanonakParser as Ro,PublisherIndex as _o,CredentialStore as Io,createAuthenticatedFetch as To}from"@kanonak-protocol/sdk";import{loadLockFile as jo,saveLockFile as Uo,computeIntegrity as Oo}from"@kanonak-protocol/sdk";function z(n){if(!n)return null;let e=n.indexOf("/");if(e===-1)return null;let t=n.substring(0,e),r=n.substring(e+1);if(!t||!r)return null;let o,a=null,i=null,s=r.indexOf("@");if(s!==-1){o=r.substring(0,s);let c=r.substring(s+1),l=c.indexOf("/");l===-1?a=c||null:(a=c.substring(0,l)||null,i=c.substring(l+1)||null)}else{let c=r.indexOf("/");c===-1?o=r:(o=r.substring(0,c),i=r.substring(c+1)||null)}return!o||i&&i.includes("/")||a&&a.includes("@")?null:{publisher:t,packageName:o,version:a,instanceName:i}}async function et(n){let e=new V,t=new Ro,r=new Io,o=To(r),a=new _o({fetchFn:o}),i=jo()??{version:"1",lastUpdated:new Date().toISOString(),packages:{}};if(!n){Object.keys(i.packages).length===0&&(console.error("No kanonak.lock file found or lock file is empty."),console.error("Usage: kanonak install {publisher}/{package}[@{version}]"),process.exit(1)),console.log(`Installing ${Object.keys(i.packages).length} package(s) from kanonak.lock...`);for(let[b,g]of Object.entries(i.packages)){let y=b.indexOf("/"),h=b.substring(0,y),w=b.substring(y+1),$=e.get(h,w,g.version);if($)console.log(` ${b}@${g.version} (cached)`);else{let S=g.resolved,D=await o(S,h);if(!D.ok)throw new Error(`Failed to fetch ${S} (${D.status} ${D.statusText})`);$=await D.text(),e.put(h,w,g.version,$),console.log(` ${b}@${g.version}`)}}console.log(`
|
|
11
|
+
Installed ${Object.keys(i.packages).length} package(s) from lock file.`);return}let s=z(n);s||(console.error(`Invalid package reference: "${n}"`),console.error("Expected format: {publisher}/{package}[@{version}]"),process.exit(1));let{publisher:c,packageName:l,version:d,instanceName:f}=s;f&&(console.error(`\`kanonak install\` works on whole packages \u2014 got an instance suffix "/${f}".`),console.error(`Try: kanonak install ${c}/${l}${d?"@"+d:""}`),console.error("(Use `kanonak <capability> add` if you want to install one named instance.)"),process.exit(1));let p=d??await a.getHighestVersion(c,l);p||(console.error(`Could not resolve version for "${c}/${l}".`),console.error("Check the spelling, or run a search to see what the publisher offers."),process.exit(1)),console.log(`Installing ${c}/${l}@${p}...`);let k=new Set;await nt(c,l,p,e,t,a,o,k,i),Uo(i),console.log(`
|
|
12
|
+
Installed ${k.size} package(s).`)}async function nt(n,e,t,r,o,a,i,s,c){let l=`${n}/${e}@${t}`;if(s.has(l))return;s.add(l);let d=`${n}/${e}`,f=r.get(n,e,t),p;if(f)console.log(` ${l} (cached)`),p=await a.getPackageUrl(n,e,t);else{p=await a.getPackageUrl(n,e,t);let g=await i(p,n);if(!g.ok)throw new Error(`Failed to fetch ${p} (${g.status} ${g.statusText})`);f=await g.text(),r.put(n,e,t,f),console.log(` ${l}`)}let k={},b=o.parse(f);if(b.metadata.imports)for(let[g,y]of Object.entries(b.metadata.imports))for(let h of y){let w=await a.resolveVersion(g,h);w?(k[`${g}/${h.packageName}`]=w,await nt(g,h.packageName,w,r,o,a,i,s,c)):console.error(` WARNING: Could not resolve ${g}/${h.packageName} ${h.package_}`)}c.packages[d]={version:t,resolved:p,integrity:Oo(f),dependencies:k}}import{readFileSync as xo}from"fs";import{resolve as No,dirname as Lo}from"path";import{KanonakParser as Fo}from"@kanonak-protocol/sdk";async function tt(n){let e=No(n),t=xo(e,"utf-8"),r=new Fo,o=r.parse(t),a=o.metadata.namespace_,i=a?`${a.publisher}/${a.package_}@${a.version}`:n;if(console.log(i),!o.metadata.imports){console.log(" (no imports)");return}let s=he(Lo(e)),c=await j(s,r),l=new Set;for(let[d,f]of Object.entries(o.metadata.imports))for(let p of f)await rt(d,p,c,l," ")}async function rt(n,e,t,r,o){let a=`${n}/${e.packageName}`;if(r.has(a)){console.log(`${o}${a} (${e.package_}) [circular]`);return}r.add(a);let i;try{i=await t.getHighestCompatibleVersionAsync(n,e)}catch{console.log(`${o}${a} (${e.package_}) [fetch failed]`);return}if(!i){console.log(`${o}${a} (${e.package_}) [not found]`);return}let s=i.metadata.namespace_?.version?.toString()??"?";if(console.log(`${o}${n}/${e.packageName}@${s}`),i.metadata.imports)for(let[c,l]of Object.entries(i.metadata.imports))for(let d of l)await rt(c,d,t,r,o+" ")}import{createHash as Mo,randomBytes as it}from"crypto";import{createServer as Bo}from"http";import{execFile as cn}from"child_process";import{CredentialStore as Ho,generateDPoPKeyPair as zo,createDPoPProof as ot,serverSupportsDPoP as qo}from"@kanonak-protocol/sdk";import{normalizeHost as Vo}from"@kanonak-protocol/sdk";var X=class{cache=new Map;async discover(e){let t=Vo(e);if(this.cache.has(t))return this.cache.get(t);let r=`https://${t}/.well-known/oauth-authorization-server`,o=await this.tryEndpoint(r);if(!o){let a=`https://${t}/.well-known/openid-configuration`;o=await this.tryEndpoint(a)}return this.cache.set(t,o),o}async supportsOAuth(e){return await this.discover(e)!==null}static supportsPkceS256(e){return e.codeChallengeMethodsSupported?.some(t=>t.toUpperCase()==="S256")??!1}static supportsDynamicRegistration(e){return!!e.registrationEndpoint}static supportsAuthorizationCode(e){return e.responseTypesSupported?.some(t=>t.toLowerCase()==="code")??!1}async tryEndpoint(e){let t;try{t=await fetch(e)}catch(o){let a=o instanceof Error?o.message:String(o);return a.includes("ENOTFOUND")||a.includes("ECONNREFUSED")?(console.error(` OAuth discovery: ${e} \u2014 host unreachable (${a})`),console.error(" If the server is behind a VPN, ensure you are connected.")):a.includes("CERT")||a.includes("SSL")||a.includes("TLS")?(console.error(` OAuth discovery: ${e} \u2014 TLS error (${a})`),console.error(" If using a custom CA certificate, set NODE_EXTRA_CA_CERTS=/path/to/ca.pem")):console.error(` OAuth discovery: ${e} \u2014 network error: ${a}`),null}if(!t.ok)return t.status===404||(t.status===403?(console.error(` OAuth discovery: ${e} \u2014 HTTP 403 Forbidden`),console.error(" Access may be blocked by a firewall, proxy, or WAF.")):t.status>=500&&(console.error(` OAuth discovery: ${e} \u2014 HTTP ${t.status} server error`),console.error(" The authorization server returned an internal error. Contact your IDP administrator."))),null;let r;try{r=await t.json()}catch{return console.error(` OAuth discovery: ${e} \u2014 response is not valid JSON`),console.error(" The endpoint may be returning HTML instead of JSON. Check IDP configuration."),null}return{issuer:ye(r.issuer),authorizationEndpoint:ye(r.authorization_endpoint),tokenEndpoint:ye(r.token_endpoint),registrationEndpoint:ye(r.registration_endpoint),revocationEndpoint:ye(r.revocation_endpoint),scopesSupported:ie(r.scopes_supported),responseTypesSupported:ie(r.response_types_supported),grantTypesSupported:ie(r.grant_types_supported),codeChallengeMethodsSupported:ie(r.code_challenge_methods_supported),tokenEndpointAuthMethodsSupported:ie(r.token_endpoint_auth_methods_supported),dpopSigningAlgValuesSupported:ie(r.dpop_signing_alg_values_supported)}}};function ye(n){return typeof n=="string"?n:null}function ie(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):null}var ce=class{discovery;credentialStore;constructor(e,t){this.discovery=e??new X,this.credentialStore=t??new Ho}async authorize(e,t=[]){console.log(`Starting OAuth flow for ${e}...`);let r=await this.discovery.discover(e);if(!r)return O(`No OAuth discovery endpoint found for '${e}'.
|
|
13
13
|
The server must expose one of:
|
|
14
14
|
- https://${e}/.well-known/oauth-authorization-server (RFC 8414)
|
|
15
15
|
- https://${e}/.well-known/openid-configuration (OpenID Connect)
|
|
16
16
|
Verify the hostname is correct and HTTPS is configured.
|
|
17
|
-
If using a corporate proxy, ensure it is not blocking the discovery request.`);let o=[];if(r.authorizationEndpoint||o.push("authorization_endpoint"),r.tokenEndpoint||o.push("token_endpoint"),o.length>0)return
|
|
18
|
-
Contact the IDP administrator to ensure these are included in the discovery document.`);let a=
|
|
19
|
-
Ensure your Node.js installation supports EC P-256 curves.`)}}let{redirectUri:
|
|
17
|
+
If using a corporate proxy, ensure it is not blocking the discovery request.`);let o=[];if(r.authorizationEndpoint||o.push("authorization_endpoint"),r.tokenEndpoint||o.push("token_endpoint"),o.length>0)return O(`OAuth metadata for '${e}' is missing required fields: ${o.join(", ")}.
|
|
18
|
+
Contact the IDP administrator to ensure these are included in the discovery document.`);let a=qo(r.dpopSigningAlgValuesSupported),i=null;if(a){console.log(" Server supports DPoP (RFC 9449) \u2014 generating key pair...");try{i=zo()}catch(D){return O(`Failed to generate DPoP key pair: ${se(D)}
|
|
19
|
+
Ensure your Node.js installation supports EC P-256 curves.`)}}let{redirectUri:s,port:c,waitForCallback:l,close:d}=await Qo(),f=await this.credentialStore.getCredential(e),p=f?.clientId??null,k=f?.clientSecret??null;if(!p&&r.registrationEndpoint){console.log(" Registering dynamic OAuth client (RFC 7591)...");let D=await this.registerClient(r.registrationEndpoint,s);if(!D.success)return d(),O(D.error);p=D.clientId,k=D.clientSecret??null}if(!p)return d(),O(`No OAuth client credentials for '${e}' and the server does not support dynamic client registration (no registration_endpoint in metadata).
|
|
20
20
|
You must pre-register a client with your IDP and configure the client_id.
|
|
21
21
|
Ask your IDP administrator to enable dynamic client registration (RFC 7591),
|
|
22
|
-
or add a registration_endpoint to the OAuth metadata.`);let b=
|
|
22
|
+
or add a registration_endpoint to the OAuth metadata.`);let b=Go(),g=Jo(b),y=Xo(),h=Yo(r.authorizationEndpoint,p,s,t,y,g);console.log(` Opening browser for authorization on port ${c}...`),console.log(" If the browser doesn't open, navigate to:"),console.log(` ${h}`),na(h);let w=await l();if(d(),!w)return O(`Authorization timed out after 5 minutes.
|
|
23
23
|
The browser authorization was not completed in time.
|
|
24
|
-
Re-run 'kanonak login ${e}' and complete the browser authorization promptly.`);if(!w.code){let
|
|
24
|
+
Re-run 'kanonak login ${e}' and complete the browser authorization promptly.`);if(!w.code){let D=w.error?`: ${w.error}`:"";return O(`No authorization code received${D}.
|
|
25
25
|
The IDP may have rejected the authorization request.
|
|
26
|
-
Check the IDP admin console for error details.`)}if(w.state!==y)return
|
|
26
|
+
Check the IDP admin console for error details.`)}if(w.state!==y)return O(`Authorization state mismatch \u2014 possible CSRF attack.
|
|
27
27
|
The response did not match the expected session.
|
|
28
|
-
Re-run 'kanonak login ${e}' to start a fresh authorization flow.`);console.log(" Exchanging authorization code for tokens...");let $=await this.exchangeCode(r.tokenEndpoint,p,
|
|
28
|
+
Re-run 'kanonak login ${e}' to start a fresh authorization flow.`);console.log(" Exchanging authorization code for tokens...");let $=await this.exchangeCode(r.tokenEndpoint,p,k,w.code,s,b,i);if(!$.success)return O($.error);let S={clientId:p,clientSecret:k,accessToken:$.tokens.accessToken,refreshToken:$.tokens.refreshToken,expiresAt:$.tokens.expiresIn?new Date(Date.now()+$.tokens.expiresIn*1e3).toISOString():null,tokenEndpoint:r.tokenEndpoint,dpopKeyPair:i};return await this.credentialStore.store(e,S),console.log(` Successfully authenticated with ${e}`),a&&console.log(" DPoP proof-of-possession is active"),{success:!0,host:e}}async refresh(e){let t=await this.credentialStore.getCredential(e);if(!t)return O(`No stored credentials for '${e}'. Run 'kanonak login ${e}' to authenticate first.`);if(!t.refreshToken)return O(`No refresh token available for '${e}'.
|
|
29
29
|
The authorization server may not issue refresh tokens for this client.
|
|
30
|
-
Run 'kanonak login ${e}' to re-authenticate.`);if(!t.clientId)return
|
|
31
|
-
The stored credential may be corrupted. Run 'kanonak logout ${e}' then 'kanonak login ${e}'.`);let r=t.tokenEndpoint;if(!r){let a=await this.discovery.discover(e);if(!a?.tokenEndpoint)return
|
|
30
|
+
Run 'kanonak login ${e}' to re-authenticate.`);if(!t.clientId)return O(`No client ID in stored credentials for '${e}'.
|
|
31
|
+
The stored credential may be corrupted. Run 'kanonak logout ${e}' then 'kanonak login ${e}'.`);let r=t.tokenEndpoint;if(!r){let a=await this.discovery.discover(e);if(!a?.tokenEndpoint)return O(`Cannot find token endpoint for '${e}'.
|
|
32
32
|
The OAuth discovery endpoint may be unreachable.
|
|
33
|
-
Check network connectivity and run 'kanonak login ${e}' to re-authenticate.`);r=a.tokenEndpoint}let o=await this.refreshTokenRequest(r,t.clientId,t.clientSecret,t.refreshToken,t.dpopKeyPair);return o.success?(t.accessToken=o.tokens.accessToken,o.tokens.refreshToken&&(t.refreshToken=o.tokens.refreshToken),t.expiresAt=o.tokens.expiresIn?new Date(Date.now()+o.tokens.expiresIn*1e3).toISOString():null,t.tokenEndpoint=r,await this.credentialStore.store(e,t),{success:!0,host:e}):
|
|
34
|
-
The refresh token may have expired. Run 'kanonak login ${e}' to re-authenticate.`)}async logout(e){let t=await this.credentialStore.getCredential(e);if(!t)return
|
|
35
|
-
You may not be logged in, or credentials may be stored in a different backend.`);let r=await this.discovery.discover(e);if(r?.revocationEndpoint&&t.accessToken&&t.clientId)try{await this.revokeToken(r.revocationEndpoint,t.accessToken,t.clientId)}catch{console.warn(` Warning: Token revocation failed for '${e}'. The token has been removed locally but may still be valid on the server until it expires.`)}return await this.credentialStore.remove(e),{success:!0,host:e}}async registerClient(e,t){let r;try{r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak CLI",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})})}catch(
|
|
33
|
+
Check network connectivity and run 'kanonak login ${e}' to re-authenticate.`);r=a.tokenEndpoint}let o=await this.refreshTokenRequest(r,t.clientId,t.clientSecret,t.refreshToken,t.dpopKeyPair);return o.success?(t.accessToken=o.tokens.accessToken,o.tokens.refreshToken&&(t.refreshToken=o.tokens.refreshToken),t.expiresAt=o.tokens.expiresIn?new Date(Date.now()+o.tokens.expiresIn*1e3).toISOString():null,t.tokenEndpoint=r,await this.credentialStore.store(e,t),{success:!0,host:e}):O(`${o.error}
|
|
34
|
+
The refresh token may have expired. Run 'kanonak login ${e}' to re-authenticate.`)}async logout(e){let t=await this.credentialStore.getCredential(e);if(!t)return O(`No stored credentials for '${e}'.
|
|
35
|
+
You may not be logged in, or credentials may be stored in a different backend.`);let r=await this.discovery.discover(e);if(r?.revocationEndpoint&&t.accessToken&&t.clientId)try{await this.revokeToken(r.revocationEndpoint,t.accessToken,t.clientId)}catch{console.warn(` Warning: Token revocation failed for '${e}'. The token has been removed locally but may still be valid on the server until it expires.`)}return await this.credentialStore.remove(e),{success:!0,host:e}}async registerClient(e,t){let r;try{r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"Kanonak CLI",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})})}catch(i){return{success:!1,error:`Dynamic client registration request to ${e} failed: ${se(i)}
|
|
36
36
|
Ensure the IDP is reachable and HTTPS is properly configured.
|
|
37
|
-
If using a corporate proxy or custom CA, set NODE_EXTRA_CA_CERTS.`}}if(!r.ok){let
|
|
37
|
+
If using a corporate proxy or custom CA, set NODE_EXTRA_CA_CERTS.`}}if(!r.ok){let i=await ln(r);return{success:!1,error:`Dynamic client registration (RFC 7591) failed.
|
|
38
38
|
Endpoint: ${e}
|
|
39
|
-
HTTP ${r.status}: ${
|
|
39
|
+
HTTP ${r.status}: ${i}
|
|
40
40
|
The IDP may not support dynamic registration for public clients.
|
|
41
41
|
Ask your IDP administrator to enable RFC 7591 support, or pre-register a client manually.`}}let o=await r.json(),a=o.client_id;return a?{success:!0,clientId:a,clientSecret:o.client_secret}:{success:!1,error:`Dynamic client registration response from ${e} did not contain a client_id.
|
|
42
|
-
The IDP response may be malformed. Contact your IDP administrator.`}}async exchangeCode(e,t,r,o,a,s
|
|
43
|
-
The stored key pair may be corrupted. Run 'kanonak login' to re-authenticate.`}}let
|
|
44
|
-
Ensure the token endpoint is reachable.`}}if(!
|
|
42
|
+
The IDP response may be malformed. Contact your IDP administrator.`}}async exchangeCode(e,t,r,o,a,i,s){let c=new URLSearchParams({grant_type:"authorization_code",client_id:t,code:o,redirect_uri:a,code_verifier:i});r&&c.set("client_secret",r);let l={"Content-Type":"application/x-www-form-urlencoded"};if(s)try{l.DPoP=ot(s.privateKey,s.publicKey,"POST",e)}catch(f){return{success:!1,error:`Failed to create DPoP proof for token exchange: ${se(f)}
|
|
43
|
+
The stored key pair may be corrupted. Run 'kanonak login' to re-authenticate.`}}let d;try{d=await fetch(e,{method:"POST",headers:l,body:c.toString()})}catch(f){return{success:!1,error:`Token exchange request to ${e} failed: ${se(f)}
|
|
44
|
+
Ensure the token endpoint is reachable.`}}if(!d.ok){let f=await ln(d),p=Wo(f);return{success:!1,error:`Token exchange failed.
|
|
45
45
|
Endpoint: ${e}
|
|
46
|
-
HTTP ${
|
|
47
|
-
${p}`:"")}}return{success:!0,tokens:
|
|
46
|
+
HTTP ${d.status}: ${f}`+(p?`
|
|
47
|
+
${p}`:"")}}return{success:!0,tokens:at(await d.json())}}async refreshTokenRequest(e,t,r,o,a){let i=new URLSearchParams({grant_type:"refresh_token",client_id:t,refresh_token:o});r&&i.set("client_secret",r);let s={"Content-Type":"application/x-www-form-urlencoded"};if(a)try{s.DPoP=ot(a.privateKey,a.publicKey,"POST",e)}catch(l){return{success:!1,error:`Failed to create DPoP proof for token refresh: ${se(l)}`}}let c;try{c=await fetch(e,{method:"POST",headers:s,body:i.toString()})}catch(l){return{success:!1,error:`Token refresh request to ${e} failed: ${se(l)}`}}if(!c.ok){let l=await ln(c);return{success:!1,error:`Token refresh failed \u2014 HTTP ${c.status}: ${l}`}}return{success:!0,tokens:at(await c.json())}}async revokeToken(e,t,r){await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:t,client_id:r}).toString()})}};function O(n){return{success:!1,error:n}}function at(n){return{accessToken:n.access_token,refreshToken:n.refresh_token,expiresIn:typeof n.expires_in=="number"?n.expires_in:void 0}}function se(n){return n instanceof Error?n.message:String(n)}async function ln(n){try{return await n.text()}catch{return"(could not read response body)"}}function Wo(n){try{let e=JSON.parse(n);switch(e.error){case"invalid_grant":return"Hint: The authorization code may have expired or already been used. Re-run the login flow.";case"invalid_client":return"Hint: The client credentials were rejected. The client_id may be invalid or the client_secret may be wrong.";case"redirect_uri_mismatch":return"Hint: The redirect_uri does not match what was registered with the IDP.";case"unsupported_grant_type":return"Hint: The IDP does not support authorization_code grants. Contact your IDP administrator.";case"invalid_scope":return"Hint: One or more requested scopes are not allowed. Check the scopes configured on the IDP.";case"use_dpop_nonce":return"Hint: The server requires a DPoP nonce. This should be handled automatically \u2014 please report this as a bug.";default:return e.error_description?`IDP says: ${e.error_description}`:null}}catch{return null}}function Go(){return it(32).toString("base64url")}function Jo(n){return Mo("sha256").update(n).digest("base64url")}function Xo(){return it(16).toString("base64url")}function Yo(n,e,t,r,o,a){let i=new URLSearchParams({client_id:e,response_type:"code",redirect_uri:t,scope:r.join(" "),state:o,code_challenge:a,code_challenge_method:"S256"});return`${n}?${i}`}var Zo=300*1e3;async function Qo(){return new Promise(n=>{let e=Bo((o,a)=>{let i=new URL(o.url,"http://localhost"),s=i.searchParams.get("code")??void 0,c=i.searchParams.get("state")??void 0,l=i.searchParams.get("error")??i.searchParams.get("error_description")??void 0,d=l?ea(l):null,f=d?`<html><body><h1>Authorization failed</h1><p>${d}</p></body></html>`:"<html><body><h1>Authorization successful!</h1><p>You can close this window.</p></body></html>";a.writeHead(200,{"Content-Type":"text/html"}),a.end(f),t({code:s,state:c,error:l})}),t,r=new Promise(o=>{t=o,setTimeout(()=>{o(null),e.close()},Zo)});e.listen(0,"127.0.0.1",()=>{let o=e.address();n({redirectUri:`http://localhost:${o.port}/callback`,port:o.port,waitForCallback:()=>r,close:()=>e.close()})})})}function ea(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function na(n){try{process.platform==="win32"?cn("cmd",["/c","start","",n]):process.platform==="darwin"?cn("open",[n]):cn("xdg-open",[n])}catch{console.log(" Could not open browser automatically. Please navigate to the URL above manually.")}}import{CredentialStore as ta}from"@kanonak-protocol/sdk";async function st(n){try{let e=new X,t=new ta,o=await new ce(e,t).authorize(n);o.success?console.log(`
|
|
48
48
|
Authenticated with ${n}.`):(console.error(`
|
|
49
49
|
Authentication failed:
|
|
50
50
|
${o.error}`),process.exit(1))}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`
|
|
51
51
|
Authentication failed unexpectedly:
|
|
52
52
|
${t}`),console.error(`
|
|
53
|
-
If this persists, see https://github.com/kanonak-protocol for support channels.`),process.exit(1)}}import{CredentialStore as
|
|
53
|
+
If this persists, see https://github.com/kanonak-protocol for support channels.`),process.exit(1)}}import{CredentialStore as ra}from"@kanonak-protocol/sdk";async function ct(n){try{let e=new X,t=new ra,o=await new ce(e,t).logout(n);o.success?console.log(`Logged out from ${n}.`):(console.error(`
|
|
54
54
|
Logout failed:
|
|
55
55
|
${o.error}`),process.exit(1))}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`
|
|
56
56
|
Logout failed unexpectedly:
|
|
57
|
-
${t}`),process.exit(1)}}import{Command as
|
|
58
|
-
`;function
|
|
59
|
-
Installed capability "${
|
|
60
|
-
`);for(let[t,r]of e)console.log(` ${t} ${r.publisher}/${r.package_}@${r.version}`)}import{Command as
|
|
61
|
-
`);return t?.trailingNewline&&(
|
|
62
|
-
`)||(
|
|
63
|
-
`)),
|
|
57
|
+
${t}`),process.exit(1)}}import{Command as Ta}from"commander";import{KanonakParser as ja,KanonakObjectParser as Ua,PublisherIndex as Oa,CredentialStore as xa,createAuthenticatedFetch as Na,computeIntegrity as La}from"@kanonak-protocol/sdk";import{readFileSync as oa,writeFileSync as aa,existsSync as ia}from"fs";import{join as sa}from"path";import lt from"js-yaml";import{getGlobalCachePath as ca}from"@kanonak-protocol/sdk";var la=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
58
|
+
`;function ut(){let n=ca();return sa(n,"..","capabilities.lock")}function le(){let n=ut();if(!ia(n))return{version:"1",lastUpdated:new Date().toISOString(),capabilities:{}};let e=oa(n,"utf-8"),t=lt.load(e);return!t||typeof t!="object"||t.version!=="1"?{version:"1",lastUpdated:new Date().toISOString(),capabilities:{}}:{version:"1",lastUpdated:t.lastUpdated??new Date().toISOString(),capabilities:t.capabilities??{}}}function be(n){n.lastUpdated=new Date().toISOString();let e={};for(let r of Object.keys(n.capabilities).sort())e[r]=n.capabilities[r];n.capabilities=e;let t=lt.dump(n,{lineWidth:-1,sortKeys:!1,quotingType:'"'});aa(ut(),la+t,"utf-8")}var E=class{constructor(e,t){this.doc=e;this.broader=t}doc;broader;async getAllDocumentsAsync(){return[this.doc]}async getDocumentAsync(e){return this.broader.getDocumentAsync(e)}async getDocumentsByNamespaceAsync(e,t){return this.broader.getDocumentsByNamespaceAsync(e,t)}async getHighestCompatibleVersionAsync(e,t){return this.broader.getHighestCompatibleVersionAsync(e,t)}async saveDocumentAsync(){throw new Error("SingleDocumentRepository is read-only")}async deleteDocumentAsync(){throw new Error("SingleDocumentRepository is read-only")}async clearNamespaceAsync(){throw new Error("SingleDocumentRepository is read-only")}async getAllDocumentReferencesAsync(){return[]}async getDocumentContentAsync(e){return this.broader.getDocumentContentAsync(e)}async getDocumentUriAsync(e){return this.broader.getDocumentUriAsync(e)}};import{existsSync as ka,readdirSync as ha,readFileSync as ya}from"fs";import{join as mt}from"path";import{KanonakObjectParser as ba,EmbeddedKanonak as ht,ReferenceKanonak as yt,getGlobalCachePath as wa}from"@kanonak-protocol/sdk";import{SubjectKanonak as dt,DefinedKanonak as ua,StringStatement as da,NumberStatement as fa,BooleanStatement as ma,ReferenceStatement as ft,EmbeddedStatement as pu,ListStatement as pa}from"@kanonak-protocol/sdk";function B(n){return`${n.publisher}/${n.package_}/${n.name}`}function U(n,e){return n.publisher===e.publisher&&n.package_===e.package_&&n.name===e.name}function v(n,e){if(!(n instanceof ua))return!1;for(let t of n.statement)if(t.predicate?.subject?.name==="type"&&t instanceof ft){let o=t.object;if(U(o.subject,e))return!0}return!1}function C(n,e){let t=[];for(let r of n)r instanceof dt&&v(r,e)&&t.push(r);return t}function we(n,e){let t=e.version,r=t&&typeof t.major=="number"?`${e.publisher}/${e.package_}@${t.major}.${t.minor}.${t.patch}`:void 0;for(let o of n){if(!(o instanceof dt)||o.name!==e.name)continue;let a=o.namespace||"";if(r!==void 0){if(a===r)return o}else if(a.startsWith(`${e.publisher}/${e.package_}@`))return o}}function un(n,e){for(let t of n.statement){let r=t.predicate;if(r?.subject&&U(r.subject,e))return t}}function ga(n,e){let t=un(n,e);if(t&&(t instanceof da||t instanceof fa||t instanceof ma))return t.object}function R(n,e){let t=ga(n,e);return typeof t=="string"?t:void 0}function ue(n,e){let t=un(n,e);if(t instanceof ft)return t.object.subject}function dn(n,e){let t=un(n,e);return t instanceof pa?t.object??[]:[]}var _="kanonak.org",I="capabilities",fn={publisher:_,package_:I,name:"Capability"},$a={publisher:_,package_:I,name:"commandName"},bt={publisher:_,package_:I,name:"description"},Sa={publisher:_,package_:I,name:"managesType"},va={publisher:_,package_:I,name:"deploymentTarget"},Pa={publisher:_,package_:I,name:"hasCommand"},Ka={publisher:_,package_:I,name:"subcommandName"},Da={publisher:_,package_:I,name:"performs"},Ea={publisher:_,package_:I,name:"hasArgument"},Ca={publisher:_,package_:I,name:"argumentName"},pt={publisher:_,package_:I,name:"isRequired"},gt={publisher:_,package_:I,name:"isOption"},Aa={publisher:_,package_:I,name:"defaultValue"};async function wt(n,e,t){let r=le(),o=new ba,a=[],i=!1;for(let[s,c]of Object.entries(r.capabilities)){let l=c,d=n.get(l.publisher,l.package_,l.version);if(!d){let f=await Ra(s,l,e,o,t);if(f)console.error(` Healed capability "${s}": ${l.publisher}/${l.package_}@${l.version} \u2192 ${f.entry.publisher}/${f.entry.package_}@${f.entry.version} (package was renamed)`),r.capabilities[s]=f.entry,l=f.entry,d=f.content,i=!0;else{console.error(` WARNING: Cached content missing for capability "${s}" (${l.publisher}/${l.package_}@${l.version}). Reinstall it with: kanonak capability remove ${s} && kanonak capability add ${l.publisher}/${l.package_}`);continue}}try{let f=e.parse(d),p=new E(f,t),k=await o.parseKanonaks(p),b=$t(k,l.publisher,l.package_,l.version);b?a.push(b):console.error(` WARNING: No Capability instance found in "${s}" (${l.publisher}/${l.package_}@${l.version})`)}catch(f){console.error(` WARNING: Failed to parse capability "${s}": ${f}`)}}return i&&be(r),a}async function Ra(n,e,t,r,o){let a=mt(wa(),e.publisher);if(!ka(a))return;let i=[];for(let s of ha(a)){if(!s.endsWith(".kan.yml"))continue;let c=s.slice(0,-8),l=c.lastIndexOf("@");if(l===-1)continue;let d=c.substring(0,l),f=c.substring(l+1);if(d===e.package_&&f===e.version)continue;let p;try{p=ya(mt(a,s),"utf-8")}catch{continue}let k;try{let b=t.parse(p),g=new E(b,o),y=await r.parseKanonaks(g);k=$t(y,e.publisher,d,f)?.commandName}catch{continue}k===n&&i.push({entry:{publisher:e.publisher,package_:d,version:f,resolved:`kanonak://${e.publisher}/${d}@${f}`,integrity:""},content:p})}if(i.length===1)return i[0]}function $t(n,e,t,r){let o=C(n,fn);if(o.length===0)return;let a=o[0],i=R(a,$a)??"",s=R(a,bt)??"",c=ue(a,Sa),l=ue(a,va),d=[];for(let f of dn(a,Pa)){let p=_a(f,n);p&&d.push(p)}return{commandName:i,description:s,managesTypeKey:c?B(c):"",deploymentTargetKey:l?B(l):"",commands:d,publisher:e,package_:t,version:r}}function _a(n,e){let t;if(n instanceof ht)t=n;else if(n instanceof yt){let c=St(e,n.subject.publisher,n.subject.package_,n.subject.name);c&&(t=c)}if(!t)return;let r=R(t,Ka)??"",o=R(t,bt)??"",a=ue(t,Da),i=dn(t,Ea),s=[];for(let c of i){let l=Ia(c,e);l&&s.push(l)}return{subcommandName:r,description:o,arguments:s,actionKey:a?B(a):""}}function Ia(n,e){let t;if(n instanceof ht)t=n;else if(n instanceof yt){let c=St(e,n.subject.publisher,n.subject.package_,n.subject.name);c&&(t=c)}if(!t)return;let r=R(t,Ca)??"",o=R(t,pt)==="true"||kt(t,pt)===!0,a=R(t,gt)==="true"||kt(t,gt)===!0,i=R(t,Aa),s={argumentName:r,required:o,isOption:a};return i!==void 0&&(s.defaultValue=i),s}function kt(n,e){for(let t of n.statement){let r=t,o=r.predicate;if(o?.subject&&o.subject.publisher===e.publisher&&o.subject.package_===e.package_&&o.subject.name===e.name)return typeof r.object=="boolean"?r.object:void 0}}function St(n,e,t,r){for(let o of n){if(!("name"in o)||!("namespace"in o))continue;let a=o;if(a.name===r&&!(!a.namespace||typeof a.namespace!="string")&&a.namespace.startsWith(`${e}/${t}@`))return o}}var Fa={publisher:_,package_:I,name:"commandName"};function vt(){let n=new Ta("capability").description("Manage Kanonak CLI capabilities (pluggable command groups)");return n.command("add <package>").description("Install a capability from a Kanonak publisher").action(async e=>{await Va(e)}),n.command("remove <name>").description("Remove an installed capability").action(async e=>{await Ma(e)}),n.command("list").description("List installed capabilities").action(async()=>{await Ba()}),n}async function Va(n){let e=z(n);e||(console.error(`Invalid package reference: "${n}"`),console.error("Expected format: {publisher}/{package}[@{version}]"),process.exit(1));let{publisher:t,packageName:r,version:o,instanceName:a}=e;a&&(console.error(`\`kanonak capability add\` installs whole packages \u2014 got an instance suffix "/${a}".`),console.error(`Try: kanonak capability add ${t}/${r}${o?"@"+o:""}`),process.exit(1));let i=new V,s=new ja,c=new Ua,l=new xa,d=Na(l),f=new Oa({fetchFn:d}),p=o??await f.getHighestVersion(t,r);p||(console.error(`Could not resolve version for "${t}/${r}".`),process.exit(1)),console.log(`Installing capability ${t}/${r}@${p}...`);let k=i.get(t,r,p);if(!k){let T=await f.getPackageUrl(t,r,p),F=await d(T,t);if(!F.ok)throw new Error(`Failed to fetch ${T} (${F.status} ${F.statusText})`);k=await F.text(),i.put(t,r,p,k)}let b=s.parse(k),g=await j(process.cwd(),s),y=new E(b,g),h=await c.parseKanonaks(y),w=C(h,fn);w.length===0&&(console.error(`Package ${t}/${r}@${p} does not contain a ${_}/${I}/Capability instance.`),process.exit(1));let $=w[0],S=R($,Fa);S||(console.error(`Capability instance in ${t}/${r}@${p} has no commandName property.`),process.exit(1));let D=le();D.capabilities[S]={publisher:t,package_:r,version:p,resolved:await f.getPackageUrl(t,r,p),integrity:La(k)},be(D),console.log(`
|
|
59
|
+
Installed capability "${S}".`),console.log(`Run "kanonak ${S} --help" to get started.`)}async function Ma(n){let e=le();e.capabilities[n]||(console.error(`Capability "${n}" is not installed.`),process.exit(1));let t=e.capabilities[n];delete e.capabilities[n],be(e),console.log(`Removed capability "${n}" (${t.publisher}/${t.package_}@${t.version}).`)}async function Ba(){let n=le(),e=Object.entries(n.capabilities);if(e.length===0){console.log("No capabilities installed."),console.log("Install one with: kanonak capability add {publisher}/{package}");return}console.log(`Installed capabilities:
|
|
60
|
+
`);for(let[t,r]of e)console.log(` ${t} ${r.publisher}/${r.package_}@${r.version}`)}import{Command as De}from"commander";import{readFileSync as zi,writeFileSync as qi,mkdirSync as Wi,existsSync as sr,statSync as Gi}from"fs";import{join as Ji,resolve as Xi}from"path";import{KanonakParser as Cn,KanonakObjectParser as An,SubjectKanonak as Yi,Reasoner as Zi,KanonakVocabulary as Qi,makeUriKey as lr,pickHighestDocument as Rn,formatVersion as ur}from"@kanonak-protocol/sdk";var Ha="kanonak.org",za="transformations";var m=n=>({publisher:Ha,package_:za,name:n}),u={Transformation:m("Transformation"),InstanceTransformation:m("InstanceTransformation"),SetTransformation:m("SetTransformation"),inputPattern:m("inputPattern"),rule:m("rule"),artifactName:m("artifactName"),outputs:m("outputs"),formatOverrides:m("formatOverrides"),partitionBy:m("partitionBy"),InputPattern:m("InputPattern"),matchesClass:m("matchesClass"),requires:m("requires"),sortBy:m("sortBy"),SortKey:m("SortKey"),byProperty:m("byProperty"),order:m("order"),SortOrder:m("SortOrder"),ascending:m("ascending"),descending:m("descending"),OutputFormat:m("OutputFormat"),backendUri:m("backendUri"),FormatOverride:m("FormatOverride"),formatTarget:m("formatTarget"),metadataKeys:m("metadataKeys"),metadataRenames:m("metadataRenames"),trailingNewline:m("trailingNewline"),omitWrapper:m("omitWrapper"),RenameEntry:m("RenameEntry"),fromKey:m("fromKey"),toKey:m("toKey"),FMT_MARKDOWN_FRONTMATTER:m("markdown-with-frontmatter"),FMT_PLAIN_MARKDOWN:m("plain-markdown"),FMT_TOML:m("toml"),FMT_JSON:m("json"),FMT_HTML:m("html"),FMT_SVG:m("svg"),Expression:m("Expression"),ListSourcedExpression:m("ListSourcedExpression"),ListAggregate:m("ListAggregate"),IteratingExpression:m("IteratingExpression"),BuildAstNode:m("BuildAstNode"),astClass:m("astClass"),set:m("set"),AstFieldBinding:m("AstFieldBinding"),field:m("field"),bindValue:m("bindValue"),When:m("When"),condition:m("condition"),thenBuild:m("thenBuild"),elseBuild:m("elseBuild"),Concat:m("Concat"),parts:m("parts"),Fallback:m("Fallback"),primary:m("primary"),alternate:m("alternate"),StringLiteral:m("StringLiteral"),stringLiteral:m("stringLiteral"),IntegerLiteral:m("IntegerLiteral"),integerLiteral:m("integerLiteral"),DecimalLiteral:m("DecimalLiteral"),decimalLiteral:m("decimalLiteral"),BooleanLiteral:m("BooleanLiteral"),booleanLiteral:m("booleanLiteral"),VarRef:m("VarRef"),varName:m("varName"),PropertyRead:m("PropertyRead"),readSource:m("readSource"),readProp:m("readProp"),Traverse:m("Traverse"),traverseSource:m("traverseSource"),through:m("through"),step:m("step"),UriName:m("UriName"),uriNameOf:m("uriNameOf"),UriPublisher:m("UriPublisher"),uriPublisherOf:m("uriPublisherOf"),UriPackage:m("UriPackage"),uriPackageOf:m("uriPackageOf"),UriVersion:m("UriVersion"),uriVersionOf:m("uriVersionOf"),SubjectUri:m("SubjectUri"),subjectOf:m("subjectOf"),UriLiteral:m("UriLiteral"),refTo:m("refTo"),DisplayLabel:m("DisplayLabel"),labelTarget:m("labelTarget"),labelSource:m("labelSource"),ResolveRef:m("ResolveRef"),resolveSource:m("resolveSource"),Normalize:m("Normalize"),normSource:m("normSource"),normKind:m("normKind"),NormalizeKind:m("NormalizeKind"),NORM_TRIM_END:m("trim-end"),IsSet:m("IsSet"),checkExpr:m("checkExpr"),ExpressionFragment:m("ExpressionFragment"),body:m("body"),CallFragment:m("CallFragment"),fragmentRef:m("fragmentRef"),source:m("source"),Join:m("Join"),separator:m("separator"),Count:m("Count"),Sum:m("Sum"),Min:m("Min"),Max:m("Max"),Average:m("Average"),loopVar:m("loopVar"),ForEach:m("ForEach"),emit:m("emit"),ListMap:m("ListMap"),mapBody:m("mapBody"),Filter:m("Filter"),predicate:m("predicate"),PartitionBy:m("PartitionBy"),partitionKey:m("partitionKey"),DistinctBy:m("DistinctBy"),distinctKey:m("distinctKey"),Partition:m("Partition"),key:m("key"),members:m("members"),AllStatements:m("AllStatements"),statementsOf:m("statementsOf"),StatementPredicate:m("StatementPredicate"),predicateOf:m("predicateOf"),StatementValue:m("StatementValue"),valueOf:m("valueOf"),DateFormat:m("DateFormat"),dateSource:m("dateSource"),dateFormat:m("dateFormat"),BinaryArithmetic:m("BinaryArithmetic"),arithLeft:m("arithLeft"),arithRight:m("arithRight"),Add:m("Add"),Subtract:m("Subtract"),Multiply:m("Multiply"),Divide:m("Divide"),Reverse:m("Reverse")};import{DefinedKanonak as Qt,ReferenceKanonak as er,StringStatement as nr,NumberStatement as tr,BooleanStatement as rr,ReferenceStatement as or,ListStatement as ar}from"@kanonak-protocol/sdk";var qa="kanonak.org",Wa="document-ast",K=n=>({publisher:qa,package_:Wa,name:n}),H={Document:K("Document"),Block:K("Block"),Inline:K("Inline"),StructuredValue:K("StructuredValue"),Heading:K("Heading"),Paragraph:K("Paragraph"),RawBlock:K("RawBlock"),Text:K("Text"),StructuredMap:K("StructuredMap"),StructuredEntry:K("StructuredEntry"),StructuredList:K("StructuredList"),StringScalar:K("StringScalar"),IntegerScalar:K("IntegerScalar"),EscapeHint:K("EscapeHint"),MediaType:K("MediaType"),metadata:K("metadata"),children:K("children"),level:K("level"),inlines:K("inlines"),text:K("text"),entries:K("entries"),key:K("key"),value:K("value"),escapeHint:K("escapeHint"),items:K("items"),stringValue:K("stringValue"),integerValue:K("integerValue"),rawContent:K("rawContent"),mediaType:K("mediaType"),mimeType:K("mimeType"),ESC_RAW:K("esc-raw"),ESC_YAML_SAFE:K("esc-yaml-safe"),ESC_TOML_STRING:K("esc-toml-string"),ESC_TOML_MULTILINE:K("esc-toml-multiline"),ESC_JSON:K("esc-json"),TEXT_PLAIN:K("text-plain"),TEXT_MARKDOWN:K("text-markdown"),TEXT_HTML:K("text-html"),APPLICATION_JSON:K("application-json"),TEXT_YAML:K("text-yaml"),IMAGE_SVG_XML:K("image-svg-xml")};function Pt(n,e){return n.publisher===e.publisher&&n.package_===e.package_&&n.name===e.name}var Re=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,t){let r=Ga(e.metadata,t),o=Ya(e.children),i=["---",...r,"---","",o].join(`
|
|
61
|
+
`);return t?.trailingNewline&&(i.endsWith(`
|
|
62
|
+
`)||(i+=`
|
|
63
|
+
`)),i}};function Ga(n,e){if(!n)return[];let t=new Map;for(let s of n.entries)t.set(Ae(s.key),s);let r=new Map;if(e?.metadataRenames)for(let[s,c]of e.metadataRenames)r.set(Ae(s),c);let a=(e?.metadataKeys??n.entries.map(s=>s.key)).map(Ae),i=[];for(let s of a){let c=t.get(s);if(!c)continue;let l=r.get(s),d=Ae(l??s),f=Dt(c.value,c.escapeHint);f!==void 0&&i.push(`${d}: ${f}`)}return i}function Ae(n){let e=n.lastIndexOf(".");return e===-1?n:n.substring(e+1)||n}function Dt(n,e){switch(n.kind){case"StringScalar":return Ja(n.stringValue,e);case"IntegerScalar":return String(n.integerValue);case"StructuredList":{let t=[];for(let r of n.items){let o=Dt(r,e);o!==void 0&&t.push(o)}return t.join(", ")}case"StructuredMap":return;default:return}}function Ja(n,e){return!e||Pt(e,H.ESC_RAW)?n:Pt(e,H.ESC_YAML_SAFE)?Xa(n):n}function Xa(n){return n.includes(`
|
|
64
64
|
`)?`|-
|
|
65
65
|
${n.replace(/\n/g,`
|
|
66
|
-
`).trimEnd()}`:/[:#\[\]{}&*!|>'"%@`,]/.test(n)?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:n}function
|
|
66
|
+
`).trimEnd()}`:/[:#\[\]{}&*!|>'"%@`,]/.test(n)?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:n}function Ya(n){let e=[];for(let t of n){let r=Za(t);r&&e.push(r)}return e.join(`
|
|
67
67
|
|
|
68
|
-
`)}function
|
|
68
|
+
`)}function Za(n){switch(n.kind){case"Heading":return`${"#".repeat(n.level)} ${Kt(n.inlines)}`;case"Paragraph":return Kt(n.inlines);case"RawBlock":return n.rawContent;default:return""}}function Kt(n){let e=[];for(let t of n)t.kind==="Text"&&e.push(t.text);return e.join("")}function Qa(n,e){return n.publisher===e.publisher&&n.package_===e.package_&&n.name===e.name}var _e=class{backendUri="kanonak.org/transformations/toml";render(e,t){let o=ei(e.metadata,t).join(`
|
|
69
69
|
`);return t?.trailingNewline&&(o.endsWith(`
|
|
70
70
|
`)||(o+=`
|
|
71
|
-
`)),o}};function
|
|
71
|
+
`)),o}};function ei(n,e){if(!n)return[];let t=new Map;for(let a of n.entries)t.set(a.key,a);let r=e?.metadataKeys??n.entries.map(a=>a.key),o=[];for(let a of r){let i=t.get(a);if(!i)continue;let s=e?.metadataRenames.get(a)??a,c=Et(i.value,i.escapeHint);c!==void 0&&o.push(`${s} = ${c}`)}return o}function Et(n,e){switch(n.kind){case"StringScalar":return ni(n.stringValue,e);case"IntegerScalar":return String(n.integerValue);case"StructuredList":{let t=[];for(let r of n.items){let o=Et(r,e);o!==void 0&&t.push(o)}return`[${t.join(", ")}]`}case"StructuredMap":return;default:return}}function ni(n,e){return e&&Qa(e,H.ESC_TOML_MULTILINE)?ri(n):ti(n)}function ti(n){return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}"`}function ri(n){return`"""
|
|
72
72
|
${n.replace(/"""/g,'\\"\\"\\"')}
|
|
73
|
-
"""`}var
|
|
73
|
+
"""`}var Ie=class{backendUri="kanonak.org/transformations/json";render(e,t){let r=JSON.stringify(e,null,2);return t?.trailingNewline&&!r.endsWith(`
|
|
74
74
|
`)?r+`
|
|
75
|
-
`:r}};function
|
|
75
|
+
`:r}};function At(n){let e=n.replace(/\r\n/g,`
|
|
76
76
|
`).split(`
|
|
77
|
-
`),t=[],r=0;for(;r<e.length;){let o=e[r];if(o.trim()===""){r++;continue}let a=/^(\s*)```(\S*)\s*$/.exec(o);if(a){let c=a[2],l=[];for(r++;r<e.length&&!/^(\s*)```\s*$/.test(e[r]);)l.push(e[r]),r++;r++;let
|
|
78
|
-
`)),f=c?` class="language-${
|
|
77
|
+
`),t=[],r=0;for(;r<e.length;){let o=e[r];if(o.trim()===""){r++;continue}let a=/^(\s*)```(\S*)\s*$/.exec(o);if(a){let c=a[2],l=[];for(r++;r<e.length&&!/^(\s*)```\s*$/.test(e[r]);)l.push(e[r]),r++;r++;let d=Rt(l.join(`
|
|
78
|
+
`)),f=c?` class="language-${_t(c)}"`:"";t.push(`<pre><code${f}>${d}</code></pre>`);continue}let i=/^(#{1,6})\s+(.*)$/.exec(o);if(i){let c=i[1].length,l=de(i[2].trim());t.push(`<h${c}>${l}</h${c}>`),r++;continue}if(o.includes("|")&&r+1<e.length&&Ct(e[r+1])){let c=mn(o),l=oi(e[r+1]);r+=2;let d=[];for(;r<e.length&&e[r].trim()!==""&&e[r].includes("|");)d.push(mn(e[r])),r++;t.push(ai(c,l,d));continue}if(/^\s*[-*]\s+/.test(o)){let c=[];for(;r<e.length&&/^\s*[-*]\s+/.test(e[r]);){let l=[e[r].replace(/^\s*[-*]\s+/,"")];for(r++;r<e.length&&e[r].trim()!==""&&!/^\s*[-*]\s+/.test(e[r])&&!/^\s*\d+\.\s+/.test(e[r]);)l.push(e[r]),r++;r<e.length&&e[r].trim()===""&&r++,c.push(`<li>${de(l.join(" ").trim())}</li>`)}t.push(`<ul>
|
|
79
79
|
${c.join(`
|
|
80
80
|
`)}
|
|
81
|
-
</ul>`);continue}if(/^\s*\d+\.\s+/.test(o)){let c=[];for(;r<e.length&&/^\s*\d+\.\s+/.test(e[r]);){let l=[e[r].replace(/^\s*\d+\.\s+/,"")];for(r++;r<e.length&&e[r].trim()!==""&&!/^\s*\d+\.\s+/.test(e[r])&&!/^\s*[-*]\s+/.test(e[r]);)l.push(e[r]),r++;r<e.length&&e[r].trim()===""&&r++,c.push(`<li>${
|
|
81
|
+
</ul>`);continue}if(/^\s*\d+\.\s+/.test(o)){let c=[];for(;r<e.length&&/^\s*\d+\.\s+/.test(e[r]);){let l=[e[r].replace(/^\s*\d+\.\s+/,"")];for(r++;r<e.length&&e[r].trim()!==""&&!/^\s*\d+\.\s+/.test(e[r])&&!/^\s*[-*]\s+/.test(e[r]);)l.push(e[r]),r++;r<e.length&&e[r].trim()===""&&r++,c.push(`<li>${de(l.join(" ").trim())}</li>`)}t.push(`<ol>
|
|
82
82
|
${c.join(`
|
|
83
83
|
`)}
|
|
84
|
-
</ol>`);continue}let
|
|
85
|
-
`)}function
|
|
84
|
+
</ol>`);continue}let s=[o];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6})\s+/.test(e[r])&&!/^(\s*)```/.test(e[r])&&!/^\s*[-*]\s+/.test(e[r])&&!/^\s*\d+\.\s+/.test(e[r])&&!(e[r].includes("|")&&r+1<e.length&&Ct(e[r+1]));)s.push(e[r]),r++;t.push(`<p>${de(s.join(" "))}</p>`)}return t.join(`
|
|
85
|
+
`)}function Ct(n){return n.includes("-")?/^[\s|:-]+$/.test(n):!1}function mn(n){let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())}function oi(n){return mn(n).map(e=>{let t=e.startsWith(":"),r=e.endsWith(":");return t&&r?"center":r?"right":t?"left":null})}function ai(n,e,t){let r=i=>{let s=e[i];return s?` style="text-align:${s}"`:""},o=n.map((i,s)=>`<th${r(s)}>${de(i)}</th>`).join(""),a=t.map(i=>`<tr>${i.map((c,l)=>`<td${r(l)}>${de(c)}</td>`).join("")}</tr>`).join(`
|
|
86
86
|
`);return`<table>
|
|
87
87
|
<thead><tr>${o}</tr></thead>
|
|
88
88
|
<tbody>
|
|
89
89
|
${a}
|
|
90
90
|
</tbody>
|
|
91
|
-
</table>`}function
|
|
91
|
+
</table>`}function de(n){let e=Rt(n);return e=e.replace(/`([^`\n]+)`/g,(t,r)=>`<code>${r}</code>`),e=e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(t,r,o)=>`<a href="${_t(o)}">${r}</a>`),e=e.replace(/\*\*([^*\n]+)\*\*/g,(t,r)=>`<strong>${r}</strong>`),e=e.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,(t,r,o)=>`${r}<em>${o}</em>`),e=e.replace(/(^|[\s(])_([^_\n]+)_(?=[\s).,;:!?]|$)/g,(t,r,o)=>`${r}<em>${o}</em>`),e}function Rt(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function _t(n){return n.replace(/"/g,""").replace(/&/g,"&")}function pn(n,e){return n.publisher===e.publisher&&n.package_===e.package_&&n.name===e.name}var Te=class{backendUri="kanonak.org/transformations/html";render(e,t){let r=ci(e.children);if(t?.omitWrapper){let s=r.endsWith(`
|
|
92
|
+
`)?r:`${r}
|
|
93
|
+
`;return t.trailingNewline===!1&&s.endsWith(`
|
|
94
|
+
`)?s.slice(0,-1):s}let o=ii(e.metadata)??"Untitled",a=si(e.metadata,t),i=`<!DOCTYPE html>
|
|
92
95
|
<html lang="en">
|
|
93
96
|
<head>
|
|
94
97
|
<meta charset="utf-8">
|
|
95
|
-
<title>${
|
|
98
|
+
<title>${$e(o)}</title>
|
|
96
99
|
<style>
|
|
97
100
|
body { font-family: -apple-system, Segoe UI, Helvetica, Arial, sans-serif; max-width: 860px; margin: 2rem auto; padding: 0 1rem; color: #222; line-height: 1.55; }
|
|
98
101
|
h1, h2, h3, h4 { line-height: 1.2; }
|
|
@@ -114,21 +117,21 @@ figure.svg-figure svg { max-width: 100%; height: auto; }
|
|
|
114
117
|
</style>
|
|
115
118
|
</head>
|
|
116
119
|
<body>
|
|
117
|
-
${
|
|
120
|
+
${a}${r}
|
|
118
121
|
</body>
|
|
119
122
|
</html>
|
|
120
|
-
`;return t?.trailingNewline===!1&&
|
|
121
|
-
`)?
|
|
123
|
+
`;return t?.trailingNewline===!1&&i.endsWith(`
|
|
124
|
+
`)?i.slice(0,-1):i}};function ii(n){if(n){for(let e of n.entries)if((e.key==="title"||e.key==="name")&&e.value.kind==="StringScalar")return e.value.stringValue}}function si(n,e){if(!n||n.entries.length===0)return"";let t=e?.metadataKeys??n.entries.map(a=>a.key),r=new Map(n.entries.map(a=>[a.key,a])),o=[];for(let a of t){let i=r.get(a);if(!i)continue;let s=e?.metadataRenames.get(a)??a,c=Tt(i.value);c!==void 0&&o.push(` <dt>${$e(s)}</dt>
|
|
122
125
|
<dd>${c}</dd>`)}return o.length===0?"":`<dl class="metadata">
|
|
123
126
|
${o.join(`
|
|
124
127
|
`)}
|
|
125
128
|
</dl>
|
|
126
|
-
`}function
|
|
127
|
-
`)}function
|
|
129
|
+
`}function Tt(n){switch(n.kind){case"StringScalar":return $e(n.stringValue);case"IntegerScalar":return String(n.integerValue);case"StructuredList":{let e=[];for(let t of n.items){let r=Tt(t);r!==void 0&&e.push(`<code>${r}</code>`)}return e.join(", ")}case"StructuredMap":return;default:return}}function ci(n){let e=[];for(let t of n){let r=li(t);r&&e.push(r)}return e.join(`
|
|
130
|
+
`)}function li(n){switch(n.kind){case"Heading":{let e=Math.max(1,Math.min(6,n.level));return`<h${e}>${It(n.inlines)}</h${e}>`}case"Paragraph":return`<p>${It(n.inlines)}</p>`;case"RawBlock":return ui(n);default:return""}}function ui(n){let e=n.mediaType;return e&&pn(e,H.TEXT_MARKDOWN)?At(n.rawContent):e&&pn(e,H.TEXT_HTML)?n.rawContent:e&&pn(e,H.IMAGE_SVG_XML)?`<figure class="svg-figure">
|
|
128
131
|
${n.rawContent}
|
|
129
|
-
</figure>`:`<pre${e?` class="media-${
|
|
132
|
+
</figure>`:`<pre${e?` class="media-${di(e.name)}"`:""}><code>${$e(n.rawContent)}</code></pre>`}function It(n){let e=[];for(let t of n)t.kind==="Text"&&e.push($e(t.text));return e.join("")}function $e(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function di(n){return n.replace(/"/g,""").replace(/&/g,"&")}function fi(n,e){return n.publisher===e.publisher&&n.package_===e.package_&&n.name===e.name}var je=class{backendUri="kanonak.org/transformations/svg";render(e,t){for(let r of e.children)if(r.kind==="RawBlock"&&r.mediaType&&fi(r.mediaType,H.IMAGE_SVG_XML)){let o=r.rawContent;return t?.trailingNewline&&!o.endsWith(`
|
|
130
133
|
`)&&(o+=`
|
|
131
|
-
`),o}return'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'}};import{SubjectKanonak as Ra}from"@kanonak-protocol/sdk";var Ie=class{constructor(e,t,r){this.repository=e;this.parser=t;this.objectParser=r}repository;parser;objectParser;cache=new Map;async resolveSubject(e,t){let r=ke(t,e);if(r)return r;let o=e.version,a=o&&typeof o.major=="number"?`@${o.major}.${o.minor}.${o.patch}`:"",s=`${e.publisher}/${e.package_}${a}`,i=this.cache.get(s);if(!i){let l=await this.repository.getDocumentsByNamespaceAsync(e.publisher,e.package_);if(l.length===0)return;let u=o&&typeof o.major=="number"?l.find(p=>{let g=p.metadata?.namespace_?.version;return g&&g.major===o.major&&g.minor===o.minor&&g.patch===o.patch})??l[0]:l[0],f=new E(u,this.repository);i=await this.objectParser.parseKanonaks(f),this.cache.set(s,i)}let c=ke(i,e);if(c)return c;for(let l of i)if(l instanceof Ra&&l.name===e.name)return l}};import{EmbeddedKanonak as be,ReferenceKanonak as yt,SubjectKanonak as Ia,ListStatement as H,ReferenceStatement as sn,EmbeddedStatement as le,StringStatement as ht,NumberStatement as Ta,BooleanStatement as ja}from"@kanonak-protocol/sdk";var C=class extends Error{constructor(t,r){super(`${t} (at ${r})`);this.path=r}path},ft=16;function ue(n,e){let t=n.name,r={catalog:e,depth:0};if(P(n,d.InstanceTransformation))return xa(n,t,r);if(P(n,d.SetTransformation))return Ua(n,t,r);throw new C("Subject is not a recognized v3 transformation type \u2014 expected InstanceTransformation or SetTransformation",t)}function xa(n,e,t){return{kind:"instance",name:n.name,inputPattern:bt(n,e),rule:Te(n,d.rule,`${e}.rule`,t),artifactName:Te(n,d.artifactName,`${e}.artifactName`,t),outputs:wt(n,`${e}.outputs`),overrides:$t(n,`${e}.formatOverrides`,t)}}function Ua(n,e,t){let r=q(n,d.partitionBy);return{kind:"set",name:n.name,inputPattern:bt(n,e),rule:Te(n,d.rule,`${e}.rule`,t),artifactName:Te(n,d.artifactName,`${e}.artifactName`,t),outputs:wt(n,`${e}.outputs`),overrides:$t(n,`${e}.formatOverrides`,t),partitionBy:r}}function bt(n,e){let t=we(n,d.inputPattern);if(!t)throw new C("inputPattern is required",e);return Oa(t,`${e}.inputPattern`)}function Oa(n,e){let t=q(n,d.matchesClass);if(!t)throw new C("matchesClass is required",e);let r=[];for(let s of x(n,d.requires))if(s instanceof sn)r.push(an(s.object.subject));else if(s instanceof H)for(let i of s.object)i instanceof yt&&r.push(an(i.subject));let o=[],a=0;for(let s of x(n,d.sortBy))if(s instanceof H)for(let i of s.object)i instanceof be&&o.push(mt(i,`${e}.sortBy[${a++}]`));else s instanceof le&&o.push(mt(s.object,`${e}.sortBy[${a++}]`));return{matchesClass:t,requires:r,sortBy:o}}function mt(n,e){let t=q(n,d.byProperty);if(!t)throw new C("SortKey.byProperty is required",e);let r=q(n,d.order);if(!r)throw new C("SortKey.order is required",e);if(T(r,d.ascending))return{byProperty:t,order:"ascending"};if(T(r,d.descending))return{byProperty:t,order:"descending"};throw new C(`SortKey.order must reference tx.ascending or tx.descending; got ${r.publisher}/${r.package_}/${r.name}`,e)}function Te(n,e,t,r){let o=we(n,e);if(!o)throw new C("expression is required",t);return ce(o,t,r)}function ce(n,e,t){if(P(n,d.StringLiteral))return{kind:"string-literal",value:M(n,d.stringLiteral,e)};if(P(n,d.IntegerLiteral))return{kind:"integer-literal",value:kt(n,d.integerLiteral,e)};if(P(n,d.DecimalLiteral))return{kind:"decimal-literal",value:kt(n,d.decimalLiteral,e)};if(P(n,d.BooleanLiteral))return{kind:"boolean-literal",value:za(n,d.booleanLiteral,e)};if(P(n,d.VarRef))return{kind:"var-ref",varName:M(n,d.varName,e)};if(P(n,d.PropertyRead))return{kind:"property-read",source:D(n,d.readSource,`${e}.readSource`,t),readProp:X(n,d.readProp,e,"readProp")};if(P(n,d.Traverse))return{kind:"traverse",source:D(n,d.traverseSource,`${e}.traverseSource`,t),through:X(n,d.through,e,"through"),step:D(n,d.step,`${e}.step`,t)};if(P(n,d.BuildAstNode))return{kind:"build-ast-node",astClass:X(n,d.astClass,e,"astClass"),set:Va(n,`${e}.set`,t)};if(P(n,d.When))return{kind:"when",condition:D(n,d.condition,`${e}.condition`,t),thenBuild:D(n,d.thenBuild,`${e}.thenBuild`,t),elseBuild:Na(n,d.elseBuild,`${e}.elseBuild`,t)};if(P(n,d.Concat))return{kind:"concat",parts:La(n,d.parts,`${e}.parts`,t)};if(P(n,d.Fallback))return{kind:"fallback",primary:D(n,d.primary,`${e}.primary`,t),alternate:D(n,d.alternate,`${e}.alternate`,t)};if(P(n,d.UriName))return{kind:"uri-name",source:D(n,d.uriNameOf,`${e}.uriNameOf`,t)};if(P(n,d.UriPublisher))return{kind:"uri-publisher",source:D(n,d.uriPublisherOf,`${e}.uriPublisherOf`,t)};if(P(n,d.UriPackage))return{kind:"uri-package",source:D(n,d.uriPackageOf,`${e}.uriPackageOf`,t)};if(P(n,d.UriVersion))return{kind:"uri-version",source:D(n,d.uriVersionOf,`${e}.uriVersionOf`,t)};if(P(n,d.SubjectUri))return{kind:"subject-uri",source:D(n,d.subjectOf,`${e}.subjectOf`,t)};if(P(n,d.UriLiteral))return{kind:"uri-literal",refTo:X(n,d.refTo,e,"refTo")};if(P(n,d.DisplayLabel))return{kind:"display-label",labelTarget:X(n,d.labelTarget,e,"labelTarget"),labelSource:X(n,d.labelSource,e,"labelSource")};if(P(n,d.ResolveRef))return{kind:"resolve-ref",source:D(n,d.resolveSource,`${e}.resolveSource`,t)};if(P(n,d.Normalize))return{kind:"normalize",source:D(n,d.normSource,`${e}.normSource`,t),normKind:Fa(n,e)};if(P(n,d.IsSet))return{kind:"is-set",check:D(n,d.checkExpr,`${e}.checkExpr`,t)};if(P(n,d.CallFragment))return Ba(n,e,t);if(P(n,d.Join))return{kind:"join",source:D(n,d.source,`${e}.source`,t),separator:M(n,d.separator,e)};if(P(n,d.Count))return{kind:"count",source:D(n,d.source,`${e}.source`,t)};if(P(n,d.Sum))return{kind:"sum",source:D(n,d.source,`${e}.source`,t)};if(P(n,d.Min))return{kind:"min",source:D(n,d.source,`${e}.source`,t)};if(P(n,d.Max))return{kind:"max",source:D(n,d.source,`${e}.source`,t)};if(P(n,d.Average))return{kind:"average",source:D(n,d.source,`${e}.source`,t)};if(P(n,d.ForEach))return{kind:"for-each",source:D(n,d.source,`${e}.source`,t),loopVar:M(n,d.loopVar,e),emit:D(n,d.emit,`${e}.emit`,t)};if(P(n,d.ListMap))return{kind:"list-map",source:D(n,d.source,`${e}.source`,t),loopVar:M(n,d.loopVar,e),mapBody:D(n,d.mapBody,`${e}.mapBody`,t)};if(P(n,d.Filter))return{kind:"filter",source:D(n,d.source,`${e}.source`,t),loopVar:M(n,d.loopVar,e),predicate:D(n,d.predicate,`${e}.predicate`,t)};if(P(n,d.PartitionBy))return{kind:"partition-by",source:D(n,d.source,`${e}.source`,t),loopVar:M(n,d.loopVar,e),partitionKey:D(n,d.partitionKey,`${e}.partitionKey`,t)};if(P(n,d.DistinctBy))return{kind:"distinct-by",source:D(n,d.source,`${e}.source`,t),loopVar:M(n,d.loopVar,e),distinctKey:D(n,d.distinctKey,`${e}.distinctKey`,t)};throw new C("Expression is not of a recognized v3 type \u2014 embedded has no matching subclass of tx.Expression",e)}function D(n,e,t,r){let o=we(n,e);if(!o)throw new C("child expression is required",t);return ce(o,t,r)}function Na(n,e,t,r){let o=we(n,e);if(o)return ce(o,t,r)}function La(n,e,t,r){let o=[],a=0;for(let s of x(n,e))if(s instanceof H)for(let i of s.object)i instanceof be&&o.push(ce(i,`${t}[${a++}]`,r));else s instanceof le&&o.push(ce(s.object,`${t}[${a++}]`,r));return o}function Va(n,e,t){let r=[],o=0;for(let a of x(n,d.set))if(a instanceof H)for(let s of a.object)s instanceof be&&r.push(pt(s,`${e}[${o++}]`,t));else a instanceof le&&r.push(pt(a.object,`${e}[${o++}]`,t));return r}function pt(n,e,t){return{field:X(n,d.field,e,"field"),value:D(n,d.bindValue,`${e}.bindValue`,t)}}function Fa(n,e){let t=q(n,d.normKind);if(!t)throw new C("normKind is required",e);if(T(t,d.NORM_TRIM_END))return"trim-end";throw new C(`Unknown NormalizeKind: ${t.publisher}/${t.package_}/${t.name}`,e)}function Ba(n,e,t){if(t.depth>=ft)throw new C(`Fragment recursion exceeded MAX_FRAGMENT_DEPTH (${ft})`,e);let r=q(n,d.fragmentRef);if(!r)throw new C("fragmentRef is required",e);let o=Ma(t.catalog,r);if(!o)throw new C(`ExpressionFragment not found: ${r.publisher}/${r.package_}/${r.name}`,e);let a=we(o,d.body);if(!a)throw new C(`ExpressionFragment ${r.name} has no body`,e);return{kind:"call-fragment",body:ce(a,`${e}.fragment(${r.name})`,{catalog:t.catalog,depth:t.depth+1})}}function Ma(n,e){for(let t of n)if(!(!(t instanceof Ia)||t.name!==e.name||!(t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))&&P(t,d.ExpressionFragment))return t}function wt(n,e){let t=new Set;for(let r of x(n,d.outputs))if(r instanceof sn)t.add(r.object.subject.name);else if(r instanceof H)for(let o of r.object)o instanceof yt&&t.add(o.subject.name);if(t.size===0)throw new C("outputs is required (at least one OutputFormat)",e);return t}function $t(n,e,t){let r=new Map,o=0;for(let a of x(n,d.formatOverrides))if(a instanceof H){for(let s of a.object)if(s instanceof be){let[i,c]=gt(s,`${e}[${o++}]`);r.set(i,c)}}else if(a instanceof le){let[s,i]=gt(a.object,`${e}[${o++}]`);r.set(s,i)}return r}function gt(n,e){let t=q(n,d.formatTarget);if(!t)throw new C("formatTarget is required",e);let r=[];for(let s of x(n,d.metadataKeys))if(s instanceof ht)r.push(s.object);else if(s instanceof H)for(let i of s.object){let c=i.value;typeof c=="string"&&r.push(c)}let o=new Map;for(let s of x(n,d.metadataRenames))if(s instanceof H){for(let i of s.object)if(i instanceof be){let c=he(i,d.fromKey),l=he(i,d.toKey);c&&l&&o.set(c,l)}}else if(s instanceof le){let i=s.object,c=he(i,d.fromKey),l=he(i,d.toKey);c&&l&&o.set(c,l)}let a=St(n,d.trailingNewline);return[t.name,{metadataKeys:r.length>0?r:void 0,metadataRenames:o,trailingNewline:a}]}function Ha(n){return n.predicate?.subject}function x(n,e){let t=[];for(let r of n.statement){let o=Ha(r);o&&T(o,e)&&t.push(r)}return t}function we(n,e){for(let t of x(n,e))if(t instanceof le)return t.object}function q(n,e){for(let t of x(n,e))if(t instanceof sn)return an(t.object.subject)}function he(n,e){for(let t of x(n,e))if(t instanceof ht)return t.object}function qa(n,e){for(let t of x(n,e))if(t instanceof Ta)return t.object}function St(n,e){for(let t of x(n,e))if(t instanceof ja)return t.object}function M(n,e,t){let r=he(n,e);if(r===void 0)throw new C(`${e.name} (string) is required`,t);return r}function kt(n,e,t){let r=qa(n,e);if(r===void 0)throw new C(`${e.name} (number) is required`,t);return r}function za(n,e,t){let r=St(n,e);if(r===void 0)throw new C(`${e.name} (boolean) is required`,t);return r}function X(n,e,t,r){let o=q(n,e);if(!o)throw new C(`${r} (URI reference) is required`,t);return o}function an(n){return{publisher:n.publisher,package_:n.package_,name:n.name}}import{DefinedKanonak as xe,EmbeddedKanonak as Wa,ReferenceKanonak as J,SubjectKanonak as un,StringStatement as Ga,NumberStatement as Xa,BooleanStatement as Ja,ReferenceStatement as Dt,EmbeddedStatement as Ya,ListStatement as Et}from"@kanonak-protocol/sdk";var z=class extends Error{},je=class{constructor(e,t){this.resolver=e;this.catalog=t}resolver;catalog;async evaluate(e,t){switch(e.kind){case"string-literal":return e.value;case"integer-literal":return e.value;case"decimal-literal":return e.value;case"boolean-literal":return e.value;case"uri-literal":return{...e.refTo};case"var-ref":{if(!t.has(e.varName))throw new z(`Unbound variable "${e.varName}"`);return t.get(e.varName)}case"concat":{let r=[];for(let o of e.parts){let a=await this.evaluate(o,t);if(a!=null)if(Array.isArray(a))for(let s of a)r.push(s);else r.push(a)}return r}case"fallback":{let r=await this.evaluate(e.primary,t);return Pt(r)?r:this.evaluate(e.alternate,t)}case"when":return await this.evaluate(e.condition,t)===!0?this.evaluate(e.thenBuild,t):e.elseBuild?this.evaluate(e.elseBuild,t):void 0;case"is-set":{let r=await this.evaluate(e.check,t);return Pt(r)}case"property-read":{let r=await this.evaluate(e.source,t);return vt(r,e.readProp)}case"traverse":{let r=await this.evaluate(e.source,t);if(!(r instanceof xe))return;let o=Qa(r,e.through),a=[];for(let s of o){let i=await this.resolver.resolveSubject(s,this.catalog);if(!i)continue;let c=new Map(t);c.set("input",i);let l=await this.evaluate(e.step,c);l!=null&&a.push(cn(l))}return a.join("")}case"uri-name":{let r=await this.evaluate(e.source,t);return $e(r)?r.name:r instanceof J?r.subject.name:r instanceof un?r.name:r instanceof Wa?r.name??"":void 0}case"uri-publisher":{let r=await this.evaluate(e.source,t);return ln(r)?.publisher}case"uri-package":{let r=await this.evaluate(e.source,t);return ln(r)?.package_}case"uri-version":{let r=await this.evaluate(e.source,t);return ln(r)?.version}case"subject-uri":{let r=await this.evaluate(e.source,t);if(r instanceof un){let o=r.namespace??"",a=r.name??"";return!o||!a?void 0:`${o}/${a}`}if(r instanceof J){let o=r.subject,a=o.version;return a&&typeof a.major=="number"?`${o.publisher}/${o.package_}@${a.major}.${a.minor}.${a.patch}/${o.name}`:`${o.publisher}/${o.package_}/${o.name}`}return}case"display-label":{let r=await this.resolver.resolveSubject({...e.labelTarget},this.catalog);return r?vt(r,e.labelSource):void 0}case"resolve-ref":{let r=await this.evaluate(e.source,t);return r instanceof J?await this.resolver.resolveSubject(r.subject,this.catalog):$e(r)?await this.resolver.resolveSubject(r,this.catalog):void 0}case"normalize":{let r=await this.evaluate(e.source,t),o=r==null?"":cn(r);return e.normKind==="trim-end"?o.replace(/[\s\r\n]+$/u,""):o}case"build-ast-node":{let r={kind:e.astClass.name};for(let o of e.set){let a=await this.evaluate(o.value,t);if(a==null||Array.isArray(a)&&a.length===0)continue;let s=o.field.name;Array.isArray(a)&&ns.has(s)&&a.every(i=>ts(i))&&(a=a.map(i=>String(i)).join("")),r[s]=a}return r}case"call-fragment":return this.evaluate(e.body,t);case"join":return(await this.evaluateList(e.source,t)).map(o=>o==null?"":cn(o)).join(e.separator);case"count":return(await this.evaluateList(e.source,t)).length;case"sum":{let r=await this.evaluateList(e.source,t),o=0;for(let a of r)o+=de(a,"Sum");return o}case"min":{let r=await this.evaluateList(e.source,t);if(r.length===0)throw new z("Min on an empty list is undefined; guard with IsSet");let o=de(r[0],"Min");for(let a=1;a<r.length;a++){let s=de(r[a],"Min");s<o&&(o=s)}return o}case"max":{let r=await this.evaluateList(e.source,t);if(r.length===0)throw new z("Max on an empty list is undefined; guard with IsSet");let o=de(r[0],"Max");for(let a=1;a<r.length;a++){let s=de(r[a],"Max");s>o&&(o=s)}return o}case"average":{let r=await this.evaluateList(e.source,t);if(r.length===0)throw new z("Average on an empty list is undefined; guard with IsSet");let o=0;for(let a of r)o+=de(a,"Average");return o/r.length}case"for-each":{let r=await this.evaluateList(e.source,t),o=[];for(let a of r){let s=new Map(t);s.set(e.loopVar,a);let i=await this.evaluate(e.emit,s);if(i!=null)if(Array.isArray(i))for(let c of i)o.push(c);else o.push(i)}return o}case"list-map":{let r=await this.evaluateList(e.source,t),o=[];for(let a of r){let s=new Map(t);s.set(e.loopVar,a),o.push(await this.evaluate(e.mapBody,s))}return o}case"filter":{let r=await this.evaluateList(e.source,t),o=[];for(let a of r){let s=new Map(t);s.set(e.loopVar,a),await this.evaluate(e.predicate,s)===!0&&o.push(a)}return o}case"partition-by":{let r=await this.evaluateList(e.source,t),o=new Map,a=[];for(let s of r){let i=new Map(t);i.set(e.loopVar,s);let c=await this.evaluate(e.partitionKey,i),l=Kt(c),u=o.get(l);u||(u={kind:"Partition",key:c,members:[]},o.set(l,u),a.push(l)),u.members.push(s)}return a.map(s=>o.get(s))}case"distinct-by":{let r=await this.evaluateList(e.source,t),o=new Set,a=[];for(let s of r){let i=new Map(t);i.set(e.loopVar,s);let c=await this.evaluate(e.distinctKey,i),l=Kt(c);o.has(l)||(o.add(l),a.push(s))}return a}default:{let r=e;throw new z("Unknown expression kind")}}}async evaluateList(e,t){let r=await this.evaluate(e,t);return r==null?[]:Array.isArray(r)?r:[r]}};function vt(n,e){if(n instanceof xe)return Za(n,e);if(es(n))return T(e,d.key)?n.key:T(e,d.members)?n.members:void 0}function Za(n,e){for(let t of n.statement){let r=Ct(t);if(!(!r||!T(r,e))&&(t instanceof Ga||t instanceof Xa||t instanceof Ja||t instanceof Dt||t instanceof Ya||t instanceof Et))return t.object}}function Qa(n,e){let t=[];for(let r of n.statement){let o=Ct(r);if(!(!o||!T(o,e))){if(r instanceof Dt)t.push(r.object.subject);else if(r instanceof Et)for(let a of r.object)a instanceof J&&t.push(a.subject)}}return t}function Ct(n){return n.predicate?.subject}function cn(n){return n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):n instanceof xe?n.name??"":n instanceof J?n.subject.name:$e(n)?n.name:""}function Pt(n){return n==null?!1:typeof n=="string"||Array.isArray(n)?n.length>0:typeof n=="boolean"?n===!0:!0}function $e(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}function es(n){return typeof n=="object"&&n!==null&&n.kind==="Partition"&&Array.isArray(n.members)}function de(n,e){if(typeof n=="number"&&Number.isFinite(n))return n;throw new z(`${e} requires numeric elements; got ${rs(n)}`)}function ln(n){if(n instanceof un){let e=n.namespace??"",t=e.indexOf("/"),r=e.indexOf("@",t+1);return t<0||r<0?void 0:{publisher:e.substring(0,t),package_:e.substring(t+1,r),version:e.substring(r+1),name:n.name??""}}if(n instanceof J){let e=n.subject,t=e.version;return{publisher:e.publisher,package_:e.package_,version:t&&typeof t.major=="number"?`${t.major}.${t.minor}.${t.patch}`:"",name:e.name}}if($e(n))return{publisher:n.publisher,package_:n.package_,version:"",name:n.name}}var ns=new Set(["stringValue","text","rawContent","key"]);function ts(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"}function rs(n){return n===void 0?"undefined":n===null?"null":Array.isArray(n)?`array(${n.length})`:typeof n}function Kt(n){if(n===void 0)return"\0undef";if(n===null)return"\0null";if(typeof n=="string")return`s:${n}`;if(typeof n=="number")return`n:${n}`;if(typeof n=="boolean")return`b:${n}`;if(n instanceof J){let e=n.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(n instanceof xe){let e=n.name??"";return`k:${n.namespace??""}/${e}`}return $e(n)?`u:${n.publisher}/${n.package_}/${n.name}`:`o:${JSON.stringify(n)}`}var Ue={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"}},W=class extends Error{},G=class{backends=new Map;constructor(){this.register(new Ee),this.register(new Ce),this.register(new Ae),this.register(new _e),this.register(new Re)}register(e){this.backends.set(e.backendUri,e)}async run(e){let t=e.transformationKanonaks??e.allKanonaks,r=ue(e.transformation,t);if(!r.outputs.has(e.outputFormat))throw new W(`Transformation "${r.name}" does not declare output format "${e.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(e.outputFormat);if(!o)throw new W(`No backend registered for OutputFormat "${e.outputFormat}".`);let a=new Ie(e.repository,e.parser,e.objectParser),s=new je(a,e.allKanonaks);return r.kind==="instance"?this.runInstance(r,e,o,s):this.runSet(r,e,o,s)}async runInstance(e,t,r,o){let a=At(t.instances,e.inputPattern.requires),s=_t(a,e.inputPattern.sortBy),i=[];for(let c of s){let l=new Map;l.set("input",c);let u=await o.evaluate(e.rule,l);dn(u,e.name,`input "${c.name}"`);let f=fn(await o.evaluate(e.artifactName,l),e.name,`input "${c.name}"`),p=e.overrides.get(t.outputFormat),g=r.render(u,p);i.push({fileName:f,format:t.outputFormat,content:g,source:{kind:"instance",sourceName:c.name}})}return i}async runSet(e,t,r,o){let a=At(t.instances,e.inputPattern.requires),s=_t(a,e.inputPattern.sortBy);return e.partitionBy?this.runSetWithPartition(e,s,t,r,o):this.runSetSingle(e,s,t,r,o)}async runSetSingle(e,t,r,o,a){let s=new Map;s.set("inputs",t);let i=await a.evaluate(e.rule,s);dn(i,e.name,"set");let c=fn(await a.evaluate(e.artifactName,s),e.name,"set"),l=e.overrides.get(r.outputFormat),u=o.render(i,l);return[{fileName:c,format:r.outputFormat,content:u,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(e,t,r,o,a){let s=e.partitionBy,i=new Map,c=[];for(let u of t){let f=ss(u,s);if(f==null)continue;let p=is(f),g=i.get(p);g||(g={keyValue:f,keyDisplay:cs(f),members:[]},i.set(p,g),c.push(p)),g.members.push(u)}let l=[];for(let u of c){let f=i.get(u),p=new Map;p.set("inputs",f.members),p.set("key",f.keyValue);let g=await a.evaluate(e.rule,p);dn(g,e.name,`partition "${f.keyDisplay}"`);let b=fn(await a.evaluate(e.artifactName,p),e.name,`partition "${f.keyDisplay}"`),k=e.overrides.get(r.outputFormat),y=o.render(g,k);l.push({fileName:b,format:r.outputFormat,content:y,source:{kind:"set",memberCount:f.members.length,partitionKey:f.keyDisplay}})}return l}findBackend(e){let t=Ue[e];if(t)return this.backends.get(t.formatUri)}};function At(n,e){return e.length===0?n:n.filter(t=>{for(let r of e)if(!as(t,r))return!1;return!0})}function _t(n,e){if(e.length===0)return n;let t=[...n];return t.sort((r,o)=>{for(let a of e){let s=Rt(r,a.byProperty),i=Rt(o,a.byProperty),c=os(s,i,a.order);if(c!==0)return c}return 0}),t}function Rt(n,e){for(let t of n.statement){let r=mn(t);if(!(!r||!T(r,e))){if(t instanceof jt||t instanceof xt||t instanceof Ut)return t.object;if(t instanceof Nt)throw new W(`Sort property "${e.name}" on instance "${n.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof Ot)throw new W(`Sort property "${e.name}" on instance "${n.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function os(n,e,t){if(n===void 0&&e===void 0)return 0;if(n===void 0)return t==="ascending"?1:-1;if(e===void 0)return t==="ascending"?-1:1;let r;return typeof n=="number"&&typeof e=="number"?r=n-e:r=String(n).localeCompare(String(e)),t==="ascending"?r:-r}function as(n,e){for(let t of n.statement){let r=mn(t);if(!r||!T(r,e))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function ss(n,e){for(let t of n.statement){let r=mn(t);if(!(!r||!T(r,e))&&(t instanceof jt||t instanceof xt||t instanceof Ut||t instanceof Ot||t instanceof Nt))return t.object}}function mn(n){return n.predicate?.subject}function is(n){if(n===void 0)return" undef";if(n===null)return" null";if(typeof n=="string")return`s:${n}`;if(typeof n=="number")return`n:${n}`;if(typeof n=="boolean")return`b:${n}`;if(n instanceof Tt){let e=n.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(n instanceof It){let e=n.name??"";return`k:${n.namespace??""}/${e}`}if(typeof n=="object"&&n!==null&&typeof n.name=="string"&&typeof n.publisher=="string"){let e=n;return`u:${e.publisher}/${e.package_}/${e.name}`}return`o:${JSON.stringify(n)}`}function cs(n){return n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):n instanceof Tt?n.subject.name:n instanceof It?n.name??"":typeof n=="object"&&n!==null&&typeof n.name=="string"?n.name:""}function dn(n,e,t){if(typeof n!="object"||n===null||n.kind!=="Document")throw new W(`Transformation "${e}" rule did not yield a Document for ${t}. Got: ${Lt(n)}`)}function fn(n,e,t){if(typeof n=="string")return n;if(Array.isArray(n)&&n.every(ls))return n.map(r=>String(r)).join("");throw new W(`Transformation "${e}" artifactName did not yield a string for ${t}. Got: ${Lt(n)}`)}function ls(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"}function Lt(n){if(n===void 0)return"undefined";if(n===null)return"null";if(Array.isArray(n))return`array(${n.length})`;if(typeof n=="object"){let e=n.kind;return e?`object(kind=${e})`:"object"}return typeof n}function pn(n){return[...A(n,d.InstanceTransformation),...A(n,d.SetTransformation)]}function Ht(){let n=new Se("transform").description("Run ontology-driven transformations against Kanonak packages. Transformations are declarative YAML rules (instances of `kanonak.org/transformations/Transformation`) that convert ontology instances into output files. The runner produces one or more Artifacts per matched input; format backends serialize them to Markdown, HTML, SVG, TOML, JSON, or (with post-processing) PDF.").addHelpText("after",`
|
|
134
|
+
`),o}return'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'}};import{SubjectKanonak as mi}from"@kanonak-protocol/sdk";var Ue=class{constructor(e,t,r){this.repository=e;this.parser=t;this.objectParser=r}repository;parser;objectParser;cache=new Map;async resolveSubject(e,t){let r=we(t,e);if(r)return r;let o=e.version,a=o&&typeof o.major=="number"?`@${o.major}.${o.minor}.${o.patch}`:"",i=`${e.publisher}/${e.package_}${a}`,s=this.cache.get(i);if(!s){let l=await this.repository.getDocumentsByNamespaceAsync(e.publisher,e.package_);if(l.length===0)return;let d=o&&typeof o.major=="number"?l.find(p=>{let k=p.metadata?.namespace_?.version;return k&&k.major===o.major&&k.minor===o.minor&&k.patch===o.patch})??l[0]:l[0],f=new E(d,this.repository);s=await this.objectParser.parseKanonaks(f),this.cache.set(i,s)}let c=we(s,e);if(c)return c;for(let l of s)if(l instanceof mi&&l.name===e.name)return l}};import{EmbeddedKanonak as Se,ReferenceKanonak as Ft,SubjectKanonak as pi,ListStatement as Z,ReferenceStatement as hn,EmbeddedStatement as pe,StringStatement as Vt,NumberStatement as gi,BooleanStatement as ki}from"@kanonak-protocol/sdk";var A=class extends Error{constructor(t,r){super(`${t} (at ${r})`);this.path=r}path},jt=16;function ge(n,e){let t=n.name,r={catalog:e,depth:0};if(v(n,u.InstanceTransformation))return hi(n,t,r);if(v(n,u.SetTransformation))return yi(n,t,r);throw new A("Subject is not a recognized v3 transformation type \u2014 expected InstanceTransformation or SetTransformation",t)}function hi(n,e,t){return{kind:"instance",name:n.name,inputPattern:Mt(n,e),rule:Oe(n,u.rule,`${e}.rule`,t),artifactName:Oe(n,u.artifactName,`${e}.artifactName`,t),outputs:Bt(n,`${e}.outputs`),overrides:Ht(n,`${e}.formatOverrides`,t)}}function yi(n,e,t){let r=Q(n,u.partitionBy);return{kind:"set",name:n.name,inputPattern:Mt(n,e),rule:Oe(n,u.rule,`${e}.rule`,t),artifactName:Oe(n,u.artifactName,`${e}.artifactName`,t),outputs:Bt(n,`${e}.outputs`),overrides:Ht(n,`${e}.formatOverrides`,t),partitionBy:r}}function Mt(n,e){let t=ve(n,u.inputPattern);if(!t)throw new A("inputPattern is required",e);return bi(t,`${e}.inputPattern`)}function bi(n,e){let t=Q(n,u.matchesClass);if(!t)throw new A("matchesClass is required",e);let r=[];for(let i of N(n,u.requires))if(i instanceof hn)r.push(kn(i.object.subject));else if(i instanceof Z)for(let s of i.object)s instanceof Ft&&r.push(kn(s.subject));let o=[],a=0;for(let i of N(n,u.sortBy))if(i instanceof Z)for(let s of i.object)s instanceof Se&&o.push(Ut(s,`${e}.sortBy[${a++}]`));else i instanceof pe&&o.push(Ut(i.object,`${e}.sortBy[${a++}]`));return{matchesClass:t,requires:r,sortBy:o}}function Ut(n,e){let t=Q(n,u.byProperty);if(!t)throw new A("SortKey.byProperty is required",e);let r=Q(n,u.order);if(!r)throw new A("SortKey.order is required",e);if(U(r,u.ascending))return{byProperty:t,order:"ascending"};if(U(r,u.descending))return{byProperty:t,order:"descending"};throw new A(`SortKey.order must reference tx.ascending or tx.descending; got ${r.publisher}/${r.package_}/${r.name}`,e)}function Oe(n,e,t,r){let o=ve(n,e);if(!o)throw new A("expression is required",t);return me(o,t,r)}function me(n,e,t){if(v(n,u.StringLiteral))return{kind:"string-literal",value:Y(n,u.stringLiteral,e)};if(v(n,u.IntegerLiteral))return{kind:"integer-literal",value:Lt(n,u.integerLiteral,e)};if(v(n,u.DecimalLiteral))return{kind:"decimal-literal",value:Lt(n,u.decimalLiteral,e)};if(v(n,u.BooleanLiteral))return{kind:"boolean-literal",value:Ai(n,u.booleanLiteral,e)};if(v(n,u.VarRef))return{kind:"var-ref",varName:Y(n,u.varName,e)};if(v(n,u.PropertyRead))return{kind:"property-read",source:P(n,u.readSource,`${e}.readSource`,t),readProp:ne(n,u.readProp,e,"readProp")};if(v(n,u.Traverse))return{kind:"traverse",source:P(n,u.traverseSource,`${e}.traverseSource`,t),through:ne(n,u.through,e,"through"),step:P(n,u.step,`${e}.step`,t)};if(v(n,u.BuildAstNode))return{kind:"build-ast-node",astClass:ne(n,u.astClass,e,"astClass"),set:Si(n,`${e}.set`,t)};if(v(n,u.When))return{kind:"when",condition:P(n,u.condition,`${e}.condition`,t),thenBuild:P(n,u.thenBuild,`${e}.thenBuild`,t),elseBuild:wi(n,u.elseBuild,`${e}.elseBuild`,t)};if(v(n,u.Concat))return{kind:"concat",parts:$i(n,u.parts,`${e}.parts`,t)};if(v(n,u.Fallback))return{kind:"fallback",primary:P(n,u.primary,`${e}.primary`,t),alternate:P(n,u.alternate,`${e}.alternate`,t)};if(v(n,u.UriName))return{kind:"uri-name",source:P(n,u.uriNameOf,`${e}.uriNameOf`,t)};if(v(n,u.UriPublisher))return{kind:"uri-publisher",source:P(n,u.uriPublisherOf,`${e}.uriPublisherOf`,t)};if(v(n,u.UriPackage))return{kind:"uri-package",source:P(n,u.uriPackageOf,`${e}.uriPackageOf`,t)};if(v(n,u.UriVersion))return{kind:"uri-version",source:P(n,u.uriVersionOf,`${e}.uriVersionOf`,t)};if(v(n,u.SubjectUri))return{kind:"subject-uri",source:P(n,u.subjectOf,`${e}.subjectOf`,t)};if(v(n,u.UriLiteral))return{kind:"uri-literal",refTo:ne(n,u.refTo,e,"refTo")};if(v(n,u.DisplayLabel))return{kind:"display-label",labelTarget:ne(n,u.labelTarget,e,"labelTarget"),labelSource:ne(n,u.labelSource,e,"labelSource")};if(v(n,u.ResolveRef))return{kind:"resolve-ref",source:P(n,u.resolveSource,`${e}.resolveSource`,t)};if(v(n,u.Normalize))return{kind:"normalize",source:P(n,u.normSource,`${e}.normSource`,t),normKind:vi(n,e)};if(v(n,u.IsSet))return{kind:"is-set",check:P(n,u.checkExpr,`${e}.checkExpr`,t)};if(v(n,u.CallFragment))return Ki(n,e,t);if(v(n,u.Join))return{kind:"join",source:P(n,u.source,`${e}.source`,t),separator:Y(n,u.separator,e)};if(v(n,u.Count))return{kind:"count",source:P(n,u.source,`${e}.source`,t)};if(v(n,u.Sum))return{kind:"sum",source:P(n,u.source,`${e}.source`,t)};if(v(n,u.Min))return{kind:"min",source:P(n,u.source,`${e}.source`,t)};if(v(n,u.Max))return{kind:"max",source:P(n,u.source,`${e}.source`,t)};if(v(n,u.Average))return{kind:"average",source:P(n,u.source,`${e}.source`,t)};if(v(n,u.ForEach))return{kind:"for-each",source:P(n,u.source,`${e}.source`,t),loopVar:Y(n,u.loopVar,e),emit:P(n,u.emit,`${e}.emit`,t)};if(v(n,u.ListMap))return{kind:"list-map",source:P(n,u.source,`${e}.source`,t),loopVar:Y(n,u.loopVar,e),mapBody:P(n,u.mapBody,`${e}.mapBody`,t)};if(v(n,u.Filter))return{kind:"filter",source:P(n,u.source,`${e}.source`,t),loopVar:Y(n,u.loopVar,e),predicate:P(n,u.predicate,`${e}.predicate`,t)};if(v(n,u.PartitionBy))return{kind:"partition-by",source:P(n,u.source,`${e}.source`,t),loopVar:Y(n,u.loopVar,e),partitionKey:P(n,u.partitionKey,`${e}.partitionKey`,t)};if(v(n,u.DistinctBy))return{kind:"distinct-by",source:P(n,u.source,`${e}.source`,t),loopVar:Y(n,u.loopVar,e),distinctKey:P(n,u.distinctKey,`${e}.distinctKey`,t)};if(v(n,u.AllStatements))return{kind:"all-statements",source:P(n,u.statementsOf,`${e}.statementsOf`,t)};if(v(n,u.StatementPredicate))return{kind:"statement-predicate",source:P(n,u.predicateOf,`${e}.predicateOf`,t)};if(v(n,u.StatementValue))return{kind:"statement-value",source:P(n,u.valueOf,`${e}.valueOf`,t)};if(v(n,u.DateFormat))return{kind:"date-format",source:P(n,u.dateSource,`${e}.dateSource`,t),format:Pi(n,e)};if(v(n,u.Add))return{kind:"add",left:P(n,u.arithLeft,`${e}.arithLeft`,t),right:P(n,u.arithRight,`${e}.arithRight`,t)};if(v(n,u.Subtract))return{kind:"subtract",left:P(n,u.arithLeft,`${e}.arithLeft`,t),right:P(n,u.arithRight,`${e}.arithRight`,t)};if(v(n,u.Multiply))return{kind:"multiply",left:P(n,u.arithLeft,`${e}.arithLeft`,t),right:P(n,u.arithRight,`${e}.arithRight`,t)};if(v(n,u.Divide))return{kind:"divide",left:P(n,u.arithLeft,`${e}.arithLeft`,t),right:P(n,u.arithRight,`${e}.arithRight`,t)};if(v(n,u.Reverse))return{kind:"reverse",source:P(n,u.source,`${e}.source`,t)};throw new A("Expression is not of a recognized v3 type \u2014 embedded has no matching subclass of tx.Expression",e)}function P(n,e,t,r){let o=ve(n,e);if(!o)throw new A("child expression is required",t);return me(o,t,r)}function wi(n,e,t,r){let o=ve(n,e);if(o)return me(o,t,r)}function $i(n,e,t,r){let o=[],a=0;for(let i of N(n,e))if(i instanceof Z)for(let s of i.object)s instanceof Se&&o.push(me(s,`${t}[${a++}]`,r));else i instanceof pe&&o.push(me(i.object,`${t}[${a++}]`,r));return o}function Si(n,e,t){let r=[],o=0;for(let a of N(n,u.set))if(a instanceof Z)for(let i of a.object)i instanceof Se&&r.push(Ot(i,`${e}[${o++}]`,t));else a instanceof pe&&r.push(Ot(a.object,`${e}[${o++}]`,t));return r}function Ot(n,e,t){return{field:ne(n,u.field,e,"field"),value:P(n,u.bindValue,`${e}.bindValue`,t)}}function vi(n,e){let t=Q(n,u.normKind);if(!t)throw new A("normKind is required",e);if(U(t,u.NORM_TRIM_END))return"trim-end";throw new A(`Unknown NormalizeKind: ${t.publisher}/${t.package_}/${t.name}`,e)}var xt=new Set(["iso-date","iso-datetime","short-date","long-date","year","month-year"]);function Pi(n,e){let t=fe(n,u.dateFormat);if(!t)throw new A("dateFormat is required",e);if(!xt.has(t))throw new A(`Unknown dateFormat "${t}"; supported: ${[...xt].join(", ")}`,e);return t}function Ki(n,e,t){if(t.depth>=jt)throw new A(`Fragment recursion exceeded MAX_FRAGMENT_DEPTH (${jt})`,e);let r=Q(n,u.fragmentRef);if(!r)throw new A("fragmentRef is required",e);let o=Di(t.catalog,r);if(!o)throw new A(`ExpressionFragment not found: ${r.publisher}/${r.package_}/${r.name}`,e);let a=ve(o,u.body);if(!a)throw new A(`ExpressionFragment ${r.name} has no body`,e);return{kind:"call-fragment",body:me(a,`${e}.fragment(${r.name})`,{catalog:t.catalog,depth:t.depth+1})}}function Di(n,e){for(let t of n)if(!(!(t instanceof pi)||t.name!==e.name||!(t.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))&&v(t,u.ExpressionFragment))return t}function Bt(n,e){let t=new Set;for(let r of N(n,u.outputs))if(r instanceof hn)t.add(r.object.subject.name);else if(r instanceof Z)for(let o of r.object)o instanceof Ft&&t.add(o.subject.name);if(t.size===0)throw new A("outputs is required (at least one OutputFormat)",e);return t}function Ht(n,e,t){let r=new Map,o=0;for(let a of N(n,u.formatOverrides))if(a instanceof Z){for(let i of a.object)if(i instanceof Se){let[s,c]=Nt(i,`${e}[${o++}]`);r.set(s,c)}}else if(a instanceof pe){let[i,s]=Nt(a.object,`${e}[${o++}]`);r.set(i,s)}return r}function Nt(n,e){let t=Q(n,u.formatTarget);if(!t)throw new A("formatTarget is required",e);let r=[];for(let s of N(n,u.metadataKeys))if(s instanceof Vt)r.push(s.object);else if(s instanceof Z)for(let c of s.object){let l=c.value;typeof l=="string"&&r.push(l)}let o=new Map;for(let s of N(n,u.metadataRenames))if(s instanceof Z){for(let c of s.object)if(c instanceof Se){let l=fe(c,u.fromKey),d=fe(c,u.toKey);l&&d&&o.set(l,d)}}else if(s instanceof pe){let c=s.object,l=fe(c,u.fromKey),d=fe(c,u.toKey);l&&d&&o.set(l,d)}let a=gn(n,u.trailingNewline),i=gn(n,u.omitWrapper);return[t.name,{metadataKeys:r.length>0?r:void 0,metadataRenames:o,trailingNewline:a,omitWrapper:i}]}function Ei(n){return n.predicate?.subject}function N(n,e){let t=[];for(let r of n.statement){let o=Ei(r);o&&U(o,e)&&t.push(r)}return t}function ve(n,e){for(let t of N(n,e))if(t instanceof pe)return t.object}function Q(n,e){for(let t of N(n,e))if(t instanceof hn)return kn(t.object.subject)}function fe(n,e){for(let t of N(n,e))if(t instanceof Vt)return t.object}function Ci(n,e){for(let t of N(n,e))if(t instanceof gi)return t.object}function gn(n,e){for(let t of N(n,e))if(t instanceof ki)return t.object}function Y(n,e,t){let r=fe(n,e);if(r===void 0)throw new A(`${e.name} (string) is required`,t);return r}function Lt(n,e,t){let r=Ci(n,e);if(r===void 0)throw new A(`${e.name} (number) is required`,t);return r}function Ai(n,e,t){let r=gn(n,e);if(r===void 0)throw new A(`${e.name} (boolean) is required`,t);return r}function ne(n,e,t,r){let o=Q(n,e);if(!o)throw new A(`${r} (URI reference) is required`,t);return o}function kn(n){return{publisher:n.publisher,package_:n.package_,name:n.name}}import{DefinedKanonak as Pe,EmbeddedKanonak as Ri,ReferenceKanonak as J,SubjectKanonak as bn,StringStatement as wn,NumberStatement as $n,BooleanStatement as Sn,ReferenceStatement as Le,EmbeddedStatement as vn,ListStatement as Fe}from"@kanonak-protocol/sdk";var G=class extends Error{},Ne=class{constructor(e,t){this.resolver=e;this.catalog=t}resolver;catalog;async evaluate(e,t){switch(e.kind){case"string-literal":return e.value;case"integer-literal":return e.value;case"decimal-literal":return e.value;case"boolean-literal":return e.value;case"uri-literal":return{...e.refTo};case"var-ref":{if(!t.has(e.varName))throw new G(`Unbound variable "${e.varName}"`);return t.get(e.varName)}case"concat":{let r=[];for(let o of e.parts){let a=await this.evaluate(o,t);if(a!=null)if(Array.isArray(a))for(let i of a)r.push(i);else r.push(a)}return r}case"fallback":{let r=await this.evaluate(e.primary,t);return qt(r)?r:this.evaluate(e.alternate,t)}case"when":return await this.evaluate(e.condition,t)===!0?this.evaluate(e.thenBuild,t):e.elseBuild?this.evaluate(e.elseBuild,t):void 0;case"is-set":{let r=await this.evaluate(e.check,t);return qt(r)}case"property-read":{let r=await this.evaluate(e.source,t);return zt(r,e.readProp)}case"traverse":{let r=await this.evaluate(e.source,t);if(!(r instanceof Pe))return;let o=Ii(r,e.through),a=[];for(let i of o){let s=await this.resolver.resolveSubject(i,this.catalog);if(!s)continue;let c=new Map(t);c.set("input",s);let l=await this.evaluate(e.step,c);l!=null&&a.push(xe(l))}return a.join("")}case"uri-name":{let r=await this.evaluate(e.source,t);return Ke(r)?r.name:r instanceof J?r.subject.name:r instanceof bn?r.name:r instanceof Ri?r.name??"":void 0}case"uri-publisher":{let r=await this.evaluate(e.source,t);return yn(r)?.publisher}case"uri-package":{let r=await this.evaluate(e.source,t);return yn(r)?.package_}case"uri-version":{let r=await this.evaluate(e.source,t);return yn(r)?.version}case"subject-uri":{let r=await this.evaluate(e.source,t);if(r instanceof bn){let o=r.namespace??"",a=r.name??"";return!o||!a?void 0:`${o}/${a}`}if(r instanceof J){let o=r.subject,a=o.version;return a&&typeof a.major=="number"?`${o.publisher}/${o.package_}@${a.major}.${a.minor}.${a.patch}/${o.name}`:`${o.publisher}/${o.package_}/${o.name}`}return}case"display-label":{let r=await this.resolver.resolveSubject({...e.labelTarget},this.catalog);return r?zt(r,e.labelSource):void 0}case"resolve-ref":{let r=await this.evaluate(e.source,t);return r instanceof J?await this.resolver.resolveSubject(r.subject,this.catalog):Ke(r)?await this.resolver.resolveSubject(r,this.catalog):void 0}case"normalize":{let r=await this.evaluate(e.source,t),o=r==null?"":xe(r);return e.normKind==="trim-end"?o.replace(/[\s\r\n]+$/u,""):o}case"build-ast-node":{let r={kind:e.astClass.name};for(let o of e.set){let a=await this.evaluate(o.value,t);if(a==null||Array.isArray(a)&&a.length===0)continue;let i=o.field.name;Array.isArray(a)&&ji.has(i)&&a.every(s=>Ui(s))&&(a=a.map(s=>String(s)).join("")),r[i]=a}return r}case"call-fragment":return this.evaluate(e.body,t);case"join":return(await this.evaluateList(e.source,t)).map(o=>o==null?"":xe(o)).join(e.separator);case"count":return(await this.evaluateList(e.source,t)).length;case"sum":{let r=await this.evaluateList(e.source,t),o=0;for(let a of r)o+=x(a,"Sum");return o}case"min":{let r=await this.evaluateList(e.source,t);if(r.length===0)throw new G("Min on an empty list is undefined; guard with IsSet");let o=x(r[0],"Min");for(let a=1;a<r.length;a++){let i=x(r[a],"Min");i<o&&(o=i)}return o}case"max":{let r=await this.evaluateList(e.source,t);if(r.length===0)throw new G("Max on an empty list is undefined; guard with IsSet");let o=x(r[0],"Max");for(let a=1;a<r.length;a++){let i=x(r[a],"Max");i>o&&(o=i)}return o}case"average":{let r=await this.evaluateList(e.source,t);if(r.length===0)throw new G("Average on an empty list is undefined; guard with IsSet");let o=0;for(let a of r)o+=x(a,"Average");return o/r.length}case"for-each":{let r=await this.evaluateList(e.source,t),o=[];for(let a of r){let i=new Map(t);i.set(e.loopVar,a);let s=await this.evaluate(e.emit,i);if(s!=null)if(Array.isArray(s))for(let c of s)o.push(c);else o.push(s)}return o}case"list-map":{let r=await this.evaluateList(e.source,t),o=[];for(let a of r){let i=new Map(t);i.set(e.loopVar,a),o.push(await this.evaluate(e.mapBody,i))}return o}case"filter":{let r=await this.evaluateList(e.source,t),o=[];for(let a of r){let i=new Map(t);i.set(e.loopVar,a),await this.evaluate(e.predicate,i)===!0&&o.push(a)}return o}case"partition-by":{let r=await this.evaluateList(e.source,t),o=new Map,a=[];for(let i of r){let s=new Map(t);s.set(e.loopVar,i);let c=await this.evaluate(e.partitionKey,s),l=Gt(c),d=o.get(l);d||(d={kind:"Partition",key:c,members:[]},o.set(l,d),a.push(l)),d.members.push(i)}return a.map(i=>o.get(i))}case"distinct-by":{let r=await this.evaluateList(e.source,t),o=new Set,a=[];for(let i of r){let s=new Map(t);s.set(e.loopVar,i);let c=await this.evaluate(e.distinctKey,s),l=Gt(c);o.has(l)||(o.add(l),a.push(i))}return a}case"all-statements":{let r=await this.evaluate(e.source,t);return r instanceof Pe?r.statement:[]}case"statement-predicate":{let r=await this.evaluate(e.source,t);if(Wt(r)){let o=r.predicate;if(o instanceof J)return o}return}case"statement-value":{let r=await this.evaluate(e.source,t);return Wt(r)?Ni(r):void 0}case"date-format":{let r=await this.evaluate(e.source,t),o=r==null?"":xe(r);return o?xi(o,e.format):""}case"add":{let r=x(await this.evaluate(e.left,t),"Add"),o=x(await this.evaluate(e.right,t),"Add");return r+o}case"subtract":{let r=x(await this.evaluate(e.left,t),"Subtract"),o=x(await this.evaluate(e.right,t),"Subtract");return r-o}case"multiply":{let r=x(await this.evaluate(e.left,t),"Multiply"),o=x(await this.evaluate(e.right,t),"Multiply");return r*o}case"divide":{let r=x(await this.evaluate(e.left,t),"Divide"),o=x(await this.evaluate(e.right,t),"Divide");if(o===0)throw new G("Divide by zero; guard with When");return r/o}case"reverse":return[...await this.evaluateList(e.source,t)].reverse();default:{let r=e;throw new G("Unknown expression kind")}}}async evaluateList(e,t){let r=await this.evaluate(e,t);return r==null?[]:Array.isArray(r)?r:[r]}};function zt(n,e){if(n instanceof Pe)return _i(n,e);if(Ti(n))return U(e,u.key)?n.key:U(e,u.members)?n.members:void 0}function _i(n,e){for(let t of n.statement){let r=Jt(t);if(!(!r||!U(r,e))&&(t instanceof wn||t instanceof $n||t instanceof Sn||t instanceof Le||t instanceof vn||t instanceof Fe))return t.object}}function Ii(n,e){let t=[];for(let r of n.statement){let o=Jt(r);if(!(!o||!U(o,e))){if(r instanceof Le)t.push(r.object.subject);else if(r instanceof Fe)for(let a of r.object)a instanceof J&&t.push(a.subject)}}return t}function Jt(n){return n.predicate?.subject}function xe(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);if(n instanceof Pe)return n.name??"";if(n instanceof J)return n.subject.name;if(Ke(n))return n.name;let e=n.value;return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function qt(n){return n==null?!1:typeof n=="string"||Array.isArray(n)?n.length>0:typeof n=="boolean"?n===!0:!0}function Ke(n){return typeof n=="object"&&n!==null&&typeof n.publisher=="string"&&typeof n.package_=="string"&&typeof n.name=="string"}function Ti(n){return typeof n=="object"&&n!==null&&n.kind==="Partition"&&Array.isArray(n.members)}function x(n,e){if(typeof n=="number"&&Number.isFinite(n))return n;throw new G(`${e} requires numeric elements; got ${Oi(n)}`)}function yn(n){if(n instanceof bn){let e=n.namespace??"",t=e.indexOf("/"),r=e.indexOf("@",t+1);return t<0||r<0?void 0:{publisher:e.substring(0,t),package_:e.substring(t+1,r),version:e.substring(r+1),name:n.name??""}}if(n instanceof J){let e=n.subject,t=e.version;return{publisher:e.publisher,package_:e.package_,version:t&&typeof t.major=="number"?`${t.major}.${t.minor}.${t.patch}`:"",name:e.name}}if(Ke(n))return{publisher:n.publisher,package_:n.package_,version:"",name:n.name}}var ji=new Set(["stringValue","text","rawContent","key"]);function Ui(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"}function Oi(n){return n===void 0?"undefined":n===null?"null":Array.isArray(n)?`array(${n.length})`:typeof n}function xi(n,e){let t=new Date(n);if(isNaN(t.getTime()))return"";let r=t.getUTCFullYear(),o=["January","February","March","April","May","June","July","August","September","October","November","December"][t.getUTCMonth()],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getUTCMonth()],i=t.getUTCDate(),s=(c,l=2)=>String(c).padStart(l,"0");switch(e){case"iso-date":return`${r}-${s(t.getUTCMonth()+1)}-${s(i)}`;case"iso-datetime":return`${r}-${s(t.getUTCMonth()+1)}-${s(i)}T${s(t.getUTCHours())}:${s(t.getUTCMinutes())}:${s(t.getUTCSeconds())}Z`;case"short-date":return`${a} ${i}`;case"long-date":return`${o} ${i}, ${r}`;case"year":return String(r);case"month-year":return`${o} ${r}`}}function Wt(n){return n instanceof wn||n instanceof $n||n instanceof Sn||n instanceof Le||n instanceof vn||n instanceof Fe}function Ni(n){return n instanceof wn||n instanceof $n||n instanceof Sn?String(n.object??""):n instanceof Le?n.object?.subject?.name??"":n instanceof vn?"[embedded]":n instanceof Fe?(n.object??[]).map(t=>{if(t instanceof J)return t.subject.name;let r=t.name;if(r&&r.length>0)return r;let o=t.value;return typeof o=="string"||typeof o=="number"||typeof o=="boolean"?String(o):"[embedded]"}).join(", "):""}function Gt(n){if(n===void 0)return"\0undef";if(n===null)return"\0null";if(typeof n=="string")return`s:${n}`;if(typeof n=="number")return`n:${n}`;if(typeof n=="boolean")return`b:${n}`;if(n instanceof J){let e=n.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(n instanceof Pe){let e=n.name??"";return`k:${n.namespace??""}/${e}`}return Ke(n)?`u:${n.publisher}/${n.package_}/${n.name}`:`o:${JSON.stringify(n)}`}var Ve={"markdown-with-frontmatter":{formatUri:"kanonak.org/transformations/markdown-with-frontmatter",extension:".md"},"plain-markdown":{formatUri:"kanonak.org/transformations/plain-markdown",extension:".md"},toml:{formatUri:"kanonak.org/transformations/toml",extension:".toml"},json:{formatUri:"kanonak.org/transformations/json",extension:".json"},html:{formatUri:"kanonak.org/transformations/html",extension:".html"},svg:{formatUri:"kanonak.org/transformations/svg",extension:".svg"}},ee=class extends Error{},M=class{backends=new Map;constructor(){this.register(new Re),this.register(new _e),this.register(new Ie),this.register(new Te),this.register(new je)}register(e){this.backends.set(e.backendUri,e)}async run(e){let t=e.transformationKanonaks??e.allKanonaks,r=ge(e.transformation,t);if(!r.outputs.has(e.outputFormat))throw new ee(`Transformation "${r.name}" does not declare output format "${e.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let o=this.findBackend(e.outputFormat);if(!o)throw new ee(`No backend registered for OutputFormat "${e.outputFormat}".`);let a=new Ue(e.repository,e.parser,e.objectParser),i=new Ne(a,e.allKanonaks);return r.kind==="instance"?this.runInstance(r,e,o,i):this.runSet(r,e,o,i)}async runInstance(e,t,r,o){let a=Xt(t.instances,e.inputPattern.requires),i=Yt(a,e.inputPattern.sortBy),s=[];for(let c of i){let l=new Map;l.set("input",c);let d=await o.evaluate(e.rule,l);Pn(d,e.name,`input "${c.name}"`);let f=Kn(await o.evaluate(e.artifactName,l),e.name,`input "${c.name}"`),p=e.overrides.get(t.outputFormat),k=r.render(d,p);s.push({fileName:f,format:t.outputFormat,content:k,source:{kind:"instance",sourceName:c.name}})}return s}async runSet(e,t,r,o){let a=Xt(t.instances,e.inputPattern.requires),i=Yt(a,e.inputPattern.sortBy);return e.partitionBy?this.runSetWithPartition(e,i,t,r,o):this.runSetSingle(e,i,t,r,o)}async runSetSingle(e,t,r,o,a){let i=new Map;i.set("inputs",t);let s=await a.evaluate(e.rule,i);Pn(s,e.name,"set");let c=Kn(await a.evaluate(e.artifactName,i),e.name,"set"),l=e.overrides.get(r.outputFormat),d=o.render(s,l);return[{fileName:c,format:r.outputFormat,content:d,source:{kind:"set",memberCount:t.length}}]}async runSetWithPartition(e,t,r,o,a){let i=e.partitionBy,s=new Map,c=[];for(let d of t){let f=Vi(d,i);if(f==null)continue;let p=Mi(f),k=s.get(p);k||(k={keyValue:f,keyDisplay:Bi(f),members:[]},s.set(p,k),c.push(p)),k.members.push(d)}let l=[];for(let d of c){let f=s.get(d),p=new Map;p.set("inputs",f.members),p.set("key",f.keyValue);let k=await a.evaluate(e.rule,p);Pn(k,e.name,`partition "${f.keyDisplay}"`);let b=Kn(await a.evaluate(e.artifactName,p),e.name,`partition "${f.keyDisplay}"`),g=e.overrides.get(r.outputFormat),y=o.render(k,g);l.push({fileName:b,format:r.outputFormat,content:y,source:{kind:"set",memberCount:f.members.length,partitionKey:f.keyDisplay}})}return l}findBackend(e){let t=Ve[e];if(t)return this.backends.get(t.formatUri)}};function Xt(n,e){return e.length===0?n:n.filter(t=>{for(let r of e)if(!Fi(t,r))return!1;return!0})}function Yt(n,e){if(e.length===0)return n;let t=[...n];return t.sort((r,o)=>{for(let a of e){let i=Zt(r,a.byProperty),s=Zt(o,a.byProperty),c=Li(i,s,a.order);if(c!==0)return c}return 0}),t}function Zt(n,e){for(let t of n.statement){let r=Dn(t);if(!(!r||!U(r,e))){if(t instanceof nr||t instanceof tr||t instanceof rr)return t.object;if(t instanceof ar)throw new ee(`Sort property "${e.name}" on instance "${n.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(t instanceof or)throw new ee(`Sort property "${e.name}" on instance "${n.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function Li(n,e,t){if(n===void 0&&e===void 0)return 0;if(n===void 0)return t==="ascending"?1:-1;if(e===void 0)return t==="ascending"?-1:1;let r;return typeof n=="number"&&typeof e=="number"?r=n-e:r=String(n).localeCompare(String(e)),t==="ascending"?r:-r}function Fi(n,e){for(let t of n.statement){let r=Dn(t);if(!r||!U(r,e))continue;let o=t.object;if(o!=null&&!(typeof o=="string"&&o.length===0)&&!(Array.isArray(o)&&o.length===0))return!0}return!1}function Vi(n,e){for(let t of n.statement){let r=Dn(t);if(!(!r||!U(r,e))&&(t instanceof nr||t instanceof tr||t instanceof rr||t instanceof or||t instanceof ar))return t.object}}function Dn(n){return n.predicate?.subject}function Mi(n){if(n===void 0)return" undef";if(n===null)return" null";if(typeof n=="string")return`s:${n}`;if(typeof n=="number")return`n:${n}`;if(typeof n=="boolean")return`b:${n}`;if(n instanceof er){let e=n.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(n instanceof Qt){let e=n.name??"";return`k:${n.namespace??""}/${e}`}if(typeof n=="object"&&n!==null&&typeof n.name=="string"&&typeof n.publisher=="string"){let e=n;return`u:${e.publisher}/${e.package_}/${e.name}`}return`o:${JSON.stringify(n)}`}function Bi(n){return n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):n instanceof er?n.subject.name:n instanceof Qt?n.name??"":typeof n=="object"&&n!==null&&typeof n.name=="string"?n.name:""}function Pn(n,e,t){if(typeof n!="object"||n===null||n.kind!=="Document")throw new ee(`Transformation "${e}" rule did not yield a Document for ${t}. Got: ${ir(n)}`)}function Kn(n,e,t){if(typeof n=="string")return n;if(Array.isArray(n)&&n.every(Hi))return n.map(r=>String(r)).join("");throw new ee(`Transformation "${e}" artifactName did not yield a string for ${t}. Got: ${ir(n)}`)}function Hi(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"}function ir(n){if(n===void 0)return"undefined";if(n===null)return"null";if(Array.isArray(n))return`array(${n.length})`;if(typeof n=="object"){let e=n.kind;return e?`object(kind=${e})`:"object"}return typeof n}function En(n){return[...C(n,u.InstanceTransformation),...C(n,u.SetTransformation)]}function dr(){let n=new De("transform").description("Run ontology-driven transformations against Kanonak packages. Transformations are declarative YAML rules (instances of `kanonak.org/transformations/Transformation`) that convert ontology instances into output files. The runner produces one or more Artifacts per matched input; format backends serialize them to Markdown, HTML, SVG, TOML, JSON, or (with post-processing) PDF.").addHelpText("after",`
|
|
132
135
|
Examples:
|
|
133
136
|
|
|
134
137
|
# List every Transformation available in the local workspace
|
|
@@ -166,14 +169,25 @@ Examples:
|
|
|
166
169
|
|
|
167
170
|
# List the registered format backends
|
|
168
171
|
$ kanonak transform formats
|
|
169
|
-
`);return n.addCommand(
|
|
172
|
+
`);return n.addCommand(es()),n.addCommand(os()),n.addCommand(is()),n.addCommand(cs()),n}function es(){return new De("run").description("Run a transformation against an input scope and write the resulting Artifacts to disk.").argument("<transformation>","Transformation URI (`publisher/package/name`, optional `@version`) or just the local name if unique in the workspace.").requiredOption("--scope <scope>","Input source \u2014 either a package URI `publisher/package[@version]` (resolved via the local workspace + cache + HTTP tiers) or a file path to a `.kan.yml` document. Repeatable: pass `--scope X --scope Y` to aggregate matching instances across multiple packages, useful for index pages and other cross-package SetTransformations.",ns,[]).option("--format <name>","OutputFormat name to target (e.g. `markdown-with-frontmatter`, `html`, `svg`, `json`). If omitted and the transformation declares exactly one output, that single format is used.").option("--out <dir>","Directory to write artifacts into.",".").action(async(n,e)=>{try{await ts(n,e)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}})}function ns(n,e){return[...e,n]}async function ts(n,e){let t=new Cn,r=new An,o=await j(process.cwd(),t),a=await fr(n,o,r),{transformation:i,transformationKanonaks:s}=a;console.log(`Transformation: ${Be(i)}`);let c=ge(i,s);e.scope.length===0&&(console.error("At least one --scope is required."),process.exit(1));let l=[],d=new Map;for(let w of e.scope){let $=await ls(w,o,t,r);l.push(...$);let S=await fs($,c.inputPattern.matchesClass,o);for(let D of S){let T=ms(D);T&&!d.has(T)&&d.set(T,D)}console.log(`Scope: ${w} \u2014 found ${S.length} instance(s) of ${c.inputPattern.matchesClass.publisher}/${c.inputPattern.matchesClass.package_}/${c.inputPattern.matchesClass.name}`)}let f=[...d.values()],p=l;e.scope.length>1&&console.log(`Total across ${e.scope.length} scope(s): ${f.length} unique instance(s)`),f.length===0&&c.kind==="instance"&&(console.error("No matching input instances across the supplied scope(s). Check the transformation's inputPattern.matchesClass vs. the scope package(s)."),process.exit(1));let k=rs(c.outputs,e.format);console.log(`Output format: ${k}`);let b=Ve[k];if(!b)throw new Error(`Unknown format "${k}". Run \`kanonak transform formats\` to see what the runner supports.`);let y=await new M().run({transformation:i,instances:f,allKanonaks:p,transformationKanonaks:s,repository:o,parser:t,objectParser:r,outputFormat:k}),h=Xi(e.out);Wi(h,{recursive:!0});for(let w of y){let $=ds(w.fileName),S=Ji(h,`${$}${b.extension}`);qi(S,w.content,"utf-8"),console.log(` wrote ${S}`)}console.log(`Done. ${y.length} artifact(s) written to ${h}`)}function rs(n,e){if(e){if(!n.has(e))throw new Error(`Transformation does not declare --format "${e}" in its outputs. Declared outputs: ${Array.from(n).sort().join(", ")}`);return e}if(n.size===1)return Array.from(n)[0];throw new Error(`Transformation supports multiple output formats (${Array.from(n).sort().join(", ")}); pass --format <name> to select one.`)}function os(){return new De("list").description("Scan the local workspace + cache for every Transformation instance and print a one-line summary per hit.").action(async()=>{try{await as()}catch(n){console.error(`Error: ${n.message}`),process.exit(1)}})}async function as(){let n=new Cn,e=new An,t=await j(process.cwd(),n),r=await t.getAllDocumentsAsync(),o=new Map;for(let i of r)try{let s=new E(i,t),c=await e.parseKanonaks(s),l=En(c);for(let d of l){let f=_n(d);if(!f)continue;let p=o.get(f)??[];p.push({tx:d,kanonaks:c,doc:i}),o.set(f,p)}}catch{}let a=[];for(let i of o.values()){if(i.length===1){a.push(cr(i[0].tx,i[0].kanonaks));continue}let s=Rn(i.map(l=>l.doc));if(!s.chosen)continue;let c=i.find(l=>l.doc===s.chosen);c&&a.push(cr(c.tx,c.kanonaks))}if(a.length===0){console.log("No Transformation instances found in the current workspace.");return}a.sort((i,s)=>i.uri.localeCompare(s.uri));for(let i of a)console.log(`${i.uri}`),console.log(` matches: ${i.matchesClass}`),console.log(` outputs: ${i.outputs.join(", ")}`)}function is(){return new De("show").description("Compile a transformation and print a human-readable summary (input pattern, outputs, format overrides, rule shape).").argument("<transformation>","Transformation URI or local name").action(async n=>{try{await ss(n)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}})}async function ss(n){let e=new Cn,t=new An,r=await j(process.cwd(),e),{transformation:o,transformationKanonaks:a}=await fr(n,r,t),i=ge(o,a);if(console.log(`Transformation: ${Be(o)}`),console.log(),console.log("Input pattern:"),console.log(` Matches class: ${Me(i.inputPattern.matchesClass)}`),i.inputPattern.requires.length>0){console.log(" Required properties:");for(let s of i.inputPattern.requires)console.log(` - ${Me(s)}`)}else console.log(" Required properties: (none)");if(console.log(),console.log(`Outputs: ${Array.from(i.outputs).sort().join(", ")}`),console.log(),i.overrides.size>0){console.log("Format overrides:");for(let[s,c]of i.overrides){if(console.log(` ${s}:`),c.metadataKeys&&console.log(` metadata keys: ${c.metadataKeys.join(", ")}`),c.metadataRenames.size>0){let l=[];for(let[d,f]of c.metadataRenames)l.push(`${d} \u2192 ${f}`);console.log(` metadata renames: ${l.join(", ")}`)}c.trailingNewline!==void 0&&console.log(` trailing newline: ${c.trailingNewline}`)}console.log()}console.log(`Rule root kind: ${i.rule.kind}`),i.rule.kind==="build-ast-node"&&(console.log(`Rule root AST class: ${Me(i.rule.astClass)}`),console.log(`Rule root bindings: ${i.rule.set.length} field(s)`)),console.log(`Artifact name root kind: ${i.artifactName.kind}`)}function cs(){return new De("formats").description("List the OutputFormat names the runner can serialize to.").action(()=>{console.log("Registered format backends:");let n=Object.entries(Ve).sort(([e],[t])=>e.localeCompare(t));for(let[e,t]of n)console.log(` ${e.padEnd(28)} ${t.extension.padEnd(6)} ${t.formatUri}`)})}async function fr(n,e,t){let r,o,a;if(n.includes("/")){let p=n.indexOf("@"),k=n;if(p!==-1){let g=n.indexOf("/",p);if(g===-1)throw new Error(`Transformation URI "${n}" has @version but no trailing /<name>`);k=n.substring(0,p)+n.substring(g)}let b=k.split("/");if(b.length<3)throw new Error(`Invalid transformation URI "${n}" \u2014 expected publisher/package/name or publisher/package@version/name`);r=b[0],o=b[1],a=b.slice(2).join("/")}else a=n;if(r&&o){let p=await e.getDocumentsByNamespaceAsync(r,o);if(p.length===0)throw new Error(`Package ${r}/${o} not found in the local workspace or cache.`);let k=us(n),b=mr(p,k,`${r}/${o}`),g=new E(b,e),y=await t.parseKanonaks(g),h=we(y,{publisher:r,package_:o,name:a,version:""});if(!h){let w=En(y),$=w.find(S=>S.name===a);if(!$)throw new Error(`Transformation "${a}" not found in package ${r}/${o}. Package contains ${w.length} Transformation(s): ${w.map(S=>S.name).join(", ")||"(none)"}`);return{transformation:$,transformationKanonaks:y}}return{transformation:h,transformationKanonaks:y}}let i=await e.getAllDocumentsAsync(),s=new Map;for(let p of i)try{let k=new E(p,e),b=await t.parseKanonaks(k),g=En(b);for(let y of g){if(y.name!==a)continue;let h=_n(y);if(!h)continue;let w=s.get(h)??[];w.push({tx:y,kanonaks:b,doc:p}),s.set(h,w)}}catch{}if(s.size===0)throw new Error(`No Transformation named "${a}" found in the workspace. Try \`kanonak transform list\` to see available transformations.`);if(s.size>1){let p=Array.from(s.keys()).sort().join(`
|
|
170
173
|
`);throw new Error(`Multiple Transformations named "${a}" in the workspace \u2014 disambiguate with a full publisher/package/name URI:
|
|
171
|
-
${p}`)}let c=Array.from(
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
174
|
+
${p}`)}let c=Array.from(s.values())[0];if(c.length===1)return{transformation:c[0].tx,transformationKanonaks:c[0].kanonaks};let l=new Map(c.map(p=>[p.doc,p])),d=Rn(c.map(p=>p.doc));if(!d.chosen)throw new Error(`Could not select a Transformation version for "${a}".`);let f=l.get(d.chosen);if(d.multipleVersionsPresent){let p=g=>{let y=g.metadata.namespace_?.version;return y?ur(y):""},k=f.tx.namespace??"",b=k.includes("@")?k.substring(0,k.indexOf("@")):k;console.warn(`Warning: Transformation "${a}" has ${c.length} versions present (${c.map(g=>p(g.doc)).filter(Boolean).join(", ")}); using @${p(d.chosen)}. Pin with ${b}@<version>/${a} to suppress this warning.`)}return{transformation:f.tx,transformationKanonaks:f.kanonaks}}async function ls(n,e,t,r){if(/^[.\/\\]/.test(n)||/^[A-Za-z]:/.test(n)||n.endsWith(".kan.yml")||sr(n)&&Gi(n).isFile()){if(!sr(n))throw new Error(`Scope file not found: ${n}`);let b=zi(n,"utf-8"),g=t.parse(b),y=new E(g,e);return r.parseKanonaks(y)}let a=n.indexOf("@"),i=a===-1?n:n.substring(0,a),s=a===-1?void 0:n.substring(a+1),c=i.indexOf("/");if(c===-1)throw new Error(`Invalid scope "${n}" \u2014 expected a file path or publisher/package[@version] URI`);let l=i.substring(0,c),d=i.substring(c+1),f=await e.getDocumentsByNamespaceAsync(l,d);if(f.length===0)throw new Error(`Scope package ${l}/${d} not found in the local workspace or cache.`);let p=mr(f,s,`${l}/${d}`),k=new E(p,e);return r.parseKanonaks(k)}function us(n){let e=n.indexOf("@");if(e===-1)return;let t=n.substring(e+1),r=t.indexOf("/");return r===-1?t:t.substring(0,r)}function mr(n,e,t){let r=a=>{let i=a.metadata.namespace_?.version;return i?ur(i):""},o=Rn(n,{requestedVersion:e});if(o.exactRequestedVersionMissing){let a=n.map(r).filter(Boolean).sort().join(", ");throw new Error(`${t}@${e} not found in the local workspace or cache. Available versions: ${a||"(none with parseable namespace)"}`)}if(!o.chosen)throw new Error(`${t} not found in the local workspace or cache.`);return!e&&o.multipleVersionsPresent&&console.warn(`Warning: ${t} has ${n.length} versions present (${n.map(r).filter(Boolean).join(", ")}); using @${r(o.chosen)}. Pin with ${t}@<version> to suppress this warning.`),o.chosen}function cr(n,e){try{let t=ge(n,e);return{uri:Be(n),matchesClass:Me(t.inputPattern.matchesClass),outputs:Array.from(t.outputs).sort()}}catch(t){return{uri:Be(n),matchesClass:`(compile error: ${t.message})`,outputs:[]}}}function Be(n){let e=n.namespace||"",t=e.indexOf("@");return`${t===-1?e:e.substring(0,t)}/${n.name}`}function Me(n){return`${n.publisher}/${n.package_}/${n.name}`}function ds(n){return n.replace(/[\\/:*?"<>|\s]+/g,"_").replace(/^_+|_+$/g,"")}async function fs(n,e,t){let r=new Map;for(let i of n){if(!(i instanceof Yi))continue;let s=_n(i);s&&r.set(s,i)}let o=[];try{o=(await new Zi({vocabulary:new Qi}).reason(t)).getInstancesOfClass(lr(e.publisher,e.package_,e.name))}catch{}let a=[];for(let i of o){let s=r.get(i);s&&a.push(s)}return a.length>0?a:C(n,e)}function _n(n){let e=n.namespace??"",t=e.indexOf("@"),r=t===-1?e:e.substring(0,t),o=r.indexOf("/");return o===-1||!n.name?null:lr(r.substring(0,o),r.substring(o+1),n.name)}function ms(n){let e=n.namespace??"";return!e||!n.name?null:`${e}/${n.name}`}import{Command as ps}from"commander";import{writeFileSync as gs,mkdirSync as ks}from"fs";import{join as hs,resolve as ys}from"path";import{KanonakParser as bs,KanonakObjectParser as ws,SubjectKanonak as kr,findDerivation as $s}from"@kanonak-protocol/sdk";var Ss={publisher:"kanonak.org",package_:"formats",name:"html"},vs={publisher:"kanonak.org",package_:"derivation",name:"default"},Ps={html:".html",markdown:".md",json:".json",yaml:".yaml",xml:".xml",svg:".svg",typescript:".ts","c-sharp":".cs",rust:".rs",python:".py"};function Ks(n){return n==="markdown"?"markdown-with-frontmatter":n}function hr(){return new ps("derive").description("Materialize a derived artifact from a Kanonak resource by walking the polymorphic derivation discovery: instance overrides \u2192 class hierarchy \u2192 universal defaults. The result is written to disk.").argument("<resource>","Resource URI in the form publisher/package[@version]/name. Identifies the specific instance to derive.").option("--format <name>","Format instance name (e.g. html, markdown, json). Defaults to html.","html").option("--variant <name>","Variant instance name (e.g. default, compact, summary). Defaults to default.","default").option("--out <dir>","Directory to write the artifact into.",".").addHelpText("after",`
|
|
175
|
+
Examples:
|
|
176
|
+
|
|
177
|
+
# Render a resource as HTML using whatever derivation the discovery
|
|
178
|
+
# walk finds \u2014 universal default if the class declares none.
|
|
179
|
+
$ kanonak derive worldview.genval.ai/snapshot@1.0.0/snapshot-instance \\
|
|
180
|
+
--format html \\
|
|
181
|
+
--out ./build/
|
|
182
|
+
|
|
183
|
+
# Materialize the JSON view (universal default unless overridden).
|
|
184
|
+
$ kanonak derive my-publisher.com/my-package/my-resource --format json
|
|
185
|
+
`).action(async(n,e)=>{try{await Ds(n,e)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}})}async function Ds(n,e){let t=z(n);if(!t||!t.instanceName)throw new Error(`Invalid resource URI "${n}". Expected publisher/package[@version]/instance.`);let r=new bs,o=new ws,a=await j(process.cwd(),r),i=await o.parseKanonaks(a),s=Es(i,t);if(!s)throw new Error(`Resource ${t.publisher}/${t.packageName}${t.version?`@${t.version}`:""}/${t.instanceName} not found in the workspace or cache.`);console.log(`Resource: ${pr(s)}`);let c=As(e.format),l=Rs(e.variant),d=$s(s,c,l,i);if(!d)throw new Error(`No derivation found for resource ${pr(s)} at (format=${e.format}, variant=${e.variant}). The class hierarchy declares no binding and no universal default applies.`);console.log(`Derivation: ${_s(d)} \u2192 ${gr(d.transformation)}`);let f=Cs(i,d.transformation);if(!f)throw new Error(`Transformation ${gr(d.transformation)} not found in the workspace or cache. The binding pointed at a transformation the resolver cannot locate.`);let p=Ks(e.format),b=await new M().run({transformation:f,instances:[s],allKanonaks:i,repository:a,parser:r,objectParser:o,outputFormat:p}),g=ys(e.out);ks(g,{recursive:!0});let y=Ps[e.format]??"";for(let h of b){let w=Is(h.fileName),$=hs(g,`${w}${y}`);gs($,h.content,"utf-8"),console.log(` wrote ${$}`)}console.log(`Done. ${b.length} artifact(s) written to ${g}`)}function Es(n,e){for(let t of n){if(!(t instanceof kr)||t.name!==e.instanceName)continue;let r=t.namespace||"",o=`${e.publisher}/${e.packageName}@`;if(r.startsWith(o))if(e.version){if(r===`${e.publisher}/${e.packageName}@${e.version}`)return t}else return t}}function Cs(n,e){let t=`${e.publisher}/${e.package_}@${e.version}`;for(let r of n)if(r instanceof kr&&r.name===e.name&&r.namespace===t)return r}function As(n){if(n.includes("/")){let e=z(n);if(!e||!e.instanceName)throw new Error(`Invalid --format URI "${n}".`);return{publisher:e.publisher,package_:e.packageName,name:e.instanceName}}return{...Ss,name:n}}function Rs(n){if(n.includes("/")){let e=z(n);if(!e||!e.instanceName)throw new Error(`Invalid --variant URI "${n}".`);return{publisher:e.publisher,package_:e.packageName,name:e.instanceName}}return{...vs,name:n}}function pr(n){return`${n.namespace}/${n.name}`}function gr(n){return`${n.publisher}/${n.package_}@${n.version}/${n.name}`}function _s(n){return n.source==="instance"?"instance override":`class ${n.source.publisher}/${n.source.package_}/${n.source.name}`}function Is(n){return n.replace(/[^a-zA-Z0-9._@-]+/g,"_")}import{Command as Sr}from"commander";import{writeFileSync as In,mkdirSync as He}from"fs";import{join as Tn,resolve as Ts,dirname as jn}from"path";import{KanonakParser as js,KanonakObjectParser as Us,SubjectKanonak as vr,ReferenceStatement as Os,ReferenceKanonak as xs,ListStatement as Ns,StringStatement as Pr,EmbeddedStatement as Ls,findDerivation as yr}from"@kanonak-protocol/sdk";var q="kanonak.org",W="site",br={publisher:"kanonak.org",package_:"formats",name:"html"},wr={publisher:"kanonak.org",package_:"derivation",name:"default"};function Kr(){let n=new Sr("site").description("Materialize a publisher's site \u2014 every StaticPage and AggregateView in the workspace gets rendered to its declared output path under the --out directory.");return n.addCommand(Fs()),n}function Fs(){return new Sr("build").description("Walk the workspace, find every StaticPage and AggregateView, and write each materialized artifact to its declared output path under the --out directory.").option("--out <dir>","Output base directory.","./_site").action(async n=>{try{await Vs(n)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}})}async function Vs(n){let e=new js,t=new Us,r=await j(process.cwd(),e),o=await t.parseKanonaks(r),a=Ts(n.out);He(a,{recursive:!0});let i=await r.getAllDocumentsAsync(),s=new Set;for(let g of i){let y=g.metadata.namespace_?.toString();y&&s.add(y)}let c={publisher:q,package_:W,name:"StaticPage"},l={publisher:q,package_:W,name:"ResourcePage"},d={publisher:q,package_:W,name:"AggregateView"},f=C(o,c).filter(g=>s.has(g.namespace||"")),p=C(o,l).filter(g=>s.has(g.namespace||"")),k=C(o,d).filter(g=>s.has(g.namespace||""));console.log(`Found ${f.length} StaticPage(s), ${p.length} ResourcePage(s), and ${k.length} AggregateView(s) in the workspace.`);let b=new M;for(let g of f){let y=Un(g,q,W,"outputPath")??`${g.name}.html`,h=yr(g,br,wr,o);if(!h){console.warn(` [skip] ${g.name}: no HTML/default derivation found (check class hierarchy or universal-derivations is loaded)`);continue}let w=On(o,h.transformation);if(!w){console.warn(` [skip] ${g.name}: transformation ${xn(h.transformation)} not found`);continue}let $=await b.run({transformation:w,instances:[g],allKanonaks:o,repository:r,parser:e,objectParser:t,outputFormat:"html"});if($.length===0){console.warn(` [skip] ${g.name}: transformation produced no artifacts`);continue}let S=Tn(a,y);He(jn(S),{recursive:!0}),In(S,$[0].content,"utf-8"),console.log(` wrote ${S} (StaticPage ${g.name})`)}for(let g of p){let y=Un(g,q,W,"outputPath")??`${g.name}.html`,h=$r(g,q,W,"pageOf");if(!h){console.warn(` [skip] ${g.name}: no pageOf declared`);continue}let w=o.find(F=>F instanceof vr&&F.name===h.name&&(F.namespace||"").startsWith(`${h.publisher}/${h.package_}@`));if(!w){console.warn(` [skip] ${g.name}: pageOf target ${h.publisher}/${h.package_}/${h.name} not found`);continue}let $=yr(w,br,wr,o);if(!$){console.warn(` [skip] ${g.name}: no derivation for target ${w.name}`);continue}let S=On(o,$.transformation);if(!S){console.warn(` [skip] ${g.name}: transformation ${xn($.transformation)} not found`);continue}let D=await b.run({transformation:S,instances:[w],allKanonaks:o,repository:r,parser:e,objectParser:t,outputFormat:"html"});if(D.length===0){console.warn(` [skip] ${g.name}: transformation produced no artifacts`);continue}let T=Tn(a,y);He(jn(T),{recursive:!0}),In(T,D[0].content,"utf-8"),console.log(` wrote ${T} (ResourcePage ${g.name} \u2192 ${w.name})`)}for(let g of k){let y=Un(g,q,W,"outputPath");if(!y){console.warn(` [skip] ${g.name}: no outputPath declared`);continue}let h=$r(g,q,W,"scopeClass");if(!h){console.warn(` [skip] ${g.name}: no scopeClass declared`);continue}let w={publisher:h.publisher,package_:h.package_,name:h.name},$=Ms(g,q,W,"scopeSources"),S=Bs(g);if(!S){console.warn(` [skip] ${g.name}: no transformation declared`);continue}let D=On(o,S);if(!D){console.warn(` [skip] ${g.name}: transformation ${xn(S)} not found`);continue}let T=await zs($,r),F=[],qn=new Set;for(let io of T){let so=await qs(io,r,e,t),co=C(so,w);for(let on of co){let Gn=`${on.namespace}/${on.name}`;qn.has(Gn)||(qn.add(Gn),F.push(on))}}console.log(` ${g.name}: ${F.length} instance(s) of ${w.publisher}/${w.package_}/${w.name} across ${T.length} scope(s)`);let Wn=await b.run({transformation:D,instances:F,allKanonaks:o,repository:r,parser:e,objectParser:t,outputFormat:"html"});if(Wn.length===0){console.warn(` [skip] ${g.name}: transformation produced no artifacts`);continue}let rn=Tn(a,y);He(jn(rn),{recursive:!0}),In(rn,Wn[0].content,"utf-8"),console.log(` wrote ${rn} (AggregateView ${g.name})`)}console.log("Site build complete.")}function Un(n,e,t,r){for(let o of n.statement)if(o instanceof Pr&&ze(o,e,t,r))return o.object}function Ms(n,e,t,r){for(let o of n.statement){if(!(o instanceof Ns)||!ze(o,e,t,r))continue;let a=[];for(let i of o.object??[]){let s=i.value;typeof s=="string"&&a.push(s)}return a}return[]}function $r(n,e,t,r){for(let o of n.statement)if(o instanceof Os&&ze(o,e,t,r)&&o.object instanceof xs)return{publisher:o.object.subject.publisher,package_:o.object.subject.package_,name:o.object.subject.name}}function Bs(n){for(let e of n.statement)if(e instanceof Ls&&ze(e,q,W,"transformation"))return Hs(e.object)}function Hs(n){let e,t,r,o;for(let a of n.statement){if(!(a instanceof Pr))continue;let i=a.predicate?.subject?.name;i==="publisher"?e=a.object:i==="package"?t=a.object:i==="version"?r=a.object:i==="name"&&(o=a.object)}if(!(!e||!t||!r||!o))return{publisher:e,package_:t,version:r,name:o}}function ze(n,e,t,r){let o=n.predicate?.subject;return o?o.publisher===e&&o.package_===t&&o.name===r:!1}function On(n,e){let t=`${e.publisher}/${e.package_}@${e.version}`;for(let r of n)if(r instanceof vr&&r.name===e.name&&r.namespace===t)return r}function xn(n){return`${n.publisher}/${n.package_}@${n.version}/${n.name}`}async function zs(n,e){let t=[];for(let r of n){let o=r.indexOf("@*");if(o===-1){t.push(r);continue}let a=r.substring(0,o),i=a.indexOf("/");if(i===-1){t.push(r);continue}let s=a.substring(0,i),c=a.substring(i+1),l=await e.getDocumentsByNamespaceAsync(s,c);for(let d of l){let f=d.metadata.namespace_;if(!f)continue;let p=f.version;t.push(`${f.publisher}/${f.package_}@${p.major}.${p.minor}.${p.patch}`)}}return t}async function qs(n,e,t,r){let o=n.indexOf("/"),a=n.indexOf("@");if(o===-1||a===-1)return[];let i=n.substring(0,o),s=n.substring(o+1,a),c=n.substring(a+1),l=await e.getDocumentsByNamespaceAsync(i,s);for(let d of l){let f=d.metadata.namespace_?.version;if(f&&`${f.major}.${f.minor}.${f.patch}`===c){let p=new E(d,e);return r.parseKanonaks(p)}}return[]}import{Command as Ws}from"commander";import{KanonakParser as Gs,PublisherIndex as Dr,CredentialStore as Er,createAuthenticatedFetch as Cr,FileSystemKanonakDocumentRepository as Js,Reasoner as Xs,KanonakVocabulary as Ys,getGlobalCachePath as Zs,makeUriKey as Qs}from"@kanonak-protocol/sdk";function ec(n){let e=n.split("/");if(e.length!==3)return null;let[t,r,o]=e;return!t||!r||!o?null:{publisher:t,package_:r,name:o}}function Ar(){return new Ws("search").description("Browse a publisher's catalogue or find instances of a class via the SDK reasoner").argument("<publisher>","Publisher domain (e.g. kanonak.org)").option("--type <uri>","Class URI to search for, in publisher/package/Name form").action(async(n,e)=>{e.type?await tc(n,e.type):await nc(n)})}async function nc(n){let e=new Er,t=Cr(e),r=new Dr({fetchFn:t}),o;try{o=await r.listLatestPackages(n)}catch(i){console.error(`Failed to fetch publisher index for ${n}: ${i.message}`),process.exit(1)}if(o.length===0){console.log(`No packages found at ${n}.`);return}console.log(`Packages published by ${n}:
|
|
186
|
+
`);let a=o.reduce((i,s)=>Math.max(i,s.packageName.length),0);for(let{packageName:i,version:s}of o)console.log(` ${i.padEnd(a)} @${s}`)}async function tc(n,e){let t=ec(e);t||(console.error(`Invalid --type value: ${e}`),console.error("Expected: publisher/package/Name (e.g. kanonak.org/capabilities/Capability)"),process.exit(1));let r=new Gs,o=new Er,a=Cr(o),i=new Dr({fetchFn:a}),s=new V,c=new Set,l=[];try{l=await i.listLatestPackages(n)}catch(y){console.error(`Failed to fetch publisher index for ${n}: ${y.message}`),process.exit(1)}for(let{packageName:y,version:h}of l)c.add(`${n}|${y}|${h}`);await Nn(i,s,a,"kanonak.org","core-rdf",c),await Nn(i,s,a,"kanonak.org","core-owl",c),await Nn(i,s,a,t.publisher,t.package_,c);for(let y of c){let[h,w,$]=y.split("|");if(!s.has(h,w,$))try{let S=await i.getPackageUrl(h,w,$),D=await a(S,h);if(!D.ok){console.error(`Warning: failed to fetch ${h}/${w}@${$}: ${D.status} ${D.statusText}`);continue}let T=await D.text();s.put(h,w,$,T)}catch(S){console.error(`Warning: failed to fetch ${h}/${w}@${$}: ${S.message}`)}}let d=new Js(Zs(),!0,r),p=await new Xs({vocabulary:new Ys}).reason(d),k=Qs(t.publisher,t.package_,t.name),g=p.getInstancesOfClass(k).filter(y=>y!==k);if(g.length===0){console.log(`No instances of ${k} found in ${n}'s catalogue.`);return}console.log(`Instances of ${k} in ${n}'s catalogue:
|
|
187
|
+
`),g.sort();for(let y of g)console.log(` ${y}`)}async function Nn(n,e,t,r,o,a){try{let i=await n.getHighestVersion(r,o);if(!i)return;a.add(`${r}|${o}|${i}`)}catch{}}import{Command as Rr}from"commander";function ke(n){return`${_}/${I}/${n}`}var Ln={[ke("fetch-and-deploy")]:(n,e,t,r)=>n.add(e,t[0],r),[ke("remove-deployed")]:(n,e,t,r)=>n.remove(e,t[0],r),[ke("list-deployed")]:(n,e,t,r)=>n.list(e,r),[ke("update-deployed")]:(n,e,t,r)=>n.update(e,t[0],r),[ke("search-available")]:(n,e,t,r)=>n.search(e,r),[ke("show-info")]:(n,e,t,r)=>n.info(e,t[0],r)};function _r(n,e,t){for(let r of e){let o=new Rr(r.commandName).description(r.description.trim());for(let a of r.commands){let i=o.command(rc(a));i.description(a.description);for(let s of a.arguments)if(s.isOption){let c=s.defaultValue!=null?`--${s.argumentName} [value]`:`--${s.argumentName} <value>`;i.option(c,"",s.defaultValue)}i.action(async(...s)=>{let c=oc(s);await ac(t,r,a,s,c)})}n.addCommand(o)}}function rc(n){let e=n.arguments.filter(t=>!t.isOption).map(t=>t.required?`<${t.argumentName}>`:`[${t.argumentName}]`);return[n.subcommandName,...e].join(" ")}function oc(n){for(let e=n.length-1;e>=0;e--)if(n[e]&&typeof n[e]=="object"&&!(n[e]instanceof Rr))return n[e];return{}}async function ac(n,e,t,r,o){let a=[];for(let s of r)if(typeof s=="string")a.push(s);else break;t.actionKey||(console.error(`Capability subcommand '${t.subcommandName}' has no resolved \`performs:\` Action. Every CapabilityCommand must declare a performs value pointing at a named Action instance from the capabilities ontology. Known actions: ${Object.keys(Ln).join(", ")}.`),process.exit(1));let i=Ln[t.actionKey];i||(console.error(`Capability subcommand '${t.subcommandName}' references unknown Action '${t.actionKey}'. Known actions: ${Object.keys(Ln).join(", ")}.`),process.exit(1)),await i(n,e,a,o)}import{existsSync as Ir,readFileSync as ic,statSync as Tr}from"fs";import{resolve as sc}from"path";import{KanonakObjectParser as cc,PublisherIndex as Fn,PublisherConfigResolver as lc,formatVersion as jr,pickHighestDocument as uc}from"@kanonak-protocol/sdk";var qe=class{constructor(e,t,r,o,a,i){this.fileCache=e;this.parser=t;this.publisherIndex=r;this.fetchFn=o;this.handlerRegistry=a;this.repository=i}fileCache;parser;publisherIndex;fetchFn;handlerRegistry;repository;objectParser=new cc;async add(e,t,r){let o=this.tryLoadFromLocalFile(t);if(o){this.fileCache.put(o.publisher,o.packageName,o.version,o.content),await this.deployFromDoc(e,o.doc,o.publisher,o.packageName,o.version,void 0,`local file ${t}`,r);return}let a=z(t);a||(console.error(`Invalid package reference: "${t}"`),console.error(""),console.error("Accepted forms:"),console.error(" publisher/package (install all instances, latest version)"),console.error(" publisher/package@version (install all instances, pinned)"),console.error(" publisher/package/instance (install one instance, latest version)"),console.error(" publisher/package@version/instance (install one instance, pinned)"),console.error(" ./path/to/file.kan.yml (install all instances from a local document)"),console.error(""),console.error("Tip: copy a URI directly from `kanonak "+e.commandName+" search`."),process.exit(1));let{publisher:i,packageName:s,version:c,instanceName:l}=a,d=await this.repository.getDocumentsByNamespaceAsync(i,s);if(d.length>0){let k=uc(d,{requestedVersion:c??void 0});if(k.chosen){let b=k.chosen.metadata.namespace_;(!b||!b.version)&&(console.error(`Document for ${i}/${s} is missing namespace metadata.`),process.exit(1));let g=jr(b.version);this.fileCache.put(i,s,g,this.parser.save(k.chosen)),await this.deployFromDoc(e,k.chosen,i,s,g,l??void 0,`${i}/${s}@${g}`,r);return}}let f=c??await this.publisherIndex.getHighestVersion(i,s);f||(console.error(`Could not resolve version for "${i}/${s}".`),await this.printPackageSuggestions(i,s,e.commandName),process.exit(1));let p=this.fileCache.get(i,s,f);if(!p){let k=await this.publisherIndex.getPackageUrl(i,s,f),b=await this.fetchFn(k,i);b.ok||(b.status===404?(console.error(`Package ${i}/${s}@${f} not found at ${k}.`),console.error(`The publisher index lists this version but the file is missing \u2014 it may have been unpublished. Try \`kanonak ${e.commandName} search\` to see the current catalogue.`)):console.error(`Failed to fetch ${k} (${b.status} ${b.statusText}).`),process.exit(1)),p=await b.text(),this.fileCache.put(i,s,f,p)}await this.deployFromDoc(e,this.parser.parse(p),i,s,f,l??void 0,`${i}/${s}@${f}`,r)}tryLoadFromLocalFile(e){if(!(/^[.\/\\]/.test(e)||/^[A-Za-z]:[\\/]/.test(e)||e.endsWith(".kan.yml")||Ir(e)&&Tr(e).isFile()))return;let r=sc(e);(!Ir(r)||!Tr(r).isFile())&&(console.error(`Local file not found: ${e}`),process.exit(1));let o=ic(r,"utf-8"),a=this.parser.parse(o),i=a.metadata.namespace_;return(!i||!i.version)&&(console.error(`${e} has no namespace metadata; cannot determine publisher/package/version. A Kanonak document must declare \`type: Package\` with publisher and version.`),process.exit(1)),{doc:a,content:o,publisher:i.publisher,packageName:i.package_,version:jr(i.version)}}async deployFromDoc(e,t,r,o,a,i,s,c){let l=new E(t,this.repository),d=await this.objectParser.parseKanonaks(l),f=Ur(e.managesTypeKey);f||(console.error(`Capability "${e.commandName}" has no resolved managesType.`),process.exit(1));let p=C(d,f);p.length===0&&(console.error(`${s} does not contain any ${B(f)} instances.`),process.exit(1));let k=p;if(i&&(k=p.filter(y=>y.name===i),k.length===0)){console.error(`Instance "${i}" not found in ${s}.`),console.error(""),console.error(`Available ${B(f)} instance(s):`);for(let y of p)console.error(` - ${y.name}`);console.error(""),console.error("To install all of them, drop the instance suffix:"),console.error(` kanonak ${e.commandName} add ${r}/${o}`),process.exit(1)}let b=i?`${i} from ${s}`:`${k.length} ${B(f)} instance(s) from ${s}`;console.log(`Installing ${b}...`);let g=this.handlerRegistry.get(e.deploymentTargetKey);g?await g.deploy({instances:k,allKanonaks:d,repository:this.repository,options:c}):console.log(`Cached ${r}/${o}@${a} (no deployment handler for "${e.deploymentTargetKey}")`)}async printPackageSuggestions(e,t,r){let o;try{o=await this.publisherIndex.listLatestPackages(e)}catch{return}let a=o.map(i=>({name:i.packageName,version:i.version,score:dc(t,i.packageName)})).filter(i=>i.score>0).sort((i,s)=>s.score-i.score).slice(0,5);if(a.length!==0){console.error(""),console.error("Did you mean one of:");for(let i of a)console.error(` kanonak ${r} add ${e}/${i.name}`)}}async remove(e,t,r){await this.requireHandler(e).undeploy(t,{repository:this.repository,options:r})}async list(e,t){let o=await this.requireHandler(e).list({repository:this.repository,options:t}),a=e.managesTypeKey||"managed";if(o.length===0){console.log(`No ${a} instances installed.`);return}console.log(`Installed ${a} instances:
|
|
188
|
+
`);for(let i of o){let s=i.publisher?`${i.publisher}/${i.package_}@${i.version}`:"unmanaged";console.log(` ${i.name} (${s}) ${i.path}`)}}async update(e,t,r){let a=await this.requireHandler(e).list({repository:this.repository,options:r}),i=t?a.filter(c=>c.name===t):a.filter(c=>c.publisher);if(i.length===0){console.log(t?`"${t}" not found.`:"No managed instances to update.");return}let s=0;for(let c of i){let l=await this.publisherIndex.getHighestVersion(c.publisher,c.package_);!l||l===c.version||(console.log(`Updating ${c.name}: ${c.version} \u2192 ${l}`),await this.add(e,`${c.publisher}/${c.package_}@${l}`,r),s++)}console.log(s===0?"All instances are up to date.":`
|
|
189
|
+
Updated ${s} instance(s).`)}async search(e,t){let r=t.publisher??"kanonak.org",o=Ur(e.managesTypeKey);if(!o){console.error("Capability has no resolved managesType; nothing to search for.");return}console.log(`Searching ${r} for ${B(o)} instances...
|
|
190
|
+
`);let a=new lc,i=await a.getConfig(r),s=a.resolveIndexUrl(r,i),c=await this.fetchFn(s,r);if(!c.ok){console.error(`Failed to fetch package index from ${r}.`);return}let l=await c.text(),d=Fn.parseIndex(l);if(d.size===0){console.error(`No packages found for publisher "${r}".`);return}let f=new Map;for(let[g,y]of d){let h=[...y].sort((w,$)=>{let S=Fn.parseVersion(w),D=Fn.parseVersion($);return!S||!D?0:S.major!==D.major?D.major-S.major:S.minor!==D.minor?D.minor-S.minor:D.patch-S.patch});f.set(g,h[0])}let p=[],k=0;for(let[g,y]of f){let h=this.fileCache.get(r,g,y);if(!h)try{let w=await this.publisherIndex.getPackageUrl(r,g,y),$=await this.fetchFn(w,r);if(!$.ok)continue;h=await $.text(),this.fileCache.put(r,g,y,h)}catch{continue}try{let w=this.parser.parse(h),$=new E(w,this.repository),S=await this.objectParser.parseKanonaks($),D=C(S,o);for(let T of D)p.push({publisher:r,package_:g,version:y,subject:T});k++}catch{continue}}if(p.length===0){console.log(`No ${B(o)} instances found across ${k} package(s).`);return}console.log(`Found ${p.length} ${B(o)} instance(s) in ${k} package(s):
|
|
191
|
+
`);let b=new Map;for(let g of p){let y=`${g.publisher}/${g.package_}@${g.version}`,h=b.get(y);h?h.push(g):b.set(y,[g])}for(let[g,y]of b){let h=y[0],w=`${h.publisher}/${h.package_}`,$=y.length===1;console.log(` ${g}`),console.log(` ${y.length} skill${$?"":"s"}:`);for(let S of y)console.log(` - ${S.subject.name}`);if(console.log(""),$)console.log(" install:"),console.log(` kanonak ${e.commandName} add ${w}/${h.subject.name}`);else{console.log(" install one of them:");for(let S of y)console.log(` kanonak ${e.commandName} add ${w}/${S.subject.name}`);console.log(" install all of them:"),console.log(` kanonak ${e.commandName} add ${w}`)}console.log("")}}async info(e,t,r){let i=(await this.requireHandler(e).list({repository:this.repository,options:r})).find(s=>s.name===t);i||(console.error(`"${t}" is not installed.`),process.exit(1)),console.log(`Name: ${i.name}`),console.log(`Type: ${e.managesTypeKey||"n/a"}`),console.log(`Publisher: ${i.publisher||"unmanaged"}`),console.log(`Package: ${i.package_||"n/a"}`),console.log(`Version: ${i.version||"n/a"}`),console.log(`Path: ${i.path}`)}requireHandler(e){let t=this.handlerRegistry.get(e.deploymentTargetKey);return t||(console.error(`No deployment handler registered for "${e.deploymentTargetKey}". Ensure the capability's deploymentTarget resolves to a DeploymentTarget instance whose URI is registered in the CLI at startup.`),process.exit(1)),t}};function Ur(n){if(!n)return;let e=n.split("/");if(e.length===3)return{publisher:e[0],package_:e[1],name:e[2]}}function dc(n,e){let t=n.toLowerCase(),r=e.toLowerCase();if(t===r)return 100;if(r.includes(t)||t.includes(r))return 50;let o=new Set(t.split("-").filter(Boolean)),a=new Set(r.split("-").filter(Boolean)),i=0;for(let c of o)a.has(c)&&i++;if(i>0)return i*10;let s=fc(t,r);return s===0?100:s<=2?Math.max(1,20-s*5):0}function fc(n,e){if(n===e)return 0;if(n.length===0)return e.length;if(e.length===0)return n.length;let t=new Array(e.length+1),r=new Array(e.length+1);for(let o=0;o<=e.length;o++)t[o]=o;for(let o=0;o<n.length;o++){r[0]=o+1;for(let a=0;a<e.length;a++){let i=n[o]===e[a]?0:1;r[a+1]=Math.min(r[a]+1,t[a+1]+1,t[a]+i)}for(let a=0;a<=e.length;a++)t[a]=r[a]}return t[e.length]}var We=class{handlers=new Map;register(e,t){this.handlers.set(e,t)}get(e){return this.handlers.get(e)??null}};import{mkdirSync as vc,rmSync as Pc,existsSync as Xe,readdirSync as Kc,writeFileSync as Dc}from"fs";import{join as Ye}from"path";import{KanonakObjectParser as Ec,KanonakParser as Cc,computeIntegrity as Ac}from"@kanonak-protocol/sdk";import{join as Vn}from"path";import{homedir as Or}from"os";import{KanonakObjectParser as mc}from"@kanonak-protocol/sdk";var te="kanonak.org",re="agent-skills",Nr={publisher:te,package_:re,name:"Client"},Lr={publisher:te,package_:re,name:"clientId"},pc={publisher:te,package_:re,name:"projectSkillDir"},gc={publisher:te,package_:re,name:"userSkillDir"},kc={publisher:te,package_:re,name:"skillFileName"},Fr="agents";async function Ee(n,e){let t=(n.client??Vr()??Fr).toLowerCase(),r=n.scope??"project",o=await Br(t,e);if(!o){let s=await hc(e);throw new Error(`Unknown client "${t}". Known clients: ${s.join(", ")||"(none)"}. Add a Client instance to a package that imports kanonak.org/agent-skills and install that package to make it available.`)}let i=R(o,r==="user"?gc:pc);if(!i)throw new Error(`Client "${t}" has no ${r==="user"?"userSkillDir":"projectSkillDir"} declared.`);return yc(i)}async function Ge(n,e,t){let r=await Ee(e,t);return Vn(r,n)}async function Mn(n,e){let t=(n.client??Vr()??Fr).toLowerCase(),r=await Br(t,e);return r?R(r,kc)??"SKILL.md":"SKILL.md"}function Vr(){if(process.env.CLAUDE_CODE||process.env.CLAUDE_PROJECT_DIR)return"claude-code"}var xr=new WeakMap;async function Mr(n){let e=xr.get(n);if(e)return e;let t=await n.getDocumentsByNamespaceAsync(te,re);if(t.length===0)throw new Error(`Could not find ${te}/${re} in the repository. Install a skill capability (which transitively imports agent-skills) or fetch agent-skills directly to populate the cache.`);let o=[...t].sort((c,l)=>{let d=c.metadata.namespace_?.version,f=l.metadata.namespace_?.version;return!d||!f?0:d.major!==f.major?f.major-d.major:d.minor!==f.minor?f.minor-d.minor:f.patch-d.patch})[0],a=new mc,i=new E(o,n),s=await a.parseKanonaks(i);return xr.set(n,s),s}async function Br(n,e){let t=await Mr(e),r=C(t,Nr);for(let o of r)if(R(o,Lr)===n)return o}async function hc(n){let e=await Mr(n),t=C(e,Nr),r=[];for(let o of t){let a=R(o,Lr);a&&r.push(a)}return r}function yc(n){return n.startsWith("~/")?Vn(Or(),n.slice(2)):n==="~"?Or():n.startsWith("/")||/^[A-Za-z]:[\\/]/.test(n)?n:Vn(process.cwd(),n)}import{readFileSync as bc,writeFileSync as wc,existsSync as $c}from"fs";import{join as Hr}from"path";import zr from"js-yaml";var qr="skills.lock",Sc=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
192
|
+
`;function Je(n){let e=Hr(n,qr);if(!$c(e))return{version:"1",lastUpdated:new Date().toISOString(),skills:{}};let t=bc(e,"utf-8"),r=zr.load(t);return!r||typeof r!="object"||r.version!=="1"?{version:"1",lastUpdated:new Date().toISOString(),skills:{}}:{version:"1",lastUpdated:r.lastUpdated??new Date().toISOString(),skills:r.skills??{}}}function Bn(n,e){e.lastUpdated=new Date().toISOString();let t={};for(let a of Object.keys(e.skills).sort())t[a]=e.skills[a];e.skills=t;let r=Hr(n,qr),o=zr.dump(e,{lineWidth:-1,sortKeys:!1,quotingType:'"'});wc(r,Sc+o,"utf-8")}var Wr="kanonak.org",Gr="skill-to-skill-md",Ze=class{parser=new Cc;objectParser=new Ec;runner=new M;async deploy(e){let{instances:t,allKanonaks:r,repository:o,options:a}=e;if(t.length===0){console.error("No Skill instances to deploy.");return}let i=await Rc(o,this.objectParser);if(!i){console.error(`Cannot deploy: ${Wr}/${Gr}@3.0.0 is not installed in the workspace or cache.`);return}let s=await this.runner.run({transformation:i,instances:t,allKanonaks:r,repository:o,parser:this.parser,objectParser:this.objectParser,outputFormat:"markdown-with-frontmatter"});if(s.length===0){console.error("No skills could be transformed from the package.");return}let c=await Ee(a,o),l=await Mn(a,o),d=Je(c),f=t[0].namespace,{publisher:p,package_:k,version:b}=_c(f);for(let g of s){let y=await Ge(g.fileName,a,o),h=Xe(Ye(y,l));vc(y,{recursive:!0}),Dc(Ye(y,l),g.content,"utf-8"),d.skills[g.fileName]={publisher:p,package_:k,version:b,resolved:p?`kanonak://${p}/${k}@${b}`:"",integrity:Ac(g.content)},console.log(` ${h?"Updated":"Installed"} skill "${g.fileName}" \u2192 ${y}`)}Bn(c,d)}async undeploy(e,t){let{repository:r,options:o}=t,a=await Ge(e,o,r);Xe(a)||(console.error(`Skill "${e}" is not installed at ${a}`),process.exit(1)),Pc(a,{recursive:!0,force:!0});let i=await Ee(o,r),s=Je(i);delete s.skills[e],Bn(i,s),console.log(`Removed skill "${e}" from ${a}`)}async list(e){let{repository:t,options:r}=e,o=await Ee(r,t),a=Je(o),i=[];for(let[c,l]of Object.entries(a.skills))i.push({name:c,publisher:l.publisher,package_:l.package_,version:l.version,path:await Ge(c,r,t)});let s=await Mn(r,t);if(Xe(o))try{let c=Kc(o,{withFileTypes:!0});for(let l of c){if(!l.isDirectory()||a.skills[l.name])continue;let d=Ye(o,l.name,s);Xe(d)&&i.push({name:l.name,publisher:"",package_:"",version:"",path:Ye(o,l.name)})}}catch{}return i}};async function Rc(n,e){let t=await n.getDocumentsByNamespaceAsync(Wr,Gr);if(t.length===0)return;let r=new E(t[0],n),o=await e.parseKanonaks(r);return C(o,u.InstanceTransformation)[0]}function _c(n){if(!n)return{publisher:"",package_:"",version:""};let e=n.indexOf("@");if(e===-1)return{publisher:"",package_:"",version:""};let t=n.substring(0,e),r=n.substring(e+1),o=t.indexOf("/");return o===-1?{publisher:"",package_:"",version:""}:{publisher:t.substring(0,o),package_:t.substring(o+1),version:r}}import{mkdirSync as zc,rmSync as qc,existsSync as zn,readdirSync as Wc,writeFileSync as Gc,statSync as Jc}from"fs";import{join as nn}from"path";import{KanonakObjectParser as Xc,KanonakParser as Yc,computeIntegrity as Zc}from"@kanonak-protocol/sdk";import{join as Jr}from"path";import{homedir as Xr}from"os";import{KanonakObjectParser as Ic}from"@kanonak-protocol/sdk";var oe="kanonak.org",ae="agent-skills",Zr={publisher:oe,package_:ae,name:"Client"},Qr={publisher:oe,package_:ae,name:"clientId"},Tc={publisher:oe,package_:ae,name:"projectAgentDir"},jc={publisher:oe,package_:ae,name:"userAgentDir"},Uc={publisher:oe,package_:ae,name:"agentFileFormat"},Oc="agents";function xc(){if(process.env.CLAUDE_CODE||process.env.CLAUDE_PROJECT_DIR)return"claude-code"}async function Qe(n,e){let t=(n.client??xc()??Oc).toLowerCase(),r=n.scope??"project",o=await Nc(t,e);if(!o){let d=await Lc(e);throw new Error(`Unknown client "${t}". Known clients: ${d.join(", ")||"(none)"}. Add a Client instance to a package that imports kanonak.org/agent-skills and install that package to make it available.`)}let i=R(o,r==="user"?jc:Tc);if(!i)throw new Error(`Client "${t}" has no ${r==="user"?"userAgentDir":"projectAgentDir"} declared.`);let c=ue(o,Uc)?.name==="toml"?"toml":"markdown-frontmatter",l=c==="toml"?".toml":".md";return{agentsDir:Fc(i),format:c,fileExtension:l}}var Yr=new WeakMap;async function eo(n){let e=Yr.get(n);if(e)return e;let t=await n.getDocumentsByNamespaceAsync(oe,ae);if(t.length===0)throw new Error(`Could not find ${oe}/${ae} in the repository. Install a capability that imports agent-skills to populate the cache.`);let o=[...t].sort((c,l)=>{let d=c.metadata.namespace_?.version,f=l.metadata.namespace_?.version;return!d||!f?0:d.major!==f.major?f.major-d.major:d.minor!==f.minor?f.minor-d.minor:f.patch-d.patch})[0],a=new Ic,i=new E(o,n),s=await a.parseKanonaks(i);return Yr.set(n,s),s}async function Nc(n,e){let t=await eo(e),r=C(t,Zr);for(let o of r)if(R(o,Qr)===n)return o}async function Lc(n){let e=await eo(n),t=C(e,Zr),r=[];for(let o of t){let a=R(o,Qr);a&&r.push(a)}return r}function Fc(n){return n.startsWith("~/")?Jr(Xr(),n.slice(2)):n==="~"?Xr():n.startsWith("/")||/^[A-Za-z]:[\\/]/.test(n)?n:Jr(process.cwd(),n)}import{readFileSync as Vc,writeFileSync as Mc,existsSync as Bc}from"fs";import{join as no}from"path";import to from"js-yaml";var ro="agents.lock",Hc=`# This file is generated by Kanonak CLI. Do not edit manually.
|
|
193
|
+
`;function en(n){let e=no(n,ro);if(!Bc(e))return{version:"1",lastUpdated:new Date().toISOString(),agents:{}};let t=Vc(e,"utf-8"),r=to.load(t);return!r||typeof r!="object"||r.version!=="1"?{version:"1",lastUpdated:new Date().toISOString(),agents:{}}:{version:"1",lastUpdated:r.lastUpdated??new Date().toISOString(),agents:r.agents??{}}}function Hn(n,e){e.lastUpdated=new Date().toISOString();let t={};for(let a of Object.keys(e.agents).sort())t[a]=e.agents[a];e.agents=t;let r=no(n,ro),o=to.dump(e,{lineWidth:-1,sortKeys:!1,quotingType:'"'});Mc(r,Hc+o,"utf-8")}var oo="kanonak.org",ao="agent-to-agent-file",tn=class{parser=new Yc;objectParser=new Xc;runner=new M;async deploy(e){let{instances:t,allKanonaks:r,repository:o,options:a}=e;if(t.length===0){console.error("No Agent instances to deploy.");return}let{agentsDir:i,format:s,fileExtension:c}=await Qe(a,o),l=await Qc(o,this.objectParser);if(!l){console.error(`Cannot deploy: ${oo}/${ao}@3.0.0 is not installed in the workspace or cache.`);return}let d=s==="toml"?"toml":"markdown-with-frontmatter",f=await this.runner.run({transformation:l,instances:t,allKanonaks:r,repository:o,parser:this.parser,objectParser:this.objectParser,outputFormat:d});if(f.length===0){console.error("No agents could be transformed from the package.");return}zc(i,{recursive:!0});let p=en(i),k=t[0].namespace,{publisher:b,package_:g,version:y}=nl(k);for(let h of f){let w=`${h.fileName}${c}`,$=nn(i,w),S=zn($);Gc($,h.content,"utf-8"),p.agents[h.fileName]={publisher:b,package_:g,version:y,resolved:b?`kanonak://${b}/${g}@${y}`:"",integrity:Zc(h.content),fileName:w},console.log(` ${S?"Updated":"Installed"} agent "${h.fileName}" \u2192 ${$}`)}Hn(i,p)}async undeploy(e,t){let{repository:r,options:o}=t,{agentsDir:a}=await Qe(o,r),i=en(a),s=i.agents[e];s||(console.error(`Agent "${e}" is not installed at ${a}`),process.exit(1));let c=nn(a,s.fileName);zn(c)&&qc(c,{force:!0}),delete i.agents[e],Hn(a,i),console.log(`Removed agent "${e}" from ${c}`)}async list(e){let{repository:t,options:r}=e,{agentsDir:o}=await Qe(r,t),a=en(o),i=[];for(let[s,c]of Object.entries(a.agents))i.push({name:s,publisher:c.publisher,package_:c.package_,version:c.version,path:nn(o,c.fileName)});if(zn(o))try{let s=Wc(o,{withFileTypes:!0});for(let c of s){if(!c.isFile()||c.name==="agents.lock")continue;let l=nn(o,c.name),d=el(c.name);if(!a.agents[d]){try{if(!Jc(l).isFile())continue}catch{continue}i.push({name:d,publisher:"",package_:"",version:"",path:l})}}}catch{}return i}};async function Qc(n,e){let t=await n.getDocumentsByNamespaceAsync(oo,ao);if(t.length===0)return;let r=new E(t[0],n),o=await e.parseKanonaks(r);return C(o,u.InstanceTransformation)[0]}function el(n){let e=n.lastIndexOf(".");return e===-1?n:n.substring(0,e)}function nl(n){if(!n)return{publisher:"",package_:"",version:""};let e=n.indexOf("@");if(e===-1)return{publisher:"",package_:"",version:""};let t=n.substring(0,e),r=n.substring(e+1),o=t.indexOf("/");return o===-1?{publisher:"",package_:"",version:""}:{publisher:t.substring(0,o),package_:t.substring(o+1),version:r}}var dl=al(ol(import.meta.url)),fl=JSON.parse(rl(il(dl,"..","package.json"),"utf-8")),L=new tl;L.name("kanonak").description("Kanonak Protocol CLI - Validate and resolve Kanonak ontology packages").version(fl.version);L.command("validate <path>").description("Validate .kan.yml file(s). Resolves imports via HTTP from publisher domains.").action(async n=>{await Qn(n)});L.command("install [package]").description("Install a package and its dependencies, or install all from kanonak.lock.").action(async n=>{await et(n)});L.command("deps <path>").description("Show resolved dependency tree for a .kan.yml file.").action(async n=>{await tt(n)});L.command("login <publisher>").description("Authenticate with a package publisher using OAuth 2.0.").action(async n=>{await st(n)});L.command("logout <publisher>").description("Revoke tokens and remove stored credentials for a publisher.").action(async n=>{await ct(n)});L.addCommand(vt());L.addCommand(dr());L.addCommand(hr());L.addCommand(Kr());L.addCommand(Ar());async function ml(){try{let n=new V,e=new sl,t=new ll,r=ul(t),o=new cl({fetchFn:r}),a=await j(process.cwd(),e),i=new We;i.register("kanonak.org/capabilities/agent-skill-deployment",new Ze),i.register("kanonak.org/agent-capabilities/agent-instance-deployment",new tn);let s=await wt(n,e,a),c=new qe(n,e,o,r,i,a);_r(L,s,c)}catch{}}await ml();L.parse();
|
|
@@ -18,4 +18,17 @@ export interface BackendFormatOverride {
|
|
|
18
18
|
metadataRenames: Map<string, string>;
|
|
19
19
|
/** Whether to append a final newline to the serialized output. */
|
|
20
20
|
trailingNewline?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Suppress the backend's default chrome (e.g. the HTML backend's
|
|
23
|
+
* `<!DOCTYPE html><html>...<style>...</style>...</html>` wrapper
|
|
24
|
+
* and its `<dl class="metadata">` block). When true, the backend
|
|
25
|
+
* emits ONLY the rendered content from `document.children`,
|
|
26
|
+
* without any framing — useful for transformations that build
|
|
27
|
+
* the entire HTML document themselves and don't want the CLI's
|
|
28
|
+
* opinionated default getting in the way.
|
|
29
|
+
*
|
|
30
|
+
* Backends that have no chrome (e.g. JSON, plain Markdown) ignore
|
|
31
|
+
* this flag.
|
|
32
|
+
*/
|
|
33
|
+
omitWrapper?: boolean;
|
|
21
34
|
}
|
|
@@ -69,8 +69,11 @@ export interface CompiledFormatOverrideV3 {
|
|
|
69
69
|
metadataKeys?: string[];
|
|
70
70
|
metadataRenames: Map<string, string>;
|
|
71
71
|
trailingNewline?: boolean;
|
|
72
|
+
/** When true, backends suppress their default chrome (HTML's
|
|
73
|
+
* doctype + style + metadata <dl>; analogous in other backends). */
|
|
74
|
+
omitWrapper?: boolean;
|
|
72
75
|
}
|
|
73
|
-
export type CompiledExpressionV3 = CompiledStringLiteralV3 | CompiledIntegerLiteralV3 | CompiledDecimalLiteralV3 | CompiledBooleanLiteralV3 | CompiledVarRefV3 | CompiledPropertyReadV3 | CompiledTraverseV3 | CompiledBuildAstNodeV3 | CompiledWhenV3 | CompiledConcatV3 | CompiledFallbackV3 | CompiledUriNameV3 | CompiledUriPublisherV3 | CompiledUriPackageV3 | CompiledUriVersionV3 | CompiledSubjectUriV3 | CompiledUriLiteralV3 | CompiledDisplayLabelV3 | CompiledResolveRefV3 | CompiledNormalizeV3 | CompiledIsSetV3 | CompiledCallFragmentV3 | CompiledJoinV3 | CompiledCountV3 | CompiledSumV3 | CompiledMinV3 | CompiledMaxV3 | CompiledAverageV3 | CompiledForEachV3 | CompiledListMapV3 | CompiledFilterV3 | CompiledPartitionByV3 | CompiledDistinctByV3;
|
|
76
|
+
export type CompiledExpressionV3 = CompiledStringLiteralV3 | CompiledIntegerLiteralV3 | CompiledDecimalLiteralV3 | CompiledBooleanLiteralV3 | CompiledVarRefV3 | CompiledPropertyReadV3 | CompiledTraverseV3 | CompiledBuildAstNodeV3 | CompiledWhenV3 | CompiledConcatV3 | CompiledFallbackV3 | CompiledUriNameV3 | CompiledUriPublisherV3 | CompiledUriPackageV3 | CompiledUriVersionV3 | CompiledSubjectUriV3 | CompiledUriLiteralV3 | CompiledDisplayLabelV3 | CompiledResolveRefV3 | CompiledNormalizeV3 | CompiledIsSetV3 | CompiledCallFragmentV3 | CompiledJoinV3 | CompiledCountV3 | CompiledSumV3 | CompiledMinV3 | CompiledMaxV3 | CompiledAverageV3 | CompiledForEachV3 | CompiledListMapV3 | CompiledFilterV3 | CompiledPartitionByV3 | CompiledDistinctByV3 | CompiledAllStatementsV3 | CompiledStatementPredicateV3 | CompiledStatementValueV3 | CompiledDateFormatV3 | CompiledAddV3 | CompiledSubtractV3 | CompiledMultiplyV3 | CompiledDivideV3 | CompiledReverseV3;
|
|
74
77
|
export interface CompiledStringLiteralV3 {
|
|
75
78
|
kind: 'string-literal';
|
|
76
79
|
value: string;
|
|
@@ -159,6 +162,49 @@ export interface CompiledResolveRefV3 {
|
|
|
159
162
|
kind: 'resolve-ref';
|
|
160
163
|
source: CompiledExpressionV3;
|
|
161
164
|
}
|
|
165
|
+
export interface CompiledAllStatementsV3 {
|
|
166
|
+
kind: 'all-statements';
|
|
167
|
+
source: CompiledExpressionV3;
|
|
168
|
+
}
|
|
169
|
+
export interface CompiledStatementPredicateV3 {
|
|
170
|
+
kind: 'statement-predicate';
|
|
171
|
+
source: CompiledExpressionV3;
|
|
172
|
+
}
|
|
173
|
+
export interface CompiledStatementValueV3 {
|
|
174
|
+
kind: 'statement-value';
|
|
175
|
+
source: CompiledExpressionV3;
|
|
176
|
+
}
|
|
177
|
+
/** Named output formats supported by the engine. */
|
|
178
|
+
export type DateFormatKindV3 = 'iso-date' | 'iso-datetime' | 'short-date' | 'long-date' | 'year' | 'month-year';
|
|
179
|
+
export interface CompiledDateFormatV3 {
|
|
180
|
+
kind: 'date-format';
|
|
181
|
+
source: CompiledExpressionV3;
|
|
182
|
+
format: DateFormatKindV3;
|
|
183
|
+
}
|
|
184
|
+
export interface CompiledAddV3 {
|
|
185
|
+
kind: 'add';
|
|
186
|
+
left: CompiledExpressionV3;
|
|
187
|
+
right: CompiledExpressionV3;
|
|
188
|
+
}
|
|
189
|
+
export interface CompiledSubtractV3 {
|
|
190
|
+
kind: 'subtract';
|
|
191
|
+
left: CompiledExpressionV3;
|
|
192
|
+
right: CompiledExpressionV3;
|
|
193
|
+
}
|
|
194
|
+
export interface CompiledMultiplyV3 {
|
|
195
|
+
kind: 'multiply';
|
|
196
|
+
left: CompiledExpressionV3;
|
|
197
|
+
right: CompiledExpressionV3;
|
|
198
|
+
}
|
|
199
|
+
export interface CompiledDivideV3 {
|
|
200
|
+
kind: 'divide';
|
|
201
|
+
left: CompiledExpressionV3;
|
|
202
|
+
right: CompiledExpressionV3;
|
|
203
|
+
}
|
|
204
|
+
export interface CompiledReverseV3 {
|
|
205
|
+
kind: 'reverse';
|
|
206
|
+
source: CompiledExpressionV3;
|
|
207
|
+
}
|
|
162
208
|
export type NormalizeKindV3 = 'trim-end';
|
|
163
209
|
export interface CompiledNormalizeV3 {
|
|
164
210
|
kind: 'normalize';
|
|
@@ -41,6 +41,7 @@ export declare const TX_V3: {
|
|
|
41
41
|
readonly metadataKeys: EntityUri;
|
|
42
42
|
readonly metadataRenames: EntityUri;
|
|
43
43
|
readonly trailingNewline: EntityUri;
|
|
44
|
+
readonly omitWrapper: EntityUri;
|
|
44
45
|
readonly RenameEntry: EntityUri;
|
|
45
46
|
readonly fromKey: EntityUri;
|
|
46
47
|
readonly toKey: EntityUri;
|
|
@@ -136,4 +137,21 @@ export declare const TX_V3: {
|
|
|
136
137
|
readonly Partition: EntityUri;
|
|
137
138
|
readonly key: EntityUri;
|
|
138
139
|
readonly members: EntityUri;
|
|
140
|
+
readonly AllStatements: EntityUri;
|
|
141
|
+
readonly statementsOf: EntityUri;
|
|
142
|
+
readonly StatementPredicate: EntityUri;
|
|
143
|
+
readonly predicateOf: EntityUri;
|
|
144
|
+
readonly StatementValue: EntityUri;
|
|
145
|
+
readonly valueOf: EntityUri;
|
|
146
|
+
readonly DateFormat: EntityUri;
|
|
147
|
+
readonly dateSource: EntityUri;
|
|
148
|
+
readonly dateFormat: EntityUri;
|
|
149
|
+
readonly BinaryArithmetic: EntityUri;
|
|
150
|
+
readonly arithLeft: EntityUri;
|
|
151
|
+
readonly arithRight: EntityUri;
|
|
152
|
+
readonly Add: EntityUri;
|
|
153
|
+
readonly Subtract: EntityUri;
|
|
154
|
+
readonly Multiply: EntityUri;
|
|
155
|
+
readonly Divide: EntityUri;
|
|
156
|
+
readonly Reverse: EntityUri;
|
|
139
157
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanonak-protocol/cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.0",
|
|
4
4
|
"description": "Kanonak Protocol CLI - Validate and resolve Kanonak ontology packages",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"semantic-web"
|
|
35
35
|
],
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@kanonak-protocol/sdk": "^3.
|
|
38
|
-
"@kanonak-protocol/types": "^3.
|
|
37
|
+
"@kanonak-protocol/sdk": "^3.6.0",
|
|
38
|
+
"@kanonak-protocol/types": "^3.6.0",
|
|
39
39
|
"commander": "^13.0.0",
|
|
40
40
|
"js-yaml": "^4.1.1"
|
|
41
41
|
},
|