@kanonak-protocol/sdk 3.11.0 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/KanonakUri-4VJGV3FN.js +1 -0
  2. package/dist/browser.js +2 -48
  3. package/dist/chunk-3JRHG2JH.js +1 -0
  4. package/dist/chunk-7M7XXZOV.js +1 -0
  5. package/dist/chunk-AFF2TQ7Y.js +2 -0
  6. package/dist/chunk-C54LRL2A.js +42 -0
  7. package/dist/chunk-CNM3SY5S.js +2 -0
  8. package/dist/chunk-CRR4BQKR.js +1 -0
  9. package/dist/chunk-FQHALFRR.js +1 -0
  10. package/dist/chunk-FUUTGGJS.js +1 -0
  11. package/dist/chunk-GKQVJITL.js +1 -0
  12. package/dist/chunk-MYITGTGJ.js +1 -0
  13. package/dist/chunk-NPWF35XZ.js +1 -0
  14. package/dist/chunk-ODIECDN7.js +1 -0
  15. package/dist/chunk-QJ66UBDY.js +1 -0
  16. package/dist/chunk-RGMZAKJV.js +1 -0
  17. package/dist/chunk-USLG7UIM.js +4 -0
  18. package/dist/chunk-W6T7MOKY.js +1 -0
  19. package/dist/chunk-YENGFI2R.js +1 -0
  20. package/dist/ctl/index.js +1 -4
  21. package/dist/filtering/index.js +1 -1
  22. package/dist/index.js +26 -72
  23. package/dist/parsing/index.js +1 -1
  24. package/dist/reasoning/index.js +1 -1
  25. package/dist/repositories/browser.js +1 -2
  26. package/dist/repositories/index.js +1 -2
  27. package/dist/resolution/index.js +1 -1
  28. package/dist/transformations/DocAst.d.ts +120 -0
  29. package/dist/transformations/DocAstUriConstants.d.ts +65 -0
  30. package/dist/transformations/FormatOverride.d.ts +34 -0
  31. package/dist/transformations/ReferenceResolver.d.ts +23 -0
  32. package/dist/transformations/TransformationEngine.d.ts +72 -0
  33. package/dist/transformations/backends/HtmlBackend.d.ts +7 -0
  34. package/dist/transformations/backends/IDocumentAstBackend.d.ts +16 -0
  35. package/dist/transformations/backends/JsonBackend.d.ts +12 -0
  36. package/dist/transformations/backends/MarkdownFrontmatterBackend.d.ts +7 -0
  37. package/dist/transformations/backends/SimpleMarkdownRenderer.d.ts +17 -0
  38. package/dist/transformations/backends/SvgBackend.d.ts +7 -0
  39. package/dist/transformations/backends/TomlBackend.d.ts +7 -0
  40. package/dist/transformations/index.d.ts +18 -0
  41. package/dist/transformations/index.js +84 -0
  42. package/dist/transformations/v3/CompiledTransformationV3.d.ts +370 -0
  43. package/dist/transformations/v3/ExpressionEngineV3.d.ts +75 -0
  44. package/dist/transformations/v3/TransformationLoaderV3.d.ts +22 -0
  45. package/dist/transformations/v3/TransformationRunnerV3.d.ts +92 -0
  46. package/dist/transformations/v3/TransformationUriConstantsV3.d.ts +200 -0
  47. package/dist/uri-helpers/SingleDocumentRepository.d.ts +28 -0
  48. package/dist/uri-helpers/UriHelpers.d.ts +89 -0
  49. package/dist/uri-helpers/index.d.ts +3 -0
  50. package/dist/uri-helpers/index.js +1 -0
  51. package/dist/validation/index.js +1 -42
  52. package/package.json +18 -2
@@ -0,0 +1,7 @@
1
+ import type { DocAstDocument } from '../DocAst.js';
2
+ import type { BackendFormatOverride } from '../FormatOverride.js';
3
+ import type { IDocumentAstBackend } from './IDocumentAstBackend.js';
4
+ export declare class HtmlBackend implements IDocumentAstBackend {
5
+ readonly backendUri = "kanonak.org/transformations/html";
6
+ render(document: DocAstDocument, override?: BackendFormatOverride): string;
7
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Format backend interface. Given a document-ast Document tree and
3
+ * an optional per-transformation format override, produce the
4
+ * serialized bytes of the artifact as a string.
5
+ *
6
+ * Backends are pure functions of (document, override) — they never
7
+ * touch the filesystem or the repository. That's the deployment
8
+ * handler's job.
9
+ */
10
+ import type { DocAstDocument } from '../DocAst.js';
11
+ import type { BackendFormatOverride } from '../FormatOverride.js';
12
+ export interface IDocumentAstBackend {
13
+ /** The backendUri string this backend registers under. */
14
+ readonly backendUri: string;
15
+ render(document: DocAstDocument, override?: BackendFormatOverride): string;
16
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Trivial JSON backend. Serializes the full Document (both channels)
3
+ * as pretty-printed JSON. Useful as a regression-test oracle that is
4
+ * immune to the whitespace sensitivity of the text backends.
5
+ */
6
+ import type { DocAstDocument } from '../DocAst.js';
7
+ import type { BackendFormatOverride } from '../FormatOverride.js';
8
+ import type { IDocumentAstBackend } from './IDocumentAstBackend.js';
9
+ export declare class JsonBackend implements IDocumentAstBackend {
10
+ readonly backendUri = "kanonak.org/transformations/json";
11
+ render(document: DocAstDocument, override?: BackendFormatOverride): string;
12
+ }
@@ -0,0 +1,7 @@
1
+ import type { DocAstDocument } from '../DocAst.js';
2
+ import type { BackendFormatOverride } from '../FormatOverride.js';
3
+ import type { IDocumentAstBackend } from './IDocumentAstBackend.js';
4
+ export declare class MarkdownFrontmatterBackend implements IDocumentAstBackend {
5
+ readonly backendUri = "kanonak.org/transformations/markdown-with-frontmatter";
6
+ render(document: DocAstDocument, override?: BackendFormatOverride): string;
7
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Minimal CommonMark-ish markdown → HTML renderer.
3
+ *
4
+ * Covers the subset of markdown the Skill hasSection bodies actually
5
+ * use: ATX headings (# through ######), paragraphs, fenced code
6
+ * blocks (```lang\n...\n```), inline code (`code`), bold (**text**),
7
+ * italic (*text* or _text_), unordered lists (- or * item), ordered
8
+ * lists (1. item), links ([text](url)), and GitHub-flavored tables
9
+ * (| header | header | ... |). Does NOT handle blockquotes,
10
+ * reference-style links, HTML passthrough, setext headings, or
11
+ * pipe-escape in table cells.
12
+ *
13
+ * Intentionally self-contained (no dependencies). If a real CommonMark
14
+ * implementation is ever needed, swap this file out — nothing else in
15
+ * the transformation system depends on its internals.
16
+ */
17
+ export declare function renderMarkdownToHtml(source: string): string;
@@ -0,0 +1,7 @@
1
+ import type { DocAstDocument } from '../DocAst.js';
2
+ import type { BackendFormatOverride } from '../FormatOverride.js';
3
+ import type { IDocumentAstBackend } from './IDocumentAstBackend.js';
4
+ export declare class SvgBackend implements IDocumentAstBackend {
5
+ readonly backendUri = "kanonak.org/transformations/svg";
6
+ render(document: DocAstDocument, override?: BackendFormatOverride): string;
7
+ }
@@ -0,0 +1,7 @@
1
+ import type { DocAstDocument } from '../DocAst.js';
2
+ import type { BackendFormatOverride } from '../FormatOverride.js';
3
+ import type { IDocumentAstBackend } from './IDocumentAstBackend.js';
4
+ export declare class TomlBackend implements IDocumentAstBackend {
5
+ readonly backendUri = "kanonak.org/transformations/toml";
6
+ render(document: DocAstDocument, override?: BackendFormatOverride): string;
7
+ }
@@ -0,0 +1,18 @@
1
+ export { TransformationEngine, RenderError, DEFAULT_VARIANT, } from './TransformationEngine.js';
2
+ export type { RenderedArtifact } from './TransformationEngine.js';
3
+ export * from './v3/CompiledTransformationV3.js';
4
+ export * from './v3/ExpressionEngineV3.js';
5
+ export * from './v3/TransformationLoaderV3.js';
6
+ export * from './v3/TransformationRunnerV3.js';
7
+ export * from './v3/TransformationUriConstantsV3.js';
8
+ export * from './DocAst.js';
9
+ export * from './DocAstUriConstants.js';
10
+ export * from './FormatOverride.js';
11
+ export { ReferenceResolver } from './ReferenceResolver.js';
12
+ export type { IDocumentAstBackend } from './backends/IDocumentAstBackend.js';
13
+ export { HtmlBackend } from './backends/HtmlBackend.js';
14
+ export { JsonBackend } from './backends/JsonBackend.js';
15
+ export { MarkdownFrontmatterBackend } from './backends/MarkdownFrontmatterBackend.js';
16
+ export { SvgBackend } from './backends/SvgBackend.js';
17
+ export { TomlBackend } from './backends/TomlBackend.js';
18
+ export { renderMarkdownToHtml } from './backends/SimpleMarkdownRenderer.js';
@@ -0,0 +1,84 @@
1
+ import{b as $,c as d,e as _,k as Ee}from"../chunk-NPWF35XZ.js";import{a as $e}from"../chunk-GKQVJITL.js";import"../chunk-7M7XXZOV.js";import{a as B,c as be}from"../chunk-CRR4BQKR.js";import{b as U,c as E,d as h,g as D,h as L,i as C,j as v,k as K,l as w}from"../chunk-W6T7MOKY.js";import{a as Se}from"../chunk-MYITGTGJ.js";import"../chunk-RGMZAKJV.js";import"../chunk-FUUTGGJS.js";var at="kanonak.org",ot="document-ast",p=t=>({publisher:at,package_:ot,name:t}),T={Document:p("Document"),Block:p("Block"),Inline:p("Inline"),StructuredValue:p("StructuredValue"),Heading:p("Heading"),Paragraph:p("Paragraph"),RawBlock:p("RawBlock"),Text:p("Text"),StructuredMap:p("StructuredMap"),StructuredEntry:p("StructuredEntry"),StructuredList:p("StructuredList"),StringScalar:p("StringScalar"),IntegerScalar:p("IntegerScalar"),EscapeHint:p("EscapeHint"),MediaType:p("MediaType"),metadata:p("metadata"),children:p("children"),level:p("level"),inlines:p("inlines"),text:p("text"),entries:p("entries"),key:p("key"),value:p("value"),escapeHint:p("escapeHint"),items:p("items"),stringValue:p("stringValue"),integerValue:p("integerValue"),rawContent:p("rawContent"),mediaType:p("mediaType"),mimeType:p("mimeType"),ESC_RAW:p("esc-raw"),ESC_YAML_SAFE:p("esc-yaml-safe"),ESC_TOML_STRING:p("esc-toml-string"),ESC_TOML_MULTILINE:p("esc-toml-multiline"),ESC_JSON:p("esc-json"),TEXT_PLAIN:p("text-plain"),TEXT_MARKDOWN:p("text-markdown"),TEXT_HTML:p("text-html"),APPLICATION_JSON:p("application-json"),TEXT_YAML:p("text-yaml"),IMAGE_SVG_XML:p("image-svg-xml"),ResourceLink:p("ResourceLink"),target:p("target"),linkLabel:p("linkLabel"),PropertyList:p("PropertyList"),propertyEntries:p("propertyEntries"),PropertyEntry:p("PropertyEntry"),propertyKey:p("propertyKey"),propertyValue:p("propertyValue")};function ve(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var G=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,n){let r=st(e.metadata,n),i=ft(e.children),u=["---",...r,"---","",i].join(`
2
+ `);return n?.trailingNewline&&(u.endsWith(`
3
+ `)||(u+=`
4
+ `)),u}};function st(t,e){if(!t)return[];let n=new Map;for(let c of t.entries)n.set(ee(c.key),c);let r=new Map;if(e?.metadataRenames)for(let[c,f]of e.metadataRenames)r.set(ee(c),f);let o=(e?.metadataKeys??t.entries.map(c=>c.key)).map(ee),u=[];for(let c of o){let f=n.get(c);if(!f)continue;let m=r.get(c),g=ee(m??c),k=Ve(f.value,f.escapeHint);k!==void 0&&u.push(`${g}: ${k}`)}return u}function ee(t){let e=t.lastIndexOf(".");return e===-1?t:t.substring(e+1)||t}function Ve(t,e){switch(t.kind){case"StringScalar":return ut(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let i=Ve(r,e);i!==void 0&&n.push(i)}return n.join(", ")}case"StructuredMap":return;default:return}}function ut(t,e){return!e||ve(e,T.ESC_RAW)?t:ve(e,T.ESC_YAML_SAFE)?ct(t):t}function ct(t){return t.includes(`
5
+ `)?`|-
6
+ ${t.replace(/\n/g,`
7
+ `).trimEnd()}`:/[:#\[\]{}&*!|>'"%@`,]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function ft(t){let e=[];for(let n of t){let r=je(n);r&&e.push(r)}return e.join(`
8
+
9
+ `)}function je(t){switch(t.kind){case"Heading":return`${"#".repeat(t.level)} ${oe(t.inlines)}`;case"Paragraph":return oe(t.inlines);case"RawBlock":return t.rawContent;case"PropertyList":return Ae(t);default:return""}}function Ae(t,e=0){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let n=" ".repeat(e),r=[];for(let i of t.propertyEntries){let o=`${n}**${i.propertyKey}:**`,u=lt(i.propertyValue,e+1);u.includes(`
10
+ `)?r.push(`${o}
11
+ ${u}`):r.push(`${o} ${u}`)}return r.join(`
12
+ `)}function lt(t,e){if(!t||t.length===0)return"";let n=[],r=[];for(let i of t){let o=i;!o||typeof o!="object"||!o.kind||(o.kind==="Text"||o.kind==="ResourceLink"?n.push(oe([o])):o.kind==="PropertyList"?r.push(Ae(o,e)):r.push(je(o)))}return r.length===0?n.join(""):n.length===0?r.join(`
13
+ `):`${n.join("")}
14
+ ${r.join(`
15
+ `)}`}function oe(t){let e=[];for(let n of t)n.kind==="Text"?e.push(n.text):n.kind==="ResourceLink"&&e.push(dt(n));return e.join("")}function dt(t){let n=t.target?.subject;if(!n||!n.publisher||!n.package_||!n.name)return t.linkLabel??"[unresolved link]";let r=n.version,i=r?`@${r.major}.${r.minor}.${r.patch}`:"",o=`kan://${n.publisher}/${n.package_}${i}/${n.name}`;return`[${t.linkLabel&&t.linkLabel.length>0?t.linkLabel:n.name}](${o})`}function mt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var J=class{backendUri="kanonak.org/transformations/toml";render(e,n){let i=pt(e.metadata,n).join(`
16
+ `);return n?.trailingNewline&&(i.endsWith(`
17
+ `)||(i+=`
18
+ `)),i}};function pt(t,e){if(!t)return[];let n=new Map;for(let o of t.entries)n.set(o.key,o);let r=e?.metadataKeys??t.entries.map(o=>o.key),i=[];for(let o of r){let u=n.get(o);if(!u)continue;let c=e?.metadataRenames.get(o)??o,f=Ke(u.value,u.escapeHint);f!==void 0&&i.push(`${c} = ${f}`)}return i}function Ke(t,e){switch(t.kind){case"StringScalar":return gt(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let i=Ke(r,e);i!==void 0&&n.push(i)}return`[${n.join(", ")}]`}case"StructuredMap":return;default:return}}function gt(t,e){return e&&mt(e,T.ESC_TOML_MULTILINE)?kt(t):yt(t)}function yt(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}"`}function kt(t){return`"""
19
+ ${t.replace(/"""/g,'\\"\\"\\"')}
20
+ """`}var X=class{backendUri="kanonak.org/transformations/json";render(e,n){let r=JSON.stringify(e,null,2);return n?.trailingNewline&&!r.endsWith(`
21
+ `)?r+`
22
+ `:r}};function ue(t){let e=t.replace(/\r\n/g,`
23
+ `).split(`
24
+ `),n=[],r=0;for(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let o=/^(\s*)```(\S*)\s*$/.exec(i);if(o){let f=o[2],m=[];for(r++;r<e.length&&!/^(\s*)```\s*$/.test(e[r]);)m.push(e[r]),r++;r++;let g=Te(m.join(`
25
+ `)),k=f?` class="language-${Le(f)}"`:"";n.push(`<pre><code${k}>${g}</code></pre>`);continue}let u=/^(#{1,6})\s+(.*)$/.exec(i);if(u){let f=u[1].length,m=q(u[2].trim());n.push(`<h${f}>${m}</h${f}>`),r++;continue}if(i.includes("|")&&r+1<e.length&&De(e[r+1])){let f=se(i),m=ht(e[r+1]);r+=2;let g=[];for(;r<e.length&&e[r].trim()!==""&&e[r].includes("|");)g.push(se(e[r])),r++;n.push(wt(f,m,g));continue}if(/^\s*[-*]\s+/.test(i)){let f=[];for(;r<e.length&&/^\s*[-*]\s+/.test(e[r]);){let m=[e[r].replace(/^\s*[-*]\s+/,"")];for(r++;r<e.length&&e[r].trim()!==""&&!/^\s*[-*]\s+/.test(e[r])&&!/^\s*\d+\.\s+/.test(e[r]);)m.push(e[r]),r++;r<e.length&&e[r].trim()===""&&r++,f.push(`<li>${q(m.join(" ").trim())}</li>`)}n.push(`<ul>
26
+ ${f.join(`
27
+ `)}
28
+ </ul>`);continue}if(/^\s*\d+\.\s+/.test(i)){let f=[];for(;r<e.length&&/^\s*\d+\.\s+/.test(e[r]);){let m=[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]);)m.push(e[r]),r++;r<e.length&&e[r].trim()===""&&r++,f.push(`<li>${q(m.join(" ").trim())}</li>`)}n.push(`<ol>
29
+ ${f.join(`
30
+ `)}
31
+ </ol>`);continue}let c=[i];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&&De(e[r+1]));)c.push(e[r]),r++;n.push(`<p>${q(c.join(" "))}</p>`)}return n.join(`
32
+ `)}function De(t){return t.includes("-")?/^[\s|:-]+$/.test(t):!1}function se(t){let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())}function ht(t){return se(t).map(e=>{let n=e.startsWith(":"),r=e.endsWith(":");return n&&r?"center":r?"right":n?"left":null})}function wt(t,e,n){let r=u=>{let c=e[u];return c?` style="text-align:${c}"`:""},i=t.map((u,c)=>`<th${r(c)}>${q(u)}</th>`).join(""),o=n.map(u=>`<tr>${u.map((f,m)=>`<td${r(m)}>${q(f)}</td>`).join("")}</tr>`).join(`
33
+ `);return`<table>
34
+ <thead><tr>${i}</tr></thead>
35
+ <tbody>
36
+ ${o}
37
+ </tbody>
38
+ </table>`}function q(t){let e=Te(t);return e=e.replace(/`([^`\n]+)`/g,(n,r)=>`<code>${r}</code>`),e=e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(n,r,i)=>`<a href="${Le(i)}">${r}</a>`),e=e.replace(/\*\*([^*\n]+)\*\*/g,(n,r)=>`<strong>${r}</strong>`),e=e.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,(n,r,i)=>`${r}<em>${i}</em>`),e=e.replace(/(^|[\s(])_([^_\n]+)_(?=[\s).,;:!?]|$)/g,(n,r,i)=>`${r}<em>${i}</em>`),e}function Te(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Le(t){return t.replace(/"/g,"&quot;").replace(/&/g,"&amp;")}function ce(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Y=class{backendUri="kanonak.org/transformations/html";render(e,n){let r=$t(e.children);if(n?.omitWrapper){let c=r.endsWith(`
39
+ `)?r:`${r}
40
+ `;return n.trailingNewline===!1&&c.endsWith(`
41
+ `)?c.slice(0,-1):c}let i=St(e.metadata)??"Untitled",o=bt(e.metadata,n),u=`<!DOCTYPE html>
42
+ <html lang="en">
43
+ <head>
44
+ <meta charset="utf-8">
45
+ <title>${I(i)}</title>
46
+ <style>
47
+ 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; }
48
+ h1, h2, h3, h4 { line-height: 1.2; }
49
+ h1 { border-bottom: 1px solid #ddd; padding-bottom: 0.3em; }
50
+ dl.metadata { background: #f6f8fa; border: 1px solid #e4e8ec; border-radius: 6px; padding: 0.75rem 1rem; margin-bottom: 1.5rem; }
51
+ dl.metadata dt { font-weight: 600; color: #555; margin-top: 0.35rem; }
52
+ dl.metadata dt:first-child { margin-top: 0; }
53
+ dl.metadata dd { margin: 0; }
54
+ code { background: #f6f8fa; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.92em; }
55
+ pre { background: #f6f8fa; border: 1px solid #e4e8ec; border-radius: 6px; padding: 0.8rem 1rem; overflow-x: auto; }
56
+ pre code { background: transparent; padding: 0; font-size: 0.88em; }
57
+ p { margin: 0.85em 0; }
58
+ table { border-collapse: collapse; width: 100%; margin: 1em 0; font-size: 0.93em; }
59
+ table th, table td { border: 1px solid #d0d7de; padding: 0.4em 0.7em; text-align: left; vertical-align: top; }
60
+ table th { background: #f6f8fa; font-weight: 600; }
61
+ table tr:nth-child(even) td { background: #fafbfc; }
62
+ figure.svg-figure { margin: 1.5em 0; text-align: center; }
63
+ figure.svg-figure svg { max-width: 100%; height: auto; }
64
+ </style>
65
+ </head>
66
+ <body>
67
+ ${o}${r}
68
+ </body>
69
+ </html>
70
+ `;return n?.trailingNewline===!1&&u.endsWith(`
71
+ `)?u.slice(0,-1):u}};function St(t){if(t){for(let e of t.entries)if((e.key==="title"||e.key==="name")&&e.value.kind==="StringScalar")return e.value.stringValue}}function bt(t,e){if(!t||t.entries.length===0)return"";let n=e?.metadataKeys??t.entries.map(o=>o.key),r=new Map(t.entries.map(o=>[o.key,o])),i=[];for(let o of n){let u=r.get(o);if(!u)continue;let c=e?.metadataRenames.get(o)??o,f=Ce(u.value);f!==void 0&&i.push(` <dt>${I(c)}</dt>
72
+ <dd>${f}</dd>`)}return i.length===0?"":`<dl class="metadata">
73
+ ${i.join(`
74
+ `)}
75
+ </dl>
76
+ `}function Ce(t){switch(t.kind){case"StringScalar":return I(t.stringValue);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let e=[];for(let n of t.items){let r=Ce(n);r!==void 0&&e.push(`<code>${r}</code>`)}return e.join(", ")}case"StructuredMap":return;default:return}}function $t(t){let e=[];for(let n of t){let r=Ue(n);r&&e.push(r)}return e.join(`
77
+ `)}function Ue(t){switch(t.kind){case"Heading":{let e=Math.max(1,Math.min(6,t.level));return`<h${e}>${fe(t.inlines)}</h${e}>`}case"Paragraph":return`<p>${fe(t.inlines)}</p>`;case"RawBlock":return Vt(t);case"PropertyList":return Et(t);default:return""}}function Et(t){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let e=[];for(let n of t.propertyEntries){let r=`<dt>${I(n.propertyKey)}</dt>`,i=`<dd>${vt(n.propertyValue)}</dd>`;e.push(r,i)}return`<dl class="property-list">
78
+ ${e.join(`
79
+ `)}
80
+ </dl>`}function vt(t){if(!t||t.length===0)return"";let e=[];for(let n of t){let r=n;!r||typeof r!="object"||!r.kind||(r.kind==="Text"||r.kind==="ResourceLink"?e.push(fe([r])):e.push(Ue(r)))}return e.join("")}function Vt(t){let e=t.mediaType;return e&&ce(e,T.TEXT_MARKDOWN)?ue(t.rawContent):e&&ce(e,T.TEXT_HTML)?t.rawContent:e&&ce(e,T.IMAGE_SVG_XML)?`<figure class="svg-figure">
81
+ ${t.rawContent}
82
+ </figure>`:`<pre${e?` class="media-${Be(e.name)}"`:""}><code>${I(t.rawContent)}</code></pre>`}function fe(t){let e=[];for(let n of t)n.kind==="Text"?e.push(I(n.text)):n.kind==="ResourceLink"&&e.push(jt(n));return e.join("")}function jt(t){let n=t.target?.subject;if(!n||!n.publisher||!n.package_||!n.name)return I(t.linkLabel??"[unresolved link]");let r=n.version,i=r?`@${r.major}.${r.minor}.${r.patch}`:"",o=`${n.publisher}/${n.package_}${i}/${n.name}`,u=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:n.name;return`<a class="kan-link" kan-href="${Be(o)}">${I(u)}</a>`}function I(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Be(t){return t.replace(/"/g,"&quot;").replace(/&/g,"&amp;")}function At(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Z=class{backendUri="kanonak.org/transformations/svg";render(e,n){for(let r of e.children)if(r.kind==="RawBlock"&&r.mediaType&&At(r.mediaType,T.IMAGE_SVG_XML)){let i=r.rawContent;return n?.trailingNewline&&!i.endsWith(`
83
+ `)&&(i+=`
84
+ `),i}return'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'}};var Q=class{constructor(e,n,r){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;cache=new Map;async resolveSubject(e,n){let r=_(n,e);if(r)return r;let i=e.version,o=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"",u=`${e.publisher}/${e.package_}${o}`,c=this.cache.get(u);if(!c){let m=await this.repository.getDocumentsByNamespaceAsync(e.publisher,e.package_);if(m.length===0)return;let g=i&&typeof i.major=="number"?m.find(A=>{let b=A.metadata?.namespace_?.version;return b&&b.major===i.major&&b.minor===i.minor&&b.patch===i.patch})??m[0]:m[0],k=new Ee(g,this.repository);c=await this.objectParser.parseKanonaks(k),this.cache.set(u,c)}let f=_(c,e);if(f)return f;for(let m of c)if(m instanceof E&&m.name===e.name)return m}};var Kt="kanonak.org",Dt="transformations",Sn=3,s=t=>({publisher:Kt,package_:Dt,name:t}),a={Transformation:s("Transformation"),InstanceTransformation:s("InstanceTransformation"),SetTransformation:s("SetTransformation"),inputPattern:s("inputPattern"),rule:s("rule"),artifactName:s("artifactName"),outputs:s("outputs"),formatOverrides:s("formatOverrides"),partitionBy:s("partitionBy"),InputPattern:s("InputPattern"),matchesClass:s("matchesClass"),requires:s("requires"),sortBy:s("sortBy"),SortKey:s("SortKey"),byProperty:s("byProperty"),order:s("order"),SortOrder:s("SortOrder"),ascending:s("ascending"),descending:s("descending"),OutputFormat:s("OutputFormat"),backendUri:s("backendUri"),FormatOverride:s("FormatOverride"),formatTarget:s("formatTarget"),metadataKeys:s("metadataKeys"),metadataRenames:s("metadataRenames"),trailingNewline:s("trailingNewline"),omitWrapper:s("omitWrapper"),RenameEntry:s("RenameEntry"),fromKey:s("fromKey"),toKey:s("toKey"),FMT_MARKDOWN_FRONTMATTER:s("markdown-with-frontmatter"),FMT_PLAIN_MARKDOWN:s("plain-markdown"),FMT_TOML:s("toml"),FMT_JSON:s("json"),FMT_HTML:s("html"),FMT_SVG:s("svg"),Expression:s("Expression"),ListSourcedExpression:s("ListSourcedExpression"),ListAggregate:s("ListAggregate"),IteratingExpression:s("IteratingExpression"),BuildAstNode:s("BuildAstNode"),astClass:s("astClass"),set:s("set"),AstFieldBinding:s("AstFieldBinding"),field:s("field"),bindValue:s("bindValue"),When:s("When"),condition:s("condition"),thenBuild:s("thenBuild"),elseBuild:s("elseBuild"),Concat:s("Concat"),parts:s("parts"),Fallback:s("Fallback"),primary:s("primary"),alternate:s("alternate"),StringLiteral:s("StringLiteral"),stringLiteral:s("stringLiteral"),IntegerLiteral:s("IntegerLiteral"),integerLiteral:s("integerLiteral"),DecimalLiteral:s("DecimalLiteral"),decimalLiteral:s("decimalLiteral"),BooleanLiteral:s("BooleanLiteral"),booleanLiteral:s("booleanLiteral"),VarRef:s("VarRef"),varName:s("varName"),PropertyRead:s("PropertyRead"),readSource:s("readSource"),readProp:s("readProp"),Traverse:s("Traverse"),traverseSource:s("traverseSource"),through:s("through"),step:s("step"),UriName:s("UriName"),uriNameOf:s("uriNameOf"),UriPublisher:s("UriPublisher"),uriPublisherOf:s("uriPublisherOf"),UriPackage:s("UriPackage"),uriPackageOf:s("uriPackageOf"),UriVersion:s("UriVersion"),uriVersionOf:s("uriVersionOf"),SubjectUri:s("SubjectUri"),subjectOf:s("subjectOf"),UriLiteral:s("UriLiteral"),refTo:s("refTo"),DisplayLabel:s("DisplayLabel"),labelTarget:s("labelTarget"),labelSource:s("labelSource"),ResolveRef:s("ResolveRef"),resolveSource:s("resolveSource"),Normalize:s("Normalize"),normSource:s("normSource"),normKind:s("normKind"),NormalizeKind:s("NormalizeKind"),NORM_TRIM_END:s("trim-end"),IsSet:s("IsSet"),checkExpr:s("checkExpr"),ExpressionFragment:s("ExpressionFragment"),body:s("body"),CallFragment:s("CallFragment"),fragmentRef:s("fragmentRef"),source:s("source"),Join:s("Join"),separator:s("separator"),Count:s("Count"),Sum:s("Sum"),Min:s("Min"),Max:s("Max"),Average:s("Average"),loopVar:s("loopVar"),ForEach:s("ForEach"),emit:s("emit"),ListMap:s("ListMap"),mapBody:s("mapBody"),Filter:s("Filter"),predicate:s("predicate"),PartitionBy:s("PartitionBy"),partitionKey:s("partitionKey"),DistinctBy:s("DistinctBy"),distinctKey:s("distinctKey"),Partition:s("Partition"),key:s("key"),members:s("members"),AllStatements:s("AllStatements"),statementsOf:s("statementsOf"),StatementPredicate:s("StatementPredicate"),predicateOf:s("predicateOf"),StatementValue:s("StatementValue"),valueOf:s("valueOf"),DateFormat:s("DateFormat"),dateSource:s("dateSource"),dateFormat:s("dateFormat"),BinaryArithmetic:s("BinaryArithmetic"),arithLeft:s("arithLeft"),arithRight:s("arithRight"),Add:s("Add"),Subtract:s("Subtract"),Multiply:s("Multiply"),Divide:s("Divide"),Reverse:s("Reverse"),WindowedMap:s("WindowedMap"),windowSize:s("windowSize"),windowVar:s("windowVar"),windowBody:s("windowBody"),PairwiseMap:s("PairwiseMap"),firstVar:s("firstVar"),secondVar:s("secondVar"),pairBody:s("pairBody"),Scan:s("Scan"),initialState:s("initialState"),stateVar:s("stateVar"),elementVar:s("elementVar"),accumulate:s("accumulate"),ListItemAt:s("ListItemAt"),itemIndex:s("itemIndex"),BinaryComparison:s("BinaryComparison"),compareLeft:s("compareLeft"),compareRight:s("compareRight"),Equals:s("Equals"),GreaterThan:s("GreaterThan"),LessThan:s("LessThan"),GreaterThanOrEqual:s("GreaterThanOrEqual"),LessThanOrEqual:s("LessThanOrEqual"),Not:s("Not"),operand:s("operand"),BooleanLogic:s("BooleanLogic"),operands:s("operands"),And:s("And"),Or:s("Or"),Contains:s("Contains"),haystack:s("haystack"),needle:s("needle"),UnaryNumericOp:s("UnaryNumericOp"),value:s("value"),Abs:s("Abs"),Negate:s("Negate"),KindPredicate:s("KindPredicate"),IsReference:s("IsReference"),IsEmbedded:s("IsEmbedded"),IsList:s("IsList"),kindCheck:s("kindCheck"),StatementObject:s("StatementObject"),statementSource:s("statementSource")};var y=class extends Error{constructor(n,r){super(`${n} (at ${r})`);this.path=r}path},Re=16;function ne(t,e){let n=t.name,r={catalog:e,depth:0};if(d(t,a.InstanceTransformation))return Tt(t,n,r);if(d(t,a.SetTransformation))return Lt(t,n,r);throw new y("Subject is not a recognized v3 transformation type \u2014 expected InstanceTransformation or SetTransformation",n)}function Tt(t,e,n){return{kind:"instance",name:t.name,inputPattern:Fe(t,e),rule:te(t,a.rule,`${e}.rule`,n),artifactName:te(t,a.artifactName,`${e}.artifactName`,n),outputs:Ne(t,`${e}.outputs`),overrides:qe(t,`${e}.formatOverrides`,n)}}function Lt(t,e,n){let r=M(t,a.partitionBy);return{kind:"set",name:t.name,inputPattern:Fe(t,e),rule:te(t,a.rule,`${e}.rule`,n),artifactName:te(t,a.artifactName,`${e}.artifactName`,n),outputs:Ne(t,`${e}.outputs`),overrides:qe(t,`${e}.formatOverrides`,n),partitionBy:r}}function Fe(t,e){let n=x(t,a.inputPattern);if(!n)throw new y("inputPattern is required",e);return Ct(n,`${e}.inputPattern`)}function Ct(t,e){let n=M(t,a.matchesClass);if(!n)throw new y("matchesClass is required",e);let r=[];for(let u of j(t,a.requires))if(u instanceof v)r.push(me(u.object.subject));else if(u instanceof w)for(let c of u.object)c instanceof h&&r.push(me(c.subject));let i=[],o=0;for(let u of j(t,a.sortBy))if(u instanceof w)for(let c of u.object)c instanceof B&&i.push(Pe(c,`${e}.sortBy[${o++}]`));else u instanceof K&&i.push(Pe(u.object,`${e}.sortBy[${o++}]`));return{matchesClass:n,requires:r,sortBy:i}}function Pe(t,e){let n=M(t,a.byProperty);if(!n)throw new y("SortKey.byProperty is required",e);let r=M(t,a.order);if(!r)throw new y("SortKey.order is required",e);if($(r,a.ascending))return{byProperty:n,order:"ascending"};if($(r,a.descending))return{byProperty:n,order:"descending"};throw new y(`SortKey.order must reference tx.ascending or tx.descending; got ${r.publisher}/${r.package_}/${r.name}`,e)}function te(t,e,n,r){let i=x(t,e);if(!i)throw new y("expression is required",n);return z(i,n,r)}function z(t,e,n){if(d(t,a.StringLiteral))return{kind:"string-literal",value:V(t,a.stringLiteral,e)};if(d(t,a.IntegerLiteral))return{kind:"integer-literal",value:_e(t,a.integerLiteral,e)};if(d(t,a.DecimalLiteral))return{kind:"decimal-literal",value:_e(t,a.decimalLiteral,e)};if(d(t,a.BooleanLiteral))return{kind:"boolean-literal",value:_t(t,a.booleanLiteral,e)};if(d(t,a.VarRef))return{kind:"var-ref",varName:V(t,a.varName,e)};if(d(t,a.PropertyRead))return{kind:"property-read",source:l(t,a.readSource,`${e}.readSource`,n),readProp:F(t,a.readProp,e,"readProp")};if(d(t,a.Traverse))return{kind:"traverse",source:l(t,a.traverseSource,`${e}.traverseSource`,n),through:F(t,a.through,e,"through"),step:l(t,a.step,`${e}.step`,n)};if(d(t,a.BuildAstNode))return{kind:"build-ast-node",astClass:F(t,a.astClass,e,"astClass"),set:Bt(t,`${e}.set`,n)};if(d(t,a.When))return{kind:"when",condition:l(t,a.condition,`${e}.condition`,n),thenBuild:l(t,a.thenBuild,`${e}.thenBuild`,n),elseBuild:Ut(t,a.elseBuild,`${e}.elseBuild`,n)};if(d(t,a.Concat))return{kind:"concat",parts:le(t,a.parts,`${e}.parts`,n)};if(d(t,a.Fallback))return{kind:"fallback",primary:l(t,a.primary,`${e}.primary`,n),alternate:l(t,a.alternate,`${e}.alternate`,n)};if(d(t,a.UriName))return{kind:"uri-name",source:l(t,a.uriNameOf,`${e}.uriNameOf`,n)};if(d(t,a.UriPublisher))return{kind:"uri-publisher",source:l(t,a.uriPublisherOf,`${e}.uriPublisherOf`,n)};if(d(t,a.UriPackage))return{kind:"uri-package",source:l(t,a.uriPackageOf,`${e}.uriPackageOf`,n)};if(d(t,a.UriVersion))return{kind:"uri-version",source:l(t,a.uriVersionOf,`${e}.uriVersionOf`,n)};if(d(t,a.SubjectUri))return{kind:"subject-uri",source:l(t,a.subjectOf,`${e}.subjectOf`,n)};if(d(t,a.UriLiteral))return{kind:"uri-literal",refTo:F(t,a.refTo,e,"refTo")};if(d(t,a.DisplayLabel))return{kind:"display-label",labelTarget:F(t,a.labelTarget,e,"labelTarget"),labelSource:F(t,a.labelSource,e,"labelSource")};if(d(t,a.ResolveRef))return{kind:"resolve-ref",source:l(t,a.resolveSource,`${e}.resolveSource`,n)};if(d(t,a.Normalize))return{kind:"normalize",source:l(t,a.normSource,`${e}.normSource`,n),normKind:Rt(t,e)};if(d(t,a.IsSet))return{kind:"is-set",check:l(t,a.checkExpr,`${e}.checkExpr`,n)};if(d(t,a.CallFragment))return It(t,e,n);if(d(t,a.Join))return{kind:"join",source:l(t,a.source,`${e}.source`,n),separator:V(t,a.separator,e)};if(d(t,a.Count))return{kind:"count",source:l(t,a.source,`${e}.source`,n)};if(d(t,a.Sum))return{kind:"sum",source:l(t,a.source,`${e}.source`,n)};if(d(t,a.Min))return{kind:"min",source:l(t,a.source,`${e}.source`,n)};if(d(t,a.Max))return{kind:"max",source:l(t,a.source,`${e}.source`,n)};if(d(t,a.Average))return{kind:"average",source:l(t,a.source,`${e}.source`,n)};if(d(t,a.ForEach))return{kind:"for-each",source:l(t,a.source,`${e}.source`,n),loopVar:V(t,a.loopVar,e),emit:l(t,a.emit,`${e}.emit`,n)};if(d(t,a.ListMap))return{kind:"list-map",source:l(t,a.source,`${e}.source`,n),loopVar:V(t,a.loopVar,e),mapBody:l(t,a.mapBody,`${e}.mapBody`,n)};if(d(t,a.Filter))return{kind:"filter",source:l(t,a.source,`${e}.source`,n),loopVar:V(t,a.loopVar,e),predicate:l(t,a.predicate,`${e}.predicate`,n)};if(d(t,a.PartitionBy))return{kind:"partition-by",source:l(t,a.source,`${e}.source`,n),loopVar:V(t,a.loopVar,e),partitionKey:l(t,a.partitionKey,`${e}.partitionKey`,n)};if(d(t,a.DistinctBy))return{kind:"distinct-by",source:l(t,a.source,`${e}.source`,n),loopVar:V(t,a.loopVar,e),distinctKey:l(t,a.distinctKey,`${e}.distinctKey`,n)};if(d(t,a.AllStatements))return{kind:"all-statements",source:l(t,a.statementsOf,`${e}.statementsOf`,n)};if(d(t,a.StatementPredicate))return{kind:"statement-predicate",source:l(t,a.predicateOf,`${e}.predicateOf`,n)};if(d(t,a.StatementValue))return{kind:"statement-value",source:l(t,a.valueOf,`${e}.valueOf`,n)};if(d(t,a.DateFormat))return{kind:"date-format",source:l(t,a.dateSource,`${e}.dateSource`,n),format:Pt(t,e)};if(d(t,a.Add))return{kind:"add",left:l(t,a.arithLeft,`${e}.arithLeft`,n),right:l(t,a.arithRight,`${e}.arithRight`,n)};if(d(t,a.Subtract))return{kind:"subtract",left:l(t,a.arithLeft,`${e}.arithLeft`,n),right:l(t,a.arithRight,`${e}.arithRight`,n)};if(d(t,a.Multiply))return{kind:"multiply",left:l(t,a.arithLeft,`${e}.arithLeft`,n),right:l(t,a.arithRight,`${e}.arithRight`,n)};if(d(t,a.Divide))return{kind:"divide",left:l(t,a.arithLeft,`${e}.arithLeft`,n),right:l(t,a.arithRight,`${e}.arithRight`,n)};if(d(t,a.Reverse))return{kind:"reverse",source:l(t,a.source,`${e}.source`,n)};if(d(t,a.WindowedMap)){let r=We(t,a.windowSize);if(r===void 0||!Number.isInteger(r)||r<1)throw new y("windowSize must be a positive integer",`${e}.windowSize`);return{kind:"windowed-map",source:l(t,a.source,`${e}.source`,n),windowSize:r,windowVar:V(t,a.windowVar,e),windowBody:l(t,a.windowBody,`${e}.windowBody`,n)}}if(d(t,a.PairwiseMap))return{kind:"pairwise-map",source:l(t,a.source,`${e}.source`,n),firstVar:V(t,a.firstVar,e),secondVar:V(t,a.secondVar,e),pairBody:l(t,a.pairBody,`${e}.pairBody`,n)};if(d(t,a.Scan))return{kind:"scan",source:l(t,a.source,`${e}.source`,n),initialState:l(t,a.initialState,`${e}.initialState`,n),stateVar:V(t,a.stateVar,e),elementVar:V(t,a.elementVar,e),accumulate:l(t,a.accumulate,`${e}.accumulate`,n)};if(d(t,a.ListItemAt))return{kind:"list-item-at",source:l(t,a.source,`${e}.source`,n),itemIndex:l(t,a.itemIndex,`${e}.itemIndex`,n)};if(d(t,a.Equals))return{kind:"equals",left:l(t,a.compareLeft,`${e}.compareLeft`,n),right:l(t,a.compareRight,`${e}.compareRight`,n)};if(d(t,a.GreaterThan))return{kind:"greater-than",left:l(t,a.compareLeft,`${e}.compareLeft`,n),right:l(t,a.compareRight,`${e}.compareRight`,n)};if(d(t,a.LessThan))return{kind:"less-than",left:l(t,a.compareLeft,`${e}.compareLeft`,n),right:l(t,a.compareRight,`${e}.compareRight`,n)};if(d(t,a.GreaterThanOrEqual))return{kind:"greater-than-or-equal",left:l(t,a.compareLeft,`${e}.compareLeft`,n),right:l(t,a.compareRight,`${e}.compareRight`,n)};if(d(t,a.LessThanOrEqual))return{kind:"less-than-or-equal",left:l(t,a.compareLeft,`${e}.compareLeft`,n),right:l(t,a.compareRight,`${e}.compareRight`,n)};if(d(t,a.Not))return{kind:"not",operand:l(t,a.operand,`${e}.operand`,n)};if(d(t,a.And))return{kind:"and",operands:le(t,a.operands,`${e}.operands`,n)};if(d(t,a.Or))return{kind:"or",operands:le(t,a.operands,`${e}.operands`,n)};if(d(t,a.Contains))return{kind:"contains",haystack:l(t,a.haystack,`${e}.haystack`,n),needle:l(t,a.needle,`${e}.needle`,n)};if(d(t,a.Abs))return{kind:"abs",value:l(t,a.value,`${e}.value`,n)};if(d(t,a.Negate))return{kind:"negate",value:l(t,a.value,`${e}.value`,n)};if(d(t,a.IsReference))return{kind:"is-reference",check:l(t,a.kindCheck,`${e}.kindCheck`,n)};if(d(t,a.IsEmbedded))return{kind:"is-embedded",check:l(t,a.kindCheck,`${e}.kindCheck`,n)};if(d(t,a.IsList))return{kind:"is-list",check:l(t,a.kindCheck,`${e}.kindCheck`,n)};if(d(t,a.StatementObject))return{kind:"statement-object",source:l(t,a.statementSource,`${e}.statementSource`,n)};throw new y("Expression is not of a recognized v3 type \u2014 embedded has no matching subclass of tx.Expression",e)}function l(t,e,n,r){let i=x(t,e);if(!i)throw new y("child expression is required",n);return z(i,n,r)}function Ut(t,e,n,r){let i=x(t,e);if(i)return z(i,n,r)}function le(t,e,n,r){let i=[],o=0;for(let u of j(t,e))if(u instanceof w)for(let c of u.object)c instanceof B&&i.push(z(c,`${n}[${o++}]`,r));else u instanceof K&&i.push(z(u.object,`${n}[${o++}]`,r));return i}function Bt(t,e,n){let r=[],i=0;for(let o of j(t,a.set))if(o instanceof w)for(let u of o.object)u instanceof B&&r.push(Ie(u,`${e}[${i++}]`,n));else o instanceof K&&r.push(Ie(o.object,`${e}[${i++}]`,n));return r}function Ie(t,e,n){return{field:F(t,a.field,e,"field"),value:l(t,a.bindValue,`${e}.bindValue`,n)}}function Rt(t,e){let n=M(t,a.normKind);if(!n)throw new y("normKind is required",e);if($(n,a.NORM_TRIM_END))return"trim-end";throw new y(`Unknown NormalizeKind: ${n.publisher}/${n.package_}/${n.name}`,e)}var Me=new Set(["iso-date","iso-datetime","short-date","long-date","year","month-year"]);function Pt(t,e){let n=W(t,a.dateFormat);if(!n)throw new y("dateFormat is required",e);if(!Me.has(n))throw new y(`Unknown dateFormat "${n}"; supported: ${[...Me].join(", ")}`,e);return n}function It(t,e,n){if(n.depth>=Re)throw new y(`Fragment recursion exceeded MAX_FRAGMENT_DEPTH (${Re})`,e);let r=M(t,a.fragmentRef);if(!r)throw new y("fragmentRef is required",e);let i=Mt(n.catalog,r);if(!i)throw new y(`ExpressionFragment not found: ${r.publisher}/${r.package_}/${r.name}`,e);let o=x(i,a.body);if(!o)throw new y(`ExpressionFragment ${r.name} has no body`,e);return{kind:"call-fragment",body:z(o,`${e}.fragment(${r.name})`,{catalog:n.catalog,depth:n.depth+1})}}function Mt(t,e){for(let n of t)if(!(!(n instanceof E)||n.name!==e.name||!(n.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))&&d(n,a.ExpressionFragment))return n}function Ne(t,e){let n=new Set;for(let r of j(t,a.outputs))if(r instanceof v)n.add(r.object.subject.name);else if(r instanceof w)for(let i of r.object)i instanceof h&&n.add(i.subject.name);if(n.size===0)throw new y("outputs is required (at least one OutputFormat)",e);return n}function qe(t,e,n){let r=new Map,i=0;for(let o of j(t,a.formatOverrides))if(o instanceof w){for(let u of o.object)if(u instanceof B){let[c,f]=Oe(u,`${e}[${i++}]`);r.set(c,f)}}else if(o instanceof K){let[u,c]=Oe(o.object,`${e}[${i++}]`);r.set(u,c)}return r}function Oe(t,e){let n=M(t,a.formatTarget);if(!n)throw new y("formatTarget is required",e);let r=[];for(let c of j(t,a.metadataKeys))if(c instanceof D)r.push(c.object);else if(c instanceof w)for(let f of c.object){let m=f.value;typeof m=="string"&&r.push(m)}let i=new Map;for(let c of j(t,a.metadataRenames))if(c instanceof w){for(let f of c.object)if(f instanceof B){let m=W(f,a.fromKey),g=W(f,a.toKey);m&&g&&i.set(m,g)}}else if(c instanceof K){let f=c.object,m=W(f,a.fromKey),g=W(f,a.toKey);m&&g&&i.set(m,g)}let o=de(t,a.trailingNewline),u=de(t,a.omitWrapper);return[n.name,{metadataKeys:r.length>0?r:void 0,metadataRenames:i,trailingNewline:o,omitWrapper:u}]}function Ot(t){return t.predicate?.subject}function j(t,e){let n=[];for(let r of t.statement){let i=Ot(r);i&&$(i,e)&&n.push(r)}return n}function x(t,e){for(let n of j(t,e))if(n instanceof K)return n.object}function M(t,e){for(let n of j(t,e))if(n instanceof v)return me(n.object.subject)}function W(t,e){for(let n of j(t,e))if(n instanceof D)return n.object}function We(t,e){for(let n of j(t,e))if(n instanceof L)return n.object}function de(t,e){for(let n of j(t,e))if(n instanceof C)return n.object}function V(t,e,n){let r=W(t,e);if(r===void 0)throw new y(`${e.name} (string) is required`,n);return r}function _e(t,e,n){let r=We(t,e);if(r===void 0)throw new y(`${e.name} (number) is required`,n);return r}function _t(t,e,n){let r=de(t,e);if(r===void 0)throw new y(`${e.name} (boolean) is required`,n);return r}function F(t,e,n,r){let i=M(t,e);if(!i)throw new y(`${r} (URI reference) is required`,n);return i}function me(t){return{publisher:t.publisher,package_:t.package_,name:t.name}}var R=class extends Error{},ie=class{constructor(e,n){this.resolver=e;this.catalog=n}resolver;catalog;async evaluate(e,n){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(!n.has(e.varName))throw new R(`Unbound variable "${e.varName}"`);return n.get(e.varName)}case"concat":{let r=[];for(let i of e.parts){let o=await this.evaluate(i,n);if(o!=null)if(Array.isArray(o))for(let u of o)r.push(u);else r.push(o)}return r}case"fallback":{let r=await this.evaluate(e.primary,n);return He(r)?r:this.evaluate(e.alternate,n)}case"when":return await this.evaluate(e.condition,n)===!0?this.evaluate(e.thenBuild,n):e.elseBuild?this.evaluate(e.elseBuild,n):void 0;case"is-set":{let r=await this.evaluate(e.check,n);return He(r)}case"property-read":{let r=await this.evaluate(e.source,n);return ze(r,e.readProp)}case"traverse":{let r=await this.evaluate(e.source,n);if(!(r instanceof U))return;let i=Nt(r,e.through),o=[];for(let u of i){let c=await this.resolver.resolveSubject(u,this.catalog);if(!c)continue;let f=new Map(n);f.set("input",c);let m=await this.evaluate(e.step,f);m!=null&&o.push(re(m))}return o.join("")}case"uri-name":{let r=await this.evaluate(e.source,n);return H(r)?r.name:r instanceof h?r.subject.name:r instanceof E?r.name:r instanceof B?r.name??"":void 0}case"uri-publisher":{let r=await this.evaluate(e.source,n);return pe(r)?.publisher}case"uri-package":{let r=await this.evaluate(e.source,n);return pe(r)?.package_}case"uri-version":{let r=await this.evaluate(e.source,n);return pe(r)?.version}case"subject-uri":{let r=await this.evaluate(e.source,n);if(r instanceof E){let i=r.namespace??"",o=r.name??"";return!i||!o?void 0:`${i}/${o}`}if(r instanceof h){let i=r.subject,o=i.version;return o&&typeof o.major=="number"?`${i.publisher}/${i.package_}@${o.major}.${o.minor}.${o.patch}/${i.name}`:`${i.publisher}/${i.package_}/${i.name}`}return}case"display-label":{let r=await this.resolver.resolveSubject({...e.labelTarget},this.catalog);return r?ze(r,e.labelSource):void 0}case"resolve-ref":{let r=await this.evaluate(e.source,n);return r instanceof h?await this.resolver.resolveSubject(r.subject,this.catalog):H(r)?await this.resolver.resolveSubject(r,this.catalog):void 0}case"normalize":{let r=await this.evaluate(e.source,n),i=r==null?"":re(r);return e.normKind==="trim-end"?i.replace(/[\s\r\n]+$/u,""):i}case"build-ast-node":{let r={kind:e.astClass.name};for(let i of e.set){let o=await this.evaluate(i.value,n);if(o==null||Array.isArray(o)&&o.length===0)continue;let u=i.field.name;Array.isArray(o)&&Wt.has(u)&&o.every(c=>zt(c))&&(o=o.map(c=>String(c)).join("")),r[u]=o}return r}case"call-fragment":return this.evaluate(e.body,n);case"join":return(await this.evaluateList(e.source,n)).map(i=>i==null?"":re(i)).join(e.separator);case"count":return(await this.evaluateList(e.source,n)).length;case"sum":{let r=await this.evaluateList(e.source,n),i=0;for(let o of r)i+=S(o,"Sum");return i}case"min":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new R("Min on an empty list is undefined; guard with IsSet");let i=S(r[0],"Min");for(let o=1;o<r.length;o++){let u=S(r[o],"Min");u<i&&(i=u)}return i}case"max":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new R("Max on an empty list is undefined; guard with IsSet");let i=S(r[0],"Max");for(let o=1;o<r.length;o++){let u=S(r[o],"Max");u>i&&(i=u)}return i}case"average":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new R("Average on an empty list is undefined; guard with IsSet");let i=0;for(let o of r)i+=S(o,"Average");return i/r.length}case"for-each":{let r=await this.evaluateList(e.source,n),i=[];for(let o of r){let u=new Map(n);u.set(e.loopVar,o);let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let f of c)i.push(f);else i.push(c)}return i}case"list-map":{let r=await this.evaluateList(e.source,n),i=[];for(let o of r){let u=new Map(n);u.set(e.loopVar,o),i.push(await this.evaluate(e.mapBody,u))}return i}case"filter":{let r=await this.evaluateList(e.source,n),i=[];for(let o of r){let u=new Map(n);u.set(e.loopVar,o),await this.evaluate(e.predicate,u)===!0&&i.push(o)}return i}case"partition-by":{let r=await this.evaluateList(e.source,n),i=new Map,o=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,u);let f=await this.evaluate(e.partitionKey,c),m=Xe(f),g=i.get(m);g||(g={kind:"Partition",key:f,members:[]},i.set(m,g),o.push(m)),g.members.push(u)}return o.map(u=>i.get(u))}case"distinct-by":{let r=await this.evaluateList(e.source,n),i=new Set,o=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,u);let f=await this.evaluate(e.distinctKey,c),m=Xe(f);i.has(m)||(i.add(m),o.push(u))}return o}case"all-statements":{let r=await this.evaluate(e.source,n);return r instanceof U?r.statement:[]}case"statement-predicate":{let r=await this.evaluate(e.source,n);if(ge(r)){let i=r.predicate;if(i instanceof h)return i}return}case"statement-value":{let r=await this.evaluate(e.source,n);return ge(r)?Jt(r):void 0}case"date-format":{let r=await this.evaluate(e.source,n),i=r==null?"":re(r);return i?Gt(i,e.format):""}case"add":{let r=S(await this.evaluate(e.left,n),"Add"),i=S(await this.evaluate(e.right,n),"Add");return r+i}case"subtract":{let r=S(await this.evaluate(e.left,n),"Subtract"),i=S(await this.evaluate(e.right,n),"Subtract");return r-i}case"multiply":{let r=S(await this.evaluate(e.left,n),"Multiply"),i=S(await this.evaluate(e.right,n),"Multiply");return r*i}case"divide":{let r=S(await this.evaluate(e.left,n),"Divide"),i=S(await this.evaluate(e.right,n),"Divide");if(i===0)throw new R("Divide by zero; guard with When");return r/i}case"reverse":{if(e.source.kind==="reverse")return this.evaluate(e.source.source,n);let r=await this.evaluateReverseIterator(e.source,n);return r!==void 0?r:[...await this.evaluateList(e.source,n)].reverse()}case"windowed-map":{let r=await this.evaluateList(e.source,n);if(r.length<e.windowSize)return[];let i=[];for(let o=0;o+e.windowSize<=r.length;o++){let u=r.slice(o,o+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let f=await this.evaluate(e.windowBody,c);if(f!=null)if(Array.isArray(f))for(let m of f)i.push(m);else i.push(f)}return i}case"pairwise-map":{let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let i=[];for(let o=0;o+1<r.length;o++){let u=new Map(n);u.set(e.firstVar,r[o]),u.set(e.secondVar,r[o+1]);let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let f of c)i.push(f);else i.push(c)}return i}case"scan":{let r=await this.evaluateList(e.source,n);if(r.length===0)return[];let i=await this.evaluate(e.initialState,n),o=[];for(let u of r){let c=new Map(n);c.set(e.stateVar,i),c.set(e.elementVar,u);let f=await this.evaluate(e.accumulate,c);o.push(f),i=f}return o}case"list-item-at":{let r=await this.evaluateList(e.source,n),i=await this.evaluate(e.itemIndex,n);return typeof i!="number"||!Number.isInteger(i)||i<0||i>=r.length?void 0:r[i]}case"equals":{let r=await this.evaluate(e.left,n),i=await this.evaluate(e.right,n);return Ge(r,i)}case"greater-than":{let r=await this.evaluate(e.left,n),i=await this.evaluate(e.right,n);return typeof r!="number"||typeof i!="number"?!1:r>i}case"less-than":{let r=await this.evaluate(e.left,n),i=await this.evaluate(e.right,n);return typeof r!="number"||typeof i!="number"?!1:r<i}case"greater-than-or-equal":{let r=await this.evaluate(e.left,n),i=await this.evaluate(e.right,n);return typeof r!="number"||typeof i!="number"?!1:r>=i}case"less-than-or-equal":{let r=await this.evaluate(e.left,n),i=await this.evaluate(e.right,n);return typeof r!="number"||typeof i!="number"?!1:r<=i}case"not":{let r=await this.evaluate(e.operand,n);return r===!0?!1:r===!1?!0:void 0}case"and":{for(let r of e.operands)if(await this.evaluate(r,n)!==!0)return!1;return!0}case"or":{for(let r of e.operands)if(await this.evaluate(r,n)===!0)return!0;return!1}case"contains":{let r=await this.evaluateList(e.haystack,n),i=await this.evaluate(e.needle,n);for(let o of r)if(Ge(o,i))return!0;return!1}case"abs":{let r=S(await this.evaluate(e.value,n),"Abs");return Math.abs(r)}case"negate":return-S(await this.evaluate(e.value,n),"Negate");case"is-reference":return await this.evaluate(e.check,n)instanceof h;case"is-embedded":return await this.evaluate(e.check,n)instanceof B;case"is-list":{let r=await this.evaluate(e.check,n);return Array.isArray(r)}case"statement-object":{let r=await this.evaluate(e.source,n);if(!ge(r))return;let i=r;return i instanceof D||i instanceof L||i instanceof C||i instanceof v||i instanceof K||i instanceof w?i.object:void 0}default:{let r=e;throw new R("Unknown expression kind")}}}async evaluateList(e,n){let r=await this.evaluate(e,n);return r==null?[]:Array.isArray(r)?r:[r]}async evaluateReverseIterator(e,n){if(e.kind==="pairwise-map"){let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let i=[];for(let o=r.length-1;o>=1;o--){let u=new Map(n);u.set(e.firstVar,r[o-1]),u.set(e.secondVar,r[o]);let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let f of c)i.push(f);else i.push(c)}return i}if(e.kind==="for-each"){let r=await this.evaluateList(e.source,n),i=[];for(let o=r.length-1;o>=0;o--){let u=new Map(n);u.set(e.loopVar,r[o]);let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let f of c)i.push(f);else i.push(c)}return i}if(e.kind==="list-map"){let r=await this.evaluateList(e.source,n),i=[];for(let o=r.length-1;o>=0;o--){let u=new Map(n);u.set(e.loopVar,r[o]),i.push(await this.evaluate(e.mapBody,u))}return i}if(e.kind==="windowed-map"){let r=await this.evaluateList(e.source,n);if(r.length<e.windowSize)return[];let i=[];for(let o=r.length-e.windowSize;o>=0;o--){let u=r.slice(o,o+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let f=await this.evaluate(e.windowBody,c);if(f!=null)if(Array.isArray(f))for(let m of f)i.push(m);else i.push(f)}return i}}};function ze(t,e){if(t instanceof U)return Ft(t,e);if(qt(t))return $(e,a.key)?t.key:$(e,a.members)?t.members:void 0}function Ft(t,e){for(let n of t.statement){let r=Ye(n);if(!(!r||!$(r,e))&&(n instanceof D||n instanceof L||n instanceof C||n instanceof v||n instanceof K||n instanceof w))return n.object}}function Nt(t,e){let n=[];for(let r of t.statement){let i=Ye(r);if(!(!i||!$(i,e))){if(r instanceof v)n.push(r.object.subject);else if(r instanceof w)for(let o of r.object)o instanceof h&&n.push(o.subject)}}return n}function Ye(t){return t.predicate?.subject}function re(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(t instanceof U)return t.name??"";if(t instanceof h)return t.subject.name;if(H(t))return t.name;let e=t.value;return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function He(t){return t==null?!1:typeof t=="string"||Array.isArray(t)?t.length>0:typeof t=="boolean"?t===!0:!0}function H(t){return typeof t=="object"&&t!==null&&typeof t.publisher=="string"&&typeof t.package_=="string"&&typeof t.name=="string"}function qt(t){return typeof t=="object"&&t!==null&&t.kind==="Partition"&&Array.isArray(t.members)}function S(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;throw new R(`${e} requires numeric elements; got ${Ht(t)}`)}function pe(t){if(t instanceof E){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);return n<0||r<0?void 0:{publisher:e.substring(0,n),package_:e.substring(n+1,r),version:e.substring(r+1),name:t.name??""}}if(t instanceof h){let e=t.subject,n=e.version;return{publisher:e.publisher,package_:e.package_,version:n&&typeof n.major=="number"?`${n.major}.${n.minor}.${n.patch}`:"",name:e.name}}if(H(t))return{publisher:t.publisher,package_:t.package_,version:"",name:t.name}}var Wt=new Set(["stringValue","text","rawContent","key","propertyKey","linkLabel"]);function zt(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function Ht(t){return t===void 0?"undefined":t===null?"null":Array.isArray(t)?`array(${t.length})`:typeof t}function Gt(t,e){let n=new Date(t);if(isNaN(n.getTime()))return"";let r=n.getUTCFullYear(),i=["January","February","March","April","May","June","July","August","September","October","November","December"][n.getUTCMonth()],o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getUTCMonth()],u=n.getUTCDate(),c=(f,m=2)=>String(f).padStart(m,"0");switch(e){case"iso-date":return`${r}-${c(n.getUTCMonth()+1)}-${c(u)}`;case"iso-datetime":return`${r}-${c(n.getUTCMonth()+1)}-${c(u)}T${c(n.getUTCHours())}:${c(n.getUTCMinutes())}:${c(n.getUTCSeconds())}Z`;case"short-date":return`${o} ${u}`;case"long-date":return`${i} ${u}, ${r}`;case"year":return String(r);case"month-year":return`${i} ${r}`}}function Ge(t,e){if(t==null||e===void 0||e===null)return!1;if(t===e)return!0;let n=typeof t=="object"&&"value"in t?t.value:void 0,r=typeof e=="object"&&"value"in e?e.value:void 0,i=n??t,o=r??e,u=Je(t),c=Je(e);return u&&c?u.publisher===c.publisher&&u.package_===c.package_&&u.name===c.name:typeof i=="string"&&typeof o=="string"||typeof i=="number"&&typeof o=="number"||typeof i=="boolean"&&typeof o=="boolean"?i===o:!1}function Je(t){if(t instanceof h){let e=t.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}if(t instanceof E){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);if(n<0)return;let i=e.substring(0,n),o=r>=0?e.substring(n+1,r):e.substring(n+1);return{publisher:i,package_:o,name:t.name??""}}if(H(t))return{publisher:t.publisher,package_:t.package_,name:t.name}}function ge(t){return t instanceof D||t instanceof L||t instanceof C||t instanceof v||t instanceof K||t instanceof w}function Jt(t){return t instanceof D||t instanceof L||t instanceof C?String(t.object??""):t instanceof v?t.object?.subject?.name??"":t instanceof K?"[embedded]":t instanceof w?(t.object??[]).map(n=>{if(n instanceof h)return n.subject.name;let r=n.name;if(r&&r.length>0)return r;let i=n.value;return typeof i=="string"||typeof i=="number"||typeof i=="boolean"?String(i):"[embedded]"}).join(", "):""}function Xe(t){if(t===void 0)return"\0undef";if(t===null)return"\0null";if(typeof t=="string")return`s:${t}`;if(typeof t=="number")return`n:${t}`;if(typeof t=="boolean")return`b:${t}`;if(t instanceof h){let e=t.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(t instanceof U){let e=t.name??"";return`k:${t.namespace??""}/${e}`}return H(t)?`u:${t.publisher}/${t.package_}/${t.name}`:`o:${JSON.stringify(t)}`}var Xt={"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"}},O=class extends Error{},ae=class{backends=new Map;constructor(){this.register(new G),this.register(new J),this.register(new X),this.register(new Y),this.register(new Z)}register(e){this.backends.set(e.backendUri,e)}async run(e){let n=e.transformationKanonaks??e.allKanonaks,r=ne(e.transformation,n);if(!r.outputs.has(e.outputFormat))throw new O(`Transformation "${r.name}" does not declare output format "${e.outputFormat}". Declared: ${Array.from(r.outputs).join(", ")}`);let i=this.findBackend(e.outputFormat);if(!i)throw new O(`No backend registered for OutputFormat "${e.outputFormat}".`);let o=new Q(e.repository,e.parser,e.objectParser),u=new ie(o,e.allKanonaks);return r.kind==="instance"?this.runInstance(r,e,i,u):this.runSet(r,e,i,u)}async runInstance(e,n,r,i){let o=Ze(n.instances,e.inputPattern.requires),u=Qe(o,e.inputPattern.sortBy),c=[];for(let f of u){let m=new Map;m.set("input",f);let g=await i.evaluate(e.rule,m);ye(g,e.name,`input "${f.name}"`);let k=ke(await i.evaluate(e.artifactName,m),e.name,`input "${f.name}"`),A=e.overrides.get(n.outputFormat),b=r.render(g,A);c.push({fileName:k,format:n.outputFormat,content:b,source:{kind:"instance",sourceName:f.name}})}return c}async runSet(e,n,r,i){let o=Ze(n.instances,e.inputPattern.requires),u=Qe(o,e.inputPattern.sortBy);return e.partitionBy?this.runSetWithPartition(e,u,n,r,i):this.runSetSingle(e,u,n,r,i)}async runSetSingle(e,n,r,i,o){let u=new Map;u.set("inputs",n);let c=await o.evaluate(e.rule,u);ye(c,e.name,"set");let f=ke(await o.evaluate(e.artifactName,u),e.name,"set"),m=e.overrides.get(r.outputFormat),g=i.render(c,m);return[{fileName:f,format:r.outputFormat,content:g,source:{kind:"set",memberCount:n.length}}]}async runSetWithPartition(e,n,r,i,o){let u=e.partitionBy,c=new Map,f=[];for(let g of n){let k=Qt(g,u);if(k==null)continue;let A=xt(k),b=c.get(A);b||(b={keyValue:k,keyDisplay:en(k),members:[]},c.set(A,b),f.push(A)),b.members.push(g)}let m=[];for(let g of f){let k=c.get(g),A=new Map;A.set("inputs",k.members),A.set("key",k.keyValue);let b=await o.evaluate(e.rule,A);ye(b,e.name,`partition "${k.keyDisplay}"`);let nt=ke(await o.evaluate(e.artifactName,A),e.name,`partition "${k.keyDisplay}"`),rt=e.overrides.get(r.outputFormat),it=i.render(b,rt);m.push({fileName:nt,format:r.outputFormat,content:it,source:{kind:"set",memberCount:k.members.length,partitionKey:k.keyDisplay}})}return m}findBackend(e){let n=Xt[e];if(n)return this.backends.get(n.formatUri)}};function Ze(t,e){return e.length===0?t:t.filter(n=>{for(let r of e)if(!Zt(n,r))return!1;return!0})}function Qe(t,e){if(e.length===0)return t;let n=[...t];return n.sort((r,i)=>{for(let o of e){let u=xe(r,o.byProperty),c=xe(i,o.byProperty),f=Yt(u,c,o.order);if(f!==0)return f}return 0}),n}function xe(t,e){for(let n of t.statement){let r=he(n);if(!(!r||!$(r,e))){if(n instanceof D||n instanceof L||n instanceof C)return n.object;if(n instanceof w)throw new O(`Sort property "${e.name}" on instance "${t.name??"?"}" resolves to a list \u2014 list-typed properties are not sortable. Use a scalar property.`);if(n instanceof v)throw new O(`Sort property "${e.name}" on instance "${t.name??"?"}" resolves to a reference \u2014 reference-typed properties don't have a natural total order. Use a scalar property.`)}}}function Yt(t,e,n){if(t===void 0&&e===void 0)return 0;if(t===void 0)return n==="ascending"?1:-1;if(e===void 0)return n==="ascending"?-1:1;let r;return typeof t=="number"&&typeof e=="number"?r=t-e:r=String(t).localeCompare(String(e)),n==="ascending"?r:-r}function Zt(t,e){for(let n of t.statement){let r=he(n);if(!r||!$(r,e))continue;let i=n.object;if(i!=null&&!(typeof i=="string"&&i.length===0)&&!(Array.isArray(i)&&i.length===0))return!0}return!1}function Qt(t,e){for(let n of t.statement){let r=he(n);if(!(!r||!$(r,e))&&(n instanceof D||n instanceof L||n instanceof C||n instanceof v||n instanceof w))return n.object}}function he(t){return t.predicate?.subject}function xt(t){if(t===void 0)return" undef";if(t===null)return" null";if(typeof t=="string")return`s:${t}`;if(typeof t=="number")return`n:${t}`;if(typeof t=="boolean")return`b:${t}`;if(t instanceof h){let e=t.subject;return`r:${e.publisher}/${e.package_}/${e.name}`}if(t instanceof U){let e=t.name??"";return`k:${t.namespace??""}/${e}`}if(typeof t=="object"&&t!==null&&typeof t.name=="string"&&typeof t.publisher=="string"){let e=t;return`u:${e.publisher}/${e.package_}/${e.name}`}return`o:${JSON.stringify(t)}`}function en(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):t instanceof h?t.subject.name:t instanceof U?t.name??"":typeof t=="object"&&t!==null&&typeof t.name=="string"?t.name:""}function ye(t,e,n){if(typeof t!="object"||t===null||t.kind!=="Document")throw new O(`Transformation "${e}" rule did not yield a Document for ${n}. Got: ${et(t)}`)}function ke(t,e,n){if(typeof t=="string")return t;if(Array.isArray(t)&&t.every(tn))return t.map(r=>String(r)).join("");throw new O(`Transformation "${e}" artifactName did not yield a string for ${n}. Got: ${et(t)}`)}function tn(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function et(t){if(t===void 0)return"undefined";if(t===null)return"null";if(Array.isArray(t))return`array(${t.length})`;if(typeof t=="object"){let e=t.kind;return e?`object(kind=${e})`:"object"}return typeof t}var P=class extends Error{constructor(n,r){super(n);this.cause=r;this.name="RenderError"}cause},tt={publisher:"kanonak.org",package_:"derivation",name:"default"},we=class{constructor(e,n=new Se,r=new be){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;runner=new ae;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async findDerivation(e){let n=await this.getCatalog(),r=_(n,e.resource);if(!(r instanceof E))return;let i=e.variant??tt;return $e(r,e.format,i,n)}async render(e){let n=await this.findDerivation(e);if(!n)throw new P(`No derivation found for ${N(e.resource)} \u2192 format ${N(e.format)}`+(e.variant?` variant ${N(e.variant)}`:""));return this.runTransformation({transformation:{publisher:n.transformation.publisher,package_:n.transformation.package_,name:n.transformation.name},input:e.resource,format:e.format})}async runTransformation(e){let n=await this.getCatalog(),r=_(n,e.transformation);if(!(r instanceof E))throw new P(`Transformation not found: ${N(e.transformation)}`);let i=_(n,e.input);if(!(i instanceof E))throw new P(`Input resource not found: ${N(e.input)}`);let o=ne(r,n),u=nn(o.outputs,e.format);if(!u)throw new P(`Transformation ${N(e.transformation)} declares outputs [${[...o.outputs].join(", ")}], none of which corresponds to format ${N(e.format)}`);let c;try{c=await this.runner.run({transformation:r,instances:[i],allKanonaks:n,repository:this.repository,parser:this.parser,objectParser:this.objectParser,outputFormat:u})}catch(f){throw new P(`Transformation execution failed: ${f.message}`,f)}if(c.length===0)throw new P("Transformation produced no artifacts");return{content:c[0].content,format:e.format,filename:c[0].fileName}}async getCatalog(){return this.cachedCatalog||(this.cachedCatalog=await this.objectParser.parseKanonaks(this.repository)),this.cachedCatalog}};function N(t){return`${t.publisher}/${t.package_}/${t.name}`}function nn(t,e){let n=e.name;if(t.has(n))return n;for(let r of t)if(r.startsWith(n+"-")||r===n)return r}export{tt as DEFAULT_VARIANT,T as DOCAST,ot as DOCAST_PKG,at as DOCAST_PUB,ie as ExpressionEngineV3,R as ExpressionEvalErrorV3,Y as HtmlBackend,X as JsonBackend,G as MarkdownFrontmatterBackend,Q as ReferenceResolver,P as RenderError,Xt as SUPPORTED_FORMATS_V3,Z as SvgBackend,a as TX_V3,Dt as TX_V3_PKG,Kt as TX_V3_PUB,Sn as TX_V3_VERSION_MAJOR,J as TomlBackend,we as TransformationEngine,y as TransformationLoadErrorV3,O as TransformationRunnerErrorV3,ae as TransformationRunnerV3,ne as compileTransformationV3,ue as renderMarkdownToHtml};