@kanonak-protocol/sdk 3.11.0 → 3.13.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 (53) 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 +163 -0
  29. package/dist/transformations/DocAstUriConstants.d.ts +71 -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 +83 -0
  33. package/dist/transformations/backends/CssBackend.d.ts +7 -0
  34. package/dist/transformations/backends/HtmlBackend.d.ts +7 -0
  35. package/dist/transformations/backends/IDocumentAstBackend.d.ts +16 -0
  36. package/dist/transformations/backends/JsonBackend.d.ts +12 -0
  37. package/dist/transformations/backends/MarkdownFrontmatterBackend.d.ts +7 -0
  38. package/dist/transformations/backends/SimpleMarkdownRenderer.d.ts +17 -0
  39. package/dist/transformations/backends/SvgBackend.d.ts +7 -0
  40. package/dist/transformations/backends/TomlBackend.d.ts +7 -0
  41. package/dist/transformations/index.d.ts +19 -0
  42. package/dist/transformations/index.js +97 -0
  43. package/dist/transformations/v3/CompiledTransformationV3.d.ts +404 -0
  44. package/dist/transformations/v3/ExpressionEngineV3.d.ts +89 -0
  45. package/dist/transformations/v3/TransformationLoaderV3.d.ts +22 -0
  46. package/dist/transformations/v3/TransformationRunnerV3.d.ts +102 -0
  47. package/dist/transformations/v3/TransformationUriConstantsV3.d.ts +207 -0
  48. package/dist/uri-helpers/SingleDocumentRepository.d.ts +28 -0
  49. package/dist/uri-helpers/UriHelpers.d.ts +89 -0
  50. package/dist/uri-helpers/index.d.ts +3 -0
  51. package/dist/uri-helpers/index.js +1 -0
  52. package/dist/validation/index.js +1 -42
  53. package/package.json +18 -2
@@ -0,0 +1,83 @@
1
+ /**
2
+ * High-level facade over the v3 transformation engine.
3
+ *
4
+ * Consumers (VS Code Browser, future web Browser, third-party tools)
5
+ * give the engine a repository plus the URI of a resource and a
6
+ * target format, and get back a rendered artifact. The facade
7
+ * handles derivation discovery, transformation loading, instance
8
+ * lookup, and execution behind a small async API — no need to
9
+ * touch the underlying CompiledTransformationV3 / TransformationRunnerV3
10
+ * machinery directly.
11
+ *
12
+ * Catalog parsing is cached per-instance. Call `invalidate()` after
13
+ * the underlying repository changes to force a refresh.
14
+ */
15
+ import type { IKanonakDocumentRepository } from '@kanonak-protocol/types/document/models';
16
+ import { KanonakParser, KanonakObjectParser } from '../parsing/index.js';
17
+ import { type EntityUri } from '../uri-helpers/index.js';
18
+ import { type DerivationLookupResult } from '../derivation/findDerivation.js';
19
+ export interface RenderedArtifact {
20
+ /** Serialized output content. */
21
+ content: string;
22
+ /** The format the artifact was rendered as. */
23
+ format: EntityUri;
24
+ /** Filename stem (no directory, no extension). */
25
+ filename: string;
26
+ }
27
+ export declare class RenderError extends Error {
28
+ readonly cause?: unknown | undefined;
29
+ constructor(message: string, cause?: unknown | undefined);
30
+ }
31
+ /** Default Variant used when `render()` is called without an explicit variant. */
32
+ export declare const DEFAULT_VARIANT: EntityUri;
33
+ export declare class TransformationEngine {
34
+ private readonly repository;
35
+ private readonly parser;
36
+ private readonly objectParser;
37
+ private readonly runner;
38
+ private cachedCatalog;
39
+ constructor(repository: IKanonakDocumentRepository, parser?: KanonakParser, objectParser?: KanonakObjectParser);
40
+ /** Discard the cached catalog; the next call will re-parse the repository. */
41
+ invalidate(): void;
42
+ /**
43
+ * Walk derivation discovery to find the transformation that should
44
+ * render the given resource as the given format/variant. Returns
45
+ * undefined if no binding exists.
46
+ */
47
+ findDerivation(opts: {
48
+ resource: EntityUri;
49
+ format: EntityUri;
50
+ variant?: EntityUri;
51
+ }): Promise<DerivationLookupResult | undefined>;
52
+ /**
53
+ * Discover + run: render the given resource as the given format.
54
+ * Throws RenderError if no derivation is found or the run fails.
55
+ */
56
+ render(opts: {
57
+ resource: EntityUri;
58
+ format: EntityUri;
59
+ variant?: EntityUri;
60
+ /**
61
+ * Suppress the backend's default chrome (e.g. the HTML backend's
62
+ * `<!DOCTYPE html>...<style>...</style>` wrapper). Useful when
63
+ * embedding the rendered content inside a host that already has
64
+ * its own document shell — the VS Code Browser's webview being
65
+ * the canonical case. Backends without chrome (JSON, plain
66
+ * Markdown) ignore the flag.
67
+ */
68
+ omitWrapper?: boolean;
69
+ }): Promise<RenderedArtifact>;
70
+ /**
71
+ * Run a specific transformation against a resource. Use when the
72
+ * caller already knows which transformation to run (typically via
73
+ * findDerivation).
74
+ */
75
+ runTransformation(opts: {
76
+ transformation: EntityUri;
77
+ input: EntityUri;
78
+ format: EntityUri;
79
+ /** Suppress backend default chrome. See render's omitWrapper. */
80
+ omitWrapper?: boolean;
81
+ }): Promise<RenderedArtifact>;
82
+ private getCatalog;
83
+ }
@@ -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 CssBackend implements IDocumentAstBackend {
5
+ readonly backendUri = "kanonak.org/transformations/stylesheet";
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 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,19 @@
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 { CssBackend } from './backends/CssBackend.js';
19
+ export { renderMarkdownToHtml } from './backends/SimpleMarkdownRenderer.js';
@@ -0,0 +1,97 @@
1
+ import{b as v,c as d,e as N,k as Te}from"../chunk-NPWF35XZ.js";import{a as Ke}from"../chunk-GKQVJITL.js";import"../chunk-7M7XXZOV.js";import{a as P,c as Ae}from"../chunk-CRR4BQKR.js";import{b as L,c as w,d as h,g as D,h as C,i as B,j,k as T,l as b}from"../chunk-W6T7MOKY.js";import{a as Ve}from"../chunk-MYITGTGJ.js";import"../chunk-RGMZAKJV.js";import"../chunk-FUUTGGJS.js";var lt="kanonak.org",ft="document-ast",p=t=>({publisher:lt,package_:ft,name:t}),V={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"),TEXT_CSS:p("text-css"),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"),Table:p("Table"),tableColumnLabels:p("tableColumnLabels"),tableRows:p("tableRows"),TableRow:p("TableRow"),tableCells:p("tableCells")};function De(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var X=class{backendUri="kanonak.org/transformations/markdown-with-frontmatter";render(e,n){let r=dt(e.metadata,n),i=gt(e.children),u=["---",...r,"---","",i].join(`
2
+ `);return n?.trailingNewline&&(u.endsWith(`
3
+ `)||(u+=`
4
+ `)),u}};function dt(t,e){if(!t)return[];let n=new Map;for(let c of t.entries)n.set(ne(c.key),c);let r=new Map;if(e?.metadataRenames)for(let[c,l]of e.metadataRenames)r.set(ne(c),l);let a=(e?.metadataKeys??t.entries.map(c=>c.key)).map(ne),u=[];for(let c of a){let l=n.get(c);if(!l)continue;let m=r.get(c),g=ne(m??c),k=Le(l.value,l.escapeHint);k!==void 0&&u.push(`${g}: ${k}`)}return u}function ne(t){let e=t.lastIndexOf(".");return e===-1?t:t.substring(e+1)||t}function Le(t,e){switch(t.kind){case"StringScalar":return mt(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let i=Le(r,e);i!==void 0&&n.push(i)}return n.join(", ")}case"StructuredMap":return;default:return}}function mt(t,e){return!e||De(e,V.ESC_RAW)?t:De(e,V.ESC_YAML_SAFE)?pt(t):t}function pt(t){return t.includes(`
5
+ `)?`|-
6
+ ${t.replace(/\n/g,`
7
+ `).trimEnd()}`:/[:#\[\]{}&*!|>'"%@`,]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function gt(t){let e=[];for(let n of t){let r=fe(n);r&&e.push(r)}return e.join(`
8
+
9
+ `)}function fe(t){switch(t.kind){case"Heading":return`${"#".repeat(t.level)} ${re(t.inlines)}`;case"Paragraph":return re(t.inlines);case"RawBlock":return t.rawContent;case"PropertyList":return Ce(t);case"Table":return yt(t);default:return""}}function yt(t){let e=t.tableColumnLabels??[],n=t.tableRows??[];if(e.length===0&&n.length===0)return"";let r=`| ${e.map(le).join(" | ")} |`,i=`| ${e.map(()=>"---").join(" | ")} |`,a=n.map(u=>`| ${(u.tableCells??[]).map(kt).join(" | ")} |`);return[r,i,...a].join(`
10
+ `)}function kt(t){let e=t;return!e||typeof e!="object"||!e.kind?"":e.kind==="Text"||e.kind==="ResourceLink"||e.kind==="Badge"?le(re([e])):le(fe(e).replace(/\n+/g," "))}function le(t){return t.replace(/\|/g,"\\|")}function Ce(t,e=0){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let n=" ".repeat(e),r=[];for(let i of t.propertyEntries){let a=`${n}**${i.propertyKey}:**`,u=ht(i.propertyValue,e+1);u.includes(`
11
+ `)?r.push(`${a}
12
+ ${u}`):r.push(`${a} ${u}`)}return r.join(`
13
+ `)}function ht(t,e){if(!t||t.length===0)return"";let n=[],r=[];for(let i of t){let a=i;!a||typeof a!="object"||!a.kind||(a.kind==="Text"||a.kind==="ResourceLink"||a.kind==="Badge"?n.push(re([a])):a.kind==="PropertyList"?r.push(Ce(a,e)):r.push(fe(a)))}return r.length===0?n.join(""):n.length===0?r.join(`
14
+ `):`${n.join("")}
15
+ ${r.join(`
16
+ `)}`}function re(t){let e=[];for(let n of t)n.kind==="Text"?e.push(n.text):n.kind==="ResourceLink"?e.push(bt(n)):n.kind==="Badge"&&e.push(wt(n));return e.join("")}function bt(t){let e=Re(t.target);if(!e)return t.linkLabel??"[unresolved link]";let n=e.version,r=n?`https://${e.publisher}/${e.package_}/${n.major}.${n.minor}.${n.patch}/${e.name}`:`https://${e.publisher}/${e.package_}/${e.name}`,i=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:e.name,a=t.linkTooltip?` "${Be(t.linkTooltip)}"`:"";return`[${i}](${r}${a})`}function wt(t){if(!t.badgeTarget)return`*${t.badgeLabel}*`;let e=Re(t.badgeTarget);if(!e)return`*${t.badgeLabel}*`;let n=e.version,r=n?`https://${e.publisher}/${e.package_}/${n.major}.${n.minor}.${n.patch}/${e.name}`:`https://${e.publisher}/${e.package_}/${e.name}`,i=t.badgeTooltip?` "${Be(t.badgeTooltip)}"`:"";return`*[${t.badgeLabel}](${r}${i})*`}function Be(t){return t.replace(/"/g,'\\"')}function Re(t){if(!t||typeof t!="object")return;let e=t;if(e.subject&&e.subject.publisher&&e.subject.package_&&e.subject.name){let r={publisher:e.subject.publisher,package_:e.subject.package_,name:e.subject.name};return e.subject.version&&(r.version=e.subject.version),r}let n=t;if(typeof n.namespace=="string"&&typeof n.name=="string"&&n.name.length>0){let r=/^([^/]+)\/([^@]+)@(\d+)\.(\d+)\.(\d+)$/.exec(n.namespace);if(r)return{publisher:r[1],package_:r[2],name:n.name,version:{major:Number(r[3]),minor:Number(r[4]),patch:Number(r[5])}}}}function $t(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=St(e.metadata,n).join(`
17
+ `);return n?.trailingNewline&&(i.endsWith(`
18
+ `)||(i+=`
19
+ `)),i}};function St(t,e){if(!t)return[];let n=new Map;for(let a of t.entries)n.set(a.key,a);let r=e?.metadataKeys??t.entries.map(a=>a.key),i=[];for(let a of r){let u=n.get(a);if(!u)continue;let c=e?.metadataRenames.get(a)??a,l=Ue(u.value,u.escapeHint);l!==void 0&&i.push(`${c} = ${l}`)}return i}function Ue(t,e){switch(t.kind){case"StringScalar":return vt(t.stringValue,e);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let n=[];for(let r of t.items){let i=Ue(r,e);i!==void 0&&n.push(i)}return`[${n.join(", ")}]`}case"StructuredMap":return;default:return}}function vt(t,e){return e&&$t(e,V.ESC_TOML_MULTILINE)?jt(t):Et(t)}function Et(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n")}"`}function jt(t){return`"""
20
+ ${t.replace(/"""/g,'\\"\\"\\"')}
21
+ """`}var Y=class{backendUri="kanonak.org/transformations/json";render(e,n){let r=JSON.stringify(e,null,2);return n?.trailingNewline&&!r.endsWith(`
22
+ `)?r+`
23
+ `:r}};function me(t){let e=t.replace(/\r\n/g,`
24
+ `).split(`
25
+ `),n=[],r=0;for(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let a=/^(\s*)```(\S*)\s*$/.exec(i);if(a){let l=a[2],m=[];for(r++;r<e.length&&!/^(\s*)```\s*$/.test(e[r]);)m.push(e[r]),r++;r++;let g=Oe(m.join(`
26
+ `)),k=l?` class="language-${_e(l)}"`:"";n.push(`<pre><code${k}>${g}</code></pre>`);continue}let u=/^(#{1,6})\s+(.*)$/.exec(i);if(u){let l=u[1].length,m=q(u[2].trim());n.push(`<h${l}>${m}</h${l}>`),r++;continue}if(i.includes("|")&&r+1<e.length&&Pe(e[r+1])){let l=de(i),m=Vt(e[r+1]);r+=2;let g=[];for(;r<e.length&&e[r].trim()!==""&&e[r].includes("|");)g.push(de(e[r])),r++;n.push(At(l,m,g));continue}if(/^\s*[-*]\s+/.test(i)){let l=[];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++,l.push(`<li>${q(m.join(" ").trim())}</li>`)}n.push(`<ul>
27
+ ${l.join(`
28
+ `)}
29
+ </ul>`);continue}if(/^\s*\d+\.\s+/.test(i)){let l=[];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++,l.push(`<li>${q(m.join(" ").trim())}</li>`)}n.push(`<ol>
30
+ ${l.join(`
31
+ `)}
32
+ </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&&Pe(e[r+1]));)c.push(e[r]),r++;n.push(`<p>${q(c.join(" "))}</p>`)}return n.join(`
33
+ `)}function Pe(t){return t.includes("-")?/^[\s|:-]+$/.test(t):!1}function de(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 Vt(t){return de(t).map(e=>{let n=e.startsWith(":"),r=e.endsWith(":");return n&&r?"center":r?"right":n?"left":null})}function At(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(""),a=n.map(u=>`<tr>${u.map((l,m)=>`<td${r(m)}>${q(l)}</td>`).join("")}</tr>`).join(`
34
+ `);return`<table>
35
+ <thead><tr>${i}</tr></thead>
36
+ <tbody>
37
+ ${a}
38
+ </tbody>
39
+ </table>`}function q(t){let e=Oe(t);return e=e.replace(/`([^`\n]+)`/g,(n,r)=>`<code>${r}</code>`),e=e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(n,r,i)=>`<a href="${_e(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 Oe(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _e(t){return t.replace(/"/g,"&quot;").replace(/&/g,"&amp;")}function pe(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Z=class{backendUri="kanonak.org/transformations/html";render(e,n){let r=Dt(e.children);if(n?.omitWrapper){let c=r.endsWith(`
40
+ `)?r:`${r}
41
+ `;return n.trailingNewline===!1&&c.endsWith(`
42
+ `)?c.slice(0,-1):c}let i=Kt(e.metadata)??"Untitled",a=Tt(e.metadata,n),u=`<!DOCTYPE html>
43
+ <html lang="en">
44
+ <head>
45
+ <meta charset="utf-8">
46
+ <title>${R(i)}</title>
47
+ <style>
48
+ 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; }
49
+ h1, h2, h3, h4 { line-height: 1.2; }
50
+ h1 { border-bottom: 1px solid #ddd; padding-bottom: 0.3em; }
51
+ dl.metadata { background: #f6f8fa; border: 1px solid #e4e8ec; border-radius: 6px; padding: 0.75rem 1rem; margin-bottom: 1.5rem; }
52
+ dl.metadata dt { font-weight: 600; color: #555; margin-top: 0.35rem; }
53
+ dl.metadata dt:first-child { margin-top: 0; }
54
+ dl.metadata dd { margin: 0; }
55
+ code { background: #f6f8fa; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.92em; }
56
+ pre { background: #f6f8fa; border: 1px solid #e4e8ec; border-radius: 6px; padding: 0.8rem 1rem; overflow-x: auto; }
57
+ pre code { background: transparent; padding: 0; font-size: 0.88em; }
58
+ p { margin: 0.85em 0; }
59
+ table { border-collapse: collapse; width: 100%; margin: 1em 0; font-size: 0.93em; }
60
+ table th, table td { border: 1px solid #d0d7de; padding: 0.4em 0.7em; text-align: left; vertical-align: top; }
61
+ table th { background: #f6f8fa; font-weight: 600; }
62
+ table tr:nth-child(even) td { background: #fafbfc; }
63
+ figure.svg-figure { margin: 1.5em 0; text-align: center; }
64
+ figure.svg-figure svg { max-width: 100%; height: auto; }
65
+ </style>
66
+ </head>
67
+ <body>
68
+ ${a}${r}
69
+ </body>
70
+ </html>
71
+ `;return n?.trailingNewline===!1&&u.endsWith(`
72
+ `)?u.slice(0,-1):u}};function Kt(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 Tt(t,e){if(!t||t.entries.length===0)return"";let n=e?.metadataKeys??t.entries.map(a=>a.key),r=new Map(t.entries.map(a=>[a.key,a])),i=[];for(let a of n){let u=r.get(a);if(!u)continue;let c=e?.metadataRenames.get(a)??a,l=Ie(u.value);l!==void 0&&i.push(` <dt>${R(c)}</dt>
73
+ <dd>${l}</dd>`)}return i.length===0?"":`<dl class="metadata">
74
+ ${i.join(`
75
+ `)}
76
+ </dl>
77
+ `}function Ie(t){switch(t.kind){case"StringScalar":return R(t.stringValue);case"IntegerScalar":return String(t.integerValue);case"StructuredList":{let e=[];for(let n of t.items){let r=Ie(n);r!==void 0&&e.push(`<code>${r}</code>`)}return e.join(", ")}case"StructuredMap":return;default:return}}function Dt(t){let e=[];for(let n of t){let r=ge(n);r&&e.push(r)}return e.join(`
78
+ `)}function ge(t){switch(t.kind){case"Heading":{let e=Math.max(1,Math.min(6,t.level));return`<h${e}>${ie(t.inlines)}</h${e}>`}case"Paragraph":return`<p>${ie(t.inlines)}</p>`;case"RawBlock":return Pt(t);case"PropertyList":return Rt(t);case"Table":return Lt(t);default:return""}}function Lt(t){let e=t.tableColumnLabels??[],n=t.tableRows??[],r=e.length>0?`<thead>
79
+ <tr>${e.map(a=>`<th>${R(a)}</th>`).join("")}</tr>
80
+ </thead>
81
+ `:"",i=n.length>0?`<tbody>
82
+ ${n.map(Ct).join(`
83
+ `)}
84
+ </tbody>
85
+ `:"";return`<table class="property-table">
86
+ ${r}${i}</table>`}function Ct(t){return` <tr>${(t.tableCells??[]).map(r=>`<td>${Bt(r)}</td>`).join("")}</tr>`}function Bt(t){let e=t;return!e||typeof e!="object"||!e.kind?"":e.kind==="Text"||e.kind==="ResourceLink"||e.kind==="Badge"?ie([e]):ge(e)}function Rt(t){if(!t.propertyEntries||t.propertyEntries.length===0)return"";let e=[];for(let n of t.propertyEntries){let i=`<dt${n.propertyTooltip?` title="${W(n.propertyTooltip)}"`:""}>${R(n.propertyKey)}</dt>`,a=`<dd>${Ut(n.propertyValue)}</dd>`;e.push(i,a)}return`<dl class="property-list">
87
+ ${e.join(`
88
+ `)}
89
+ </dl>`}function Ut(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"||r.kind==="Badge"?e.push(ie([r])):e.push(ge(r)))}return e.join("")}function Pt(t){let e=t.mediaType;return e&&pe(e,V.TEXT_MARKDOWN)?me(t.rawContent):e&&pe(e,V.TEXT_HTML)?t.rawContent:e&&pe(e,V.IMAGE_SVG_XML)?`<figure class="svg-figure">
90
+ ${t.rawContent}
91
+ </figure>`:`<pre${e?` class="media-${W(e.name)}"`:""}><code>${R(t.rawContent)}</code></pre>`}function ie(t){let e=[];for(let n of t)n.kind==="Text"?e.push(R(n.text)):n.kind==="ResourceLink"?e.push(Ot(n)):n.kind==="Badge"&&e.push(_t(n));return e.join("")}function Ot(t){let e=Ne(t.target);if(!e)return R(t.linkLabel??"[unresolved link]");let n=e.version,r=n?`https://${e.publisher}/${e.package_}/${n.major}.${n.minor}.${n.patch}/${e.name}`:`https://${e.publisher}/${e.package_}/${e.name}`,i=t.linkLabel&&t.linkLabel.length>0?t.linkLabel:e.name,a=t.linkTooltip?` title="${W(t.linkTooltip)}"`:"";return`<a class="kan-link" href="${W(r)}"${a}>${R(i)}</a>`}function _t(t){let e=t.badgeTooltip?` title="${W(t.badgeTooltip)}"`:"",n=R(t.badgeLabel);if(!t.badgeTarget)return`<span class="kan-badge"${e}>${n}</span>`;let r=Ne(t.badgeTarget);if(!r)return`<span class="kan-badge"${e}>${n}</span>`;let i=r.version,a=i?`https://${r.publisher}/${r.package_}/${i.major}.${i.minor}.${i.patch}/${r.name}`:`https://${r.publisher}/${r.package_}/${r.name}`;return`<a class="kan-badge" href="${W(a)}"${e}>${n}</a>`}function Ne(t){if(!t||typeof t!="object")return;let e=t;if(e.subject&&e.subject.publisher&&e.subject.package_&&e.subject.name){let r={publisher:e.subject.publisher,package_:e.subject.package_,name:e.subject.name};return e.subject.version&&(r.version=e.subject.version),r}let n=t;if(typeof n.namespace=="string"&&typeof n.name=="string"&&n.name.length>0){let r=/^([^/]+)\/([^@]+)@(\d+)\.(\d+)\.(\d+)$/.exec(n.namespace);if(r)return{publisher:r[1],package_:r[2],name:n.name,version:{major:Number(r[3]),minor:Number(r[4]),patch:Number(r[5])}}}}function R(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function W(t){return t.replace(/"/g,"&quot;").replace(/&/g,"&amp;")}function It(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var Q=class{backendUri="kanonak.org/transformations/svg";render(e,n){for(let r of e.children)if(r.kind==="RawBlock"&&r.mediaType&&It(r.mediaType,V.IMAGE_SVG_XML)){let i=r.rawContent;return n?.trailingNewline&&!i.endsWith(`
92
+ `)&&(i+=`
93
+ `),i}return'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'}};function Nt(t,e){return t.publisher===e.publisher&&t.package_===e.package_&&t.name===e.name}var x=class{backendUri="kanonak.org/transformations/stylesheet";render(e,n){let r=[];for(let a of e.children)a.kind==="RawBlock"&&a.mediaType&&Nt(a.mediaType,V.TEXT_CSS)&&r.push(a.rawContent);let i=r.join(`
94
+
95
+ `);return n?.trailingNewline&&i.length>0&&!i.endsWith(`
96
+ `)&&(i+=`
97
+ `),i}};var ee=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(n,e);if(r)return r;let i=e.version,a=i&&typeof i.major=="number"?`@${i.major}.${i.minor}.${i.patch}`:"",u=`${e.publisher}/${e.package_}${a}`,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(K=>{let S=K.metadata?.namespace_?.version;return S&&S.major===i.major&&S.minor===i.minor&&S.patch===i.patch})??m[0]:m[0],k=new Te(g,this.repository);c=await this.objectParser.parseKanonaks(k),this.cache.set(u,c)}let l=N(c,e);if(l)return l;for(let m of c)if(m instanceof w&&m.name===e.name)return m}};var Mt="kanonak.org",Ft="transformations",On=3,s=t=>({publisher:Mt,package_:Ft,name:t}),o={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"),Let:s("Let"),letName:s("letName"),letValue:s("letValue"),letBody:s("letBody"),GetStatementByName:s("GetStatementByName"),inSubject:s("inSubject"),byName:s("byName")};var y=class extends Error{constructor(n,r){super(`${n} (at ${r})`);this.path=r}path};function oe(t,e){let n=t.name,r=Qt(e),i={catalog:e,depth:0};if(d(t,o.InstanceTransformation))return qt(t,n,i,r);if(d(t,o.SetTransformation))return Wt(t,n,i,r);throw new y("Subject is not a recognized v3 transformation type \u2014 expected InstanceTransformation or SetTransformation",n)}function qt(t,e,n,r){return{kind:"instance",name:t.name,inputPattern:He(t,e),rule:ae(t,o.rule,`${e}.rule`,n),artifactName:ae(t,o.artifactName,`${e}.artifactName`,n),outputs:Ge(t,`${e}.outputs`),overrides:Xe(t,`${e}.formatOverrides`,n),fragments:r}}function Wt(t,e,n,r){let i=_(t,o.partitionBy);return{kind:"set",name:t.name,inputPattern:He(t,e),rule:ae(t,o.rule,`${e}.rule`,n),artifactName:ae(t,o.artifactName,`${e}.artifactName`,n),outputs:Ge(t,`${e}.outputs`),overrides:Xe(t,`${e}.formatOverrides`,n),partitionBy:i,fragments:r}}function He(t,e){let n=te(t,o.inputPattern);if(!n)throw new y("inputPattern is required",e);return zt(n,`${e}.inputPattern`)}function zt(t,e){let n=_(t,o.matchesClass);if(!n)throw new y("matchesClass is required",e);let r=[];for(let u of A(t,o.requires))if(u instanceof j)r.push(he(u.object.subject));else if(u instanceof b)for(let c of u.object)c instanceof h&&r.push(he(c.subject));let i=[],a=0;for(let u of A(t,o.sortBy))if(u instanceof b)for(let c of u.object)c instanceof P&&i.push(Me(c,`${e}.sortBy[${a++}]`));else u instanceof T&&i.push(Me(u.object,`${e}.sortBy[${a++}]`));return{matchesClass:n,requires:r,sortBy:i}}function Me(t,e){let n=_(t,o.byProperty);if(!n)throw new y("SortKey.byProperty is required",e);let r=_(t,o.order);if(!r)throw new y("SortKey.order is required",e);if(v(r,o.ascending))return{byProperty:n,order:"ascending"};if(v(r,o.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 ae(t,e,n,r){let i=te(t,e);if(!i)throw new y("expression is required",n);return H(i,n,r)}function H(t,e,n){if(d(t,o.StringLiteral))return{kind:"string-literal",value:E(t,o.stringLiteral,e)};if(d(t,o.IntegerLiteral))return{kind:"integer-literal",value:ze(t,o.integerLiteral,e)};if(d(t,o.DecimalLiteral))return{kind:"decimal-literal",value:ze(t,o.decimalLiteral,e)};if(d(t,o.BooleanLiteral))return{kind:"boolean-literal",value:tn(t,o.booleanLiteral,e)};if(d(t,o.VarRef))return{kind:"var-ref",varName:E(t,o.varName,e)};if(d(t,o.PropertyRead))return{kind:"property-read",source:f(t,o.readSource,`${e}.readSource`,n),readProp:M(t,o.readProp,e,"readProp")};if(d(t,o.Traverse))return{kind:"traverse",source:f(t,o.traverseSource,`${e}.traverseSource`,n),through:M(t,o.through,e,"through"),step:f(t,o.step,`${e}.step`,n)};if(d(t,o.BuildAstNode))return{kind:"build-ast-node",astClass:M(t,o.astClass,e,"astClass"),set:Gt(t,`${e}.set`,n)};if(d(t,o.When))return{kind:"when",condition:f(t,o.condition,`${e}.condition`,n),thenBuild:f(t,o.thenBuild,`${e}.thenBuild`,n),elseBuild:Ht(t,o.elseBuild,`${e}.elseBuild`,n)};if(d(t,o.Concat))return{kind:"concat",parts:ye(t,o.parts,`${e}.parts`,n)};if(d(t,o.Fallback))return{kind:"fallback",primary:f(t,o.primary,`${e}.primary`,n),alternate:f(t,o.alternate,`${e}.alternate`,n)};if(d(t,o.UriName))return{kind:"uri-name",source:f(t,o.uriNameOf,`${e}.uriNameOf`,n)};if(d(t,o.UriPublisher))return{kind:"uri-publisher",source:f(t,o.uriPublisherOf,`${e}.uriPublisherOf`,n)};if(d(t,o.UriPackage))return{kind:"uri-package",source:f(t,o.uriPackageOf,`${e}.uriPackageOf`,n)};if(d(t,o.UriVersion))return{kind:"uri-version",source:f(t,o.uriVersionOf,`${e}.uriVersionOf`,n)};if(d(t,o.SubjectUri))return{kind:"subject-uri",source:f(t,o.subjectOf,`${e}.subjectOf`,n)};if(d(t,o.UriLiteral))return{kind:"uri-literal",refTo:M(t,o.refTo,e,"refTo")};if(d(t,o.DisplayLabel))return{kind:"display-label",labelTarget:M(t,o.labelTarget,e,"labelTarget"),labelSource:M(t,o.labelSource,e,"labelSource")};if(d(t,o.ResolveRef))return{kind:"resolve-ref",source:f(t,o.resolveSource,`${e}.resolveSource`,n)};if(d(t,o.Normalize))return{kind:"normalize",source:f(t,o.normSource,`${e}.normSource`,n),normKind:Xt(t,e)};if(d(t,o.IsSet))return{kind:"is-set",check:f(t,o.checkExpr,`${e}.checkExpr`,n)};if(d(t,o.CallFragment))return Yt(t,e,n);if(d(t,o.Join))return{kind:"join",source:f(t,o.source,`${e}.source`,n),separator:E(t,o.separator,e)};if(d(t,o.Count))return{kind:"count",source:f(t,o.source,`${e}.source`,n)};if(d(t,o.Sum))return{kind:"sum",source:f(t,o.source,`${e}.source`,n)};if(d(t,o.Min))return{kind:"min",source:f(t,o.source,`${e}.source`,n)};if(d(t,o.Max))return{kind:"max",source:f(t,o.source,`${e}.source`,n)};if(d(t,o.Average))return{kind:"average",source:f(t,o.source,`${e}.source`,n)};if(d(t,o.ForEach))return{kind:"for-each",source:f(t,o.source,`${e}.source`,n),loopVar:E(t,o.loopVar,e),emit:f(t,o.emit,`${e}.emit`,n)};if(d(t,o.ListMap))return{kind:"list-map",source:f(t,o.source,`${e}.source`,n),loopVar:E(t,o.loopVar,e),mapBody:f(t,o.mapBody,`${e}.mapBody`,n)};if(d(t,o.Filter))return{kind:"filter",source:f(t,o.source,`${e}.source`,n),loopVar:E(t,o.loopVar,e),predicate:f(t,o.predicate,`${e}.predicate`,n)};if(d(t,o.PartitionBy))return{kind:"partition-by",source:f(t,o.source,`${e}.source`,n),loopVar:E(t,o.loopVar,e),partitionKey:f(t,o.partitionKey,`${e}.partitionKey`,n)};if(d(t,o.DistinctBy))return{kind:"distinct-by",source:f(t,o.source,`${e}.source`,n),loopVar:E(t,o.loopVar,e),distinctKey:f(t,o.distinctKey,`${e}.distinctKey`,n)};if(d(t,o.AllStatements))return{kind:"all-statements",source:f(t,o.statementsOf,`${e}.statementsOf`,n)};if(d(t,o.StatementPredicate))return{kind:"statement-predicate",source:f(t,o.predicateOf,`${e}.predicateOf`,n)};if(d(t,o.StatementValue))return{kind:"statement-value",source:f(t,o.valueOf,`${e}.valueOf`,n)};if(d(t,o.DateFormat))return{kind:"date-format",source:f(t,o.dateSource,`${e}.dateSource`,n),format:Jt(t,e)};if(d(t,o.Add))return{kind:"add",left:f(t,o.arithLeft,`${e}.arithLeft`,n),right:f(t,o.arithRight,`${e}.arithRight`,n)};if(d(t,o.Subtract))return{kind:"subtract",left:f(t,o.arithLeft,`${e}.arithLeft`,n),right:f(t,o.arithRight,`${e}.arithRight`,n)};if(d(t,o.Multiply))return{kind:"multiply",left:f(t,o.arithLeft,`${e}.arithLeft`,n),right:f(t,o.arithRight,`${e}.arithRight`,n)};if(d(t,o.Divide))return{kind:"divide",left:f(t,o.arithLeft,`${e}.arithLeft`,n),right:f(t,o.arithRight,`${e}.arithRight`,n)};if(d(t,o.Reverse))return{kind:"reverse",source:f(t,o.source,`${e}.source`,n)};if(d(t,o.WindowedMap)){let r=Je(t,o.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:f(t,o.source,`${e}.source`,n),windowSize:r,windowVar:E(t,o.windowVar,e),windowBody:f(t,o.windowBody,`${e}.windowBody`,n)}}if(d(t,o.PairwiseMap))return{kind:"pairwise-map",source:f(t,o.source,`${e}.source`,n),firstVar:E(t,o.firstVar,e),secondVar:E(t,o.secondVar,e),pairBody:f(t,o.pairBody,`${e}.pairBody`,n)};if(d(t,o.Scan))return{kind:"scan",source:f(t,o.source,`${e}.source`,n),initialState:f(t,o.initialState,`${e}.initialState`,n),stateVar:E(t,o.stateVar,e),elementVar:E(t,o.elementVar,e),accumulate:f(t,o.accumulate,`${e}.accumulate`,n)};if(d(t,o.ListItemAt))return{kind:"list-item-at",source:f(t,o.source,`${e}.source`,n),itemIndex:f(t,o.itemIndex,`${e}.itemIndex`,n)};if(d(t,o.Equals))return{kind:"equals",left:f(t,o.compareLeft,`${e}.compareLeft`,n),right:f(t,o.compareRight,`${e}.compareRight`,n)};if(d(t,o.GreaterThan))return{kind:"greater-than",left:f(t,o.compareLeft,`${e}.compareLeft`,n),right:f(t,o.compareRight,`${e}.compareRight`,n)};if(d(t,o.LessThan))return{kind:"less-than",left:f(t,o.compareLeft,`${e}.compareLeft`,n),right:f(t,o.compareRight,`${e}.compareRight`,n)};if(d(t,o.GreaterThanOrEqual))return{kind:"greater-than-or-equal",left:f(t,o.compareLeft,`${e}.compareLeft`,n),right:f(t,o.compareRight,`${e}.compareRight`,n)};if(d(t,o.LessThanOrEqual))return{kind:"less-than-or-equal",left:f(t,o.compareLeft,`${e}.compareLeft`,n),right:f(t,o.compareRight,`${e}.compareRight`,n)};if(d(t,o.Not))return{kind:"not",operand:f(t,o.operand,`${e}.operand`,n)};if(d(t,o.And))return{kind:"and",operands:ye(t,o.operands,`${e}.operands`,n)};if(d(t,o.Or))return{kind:"or",operands:ye(t,o.operands,`${e}.operands`,n)};if(d(t,o.Contains))return{kind:"contains",haystack:f(t,o.haystack,`${e}.haystack`,n),needle:f(t,o.needle,`${e}.needle`,n)};if(d(t,o.Abs))return{kind:"abs",value:f(t,o.value,`${e}.value`,n)};if(d(t,o.Negate))return{kind:"negate",value:f(t,o.value,`${e}.value`,n)};if(d(t,o.IsReference))return{kind:"is-reference",check:f(t,o.kindCheck,`${e}.kindCheck`,n)};if(d(t,o.IsEmbedded))return{kind:"is-embedded",check:f(t,o.kindCheck,`${e}.kindCheck`,n)};if(d(t,o.IsList))return{kind:"is-list",check:f(t,o.kindCheck,`${e}.kindCheck`,n)};if(d(t,o.StatementObject))return{kind:"statement-object",source:f(t,o.statementSource,`${e}.statementSource`,n)};if(d(t,o.Let))return{kind:"let",bindName:E(t,o.letName,e),bindValue:f(t,o.letValue,`${e}.letValue`,n),body:f(t,o.letBody,`${e}.letBody`,n)};if(d(t,o.GetStatementByName))return{kind:"get-statement-by-name",inSubject:f(t,o.inSubject,`${e}.inSubject`,n),byName:f(t,o.byName,`${e}.byName`,n)};throw new y("Expression is not of a recognized v3 type \u2014 embedded has no matching subclass of tx.Expression",e)}function f(t,e,n,r){let i=te(t,e);if(!i)throw new y("child expression is required",n);return H(i,n,r)}function Ht(t,e,n,r){let i=te(t,e);if(i)return H(i,n,r)}function ye(t,e,n,r){let i=[],a=0;for(let u of A(t,e))if(u instanceof b)for(let c of u.object)c instanceof P&&i.push(H(c,`${n}[${a++}]`,r));else u instanceof T&&i.push(H(u.object,`${n}[${a++}]`,r));return i}function Gt(t,e,n){let r=[],i=0;for(let a of A(t,o.set))if(a instanceof b)for(let u of a.object)u instanceof P&&r.push(Fe(u,`${e}[${i++}]`,n));else a instanceof T&&r.push(Fe(a.object,`${e}[${i++}]`,n));return r}function Fe(t,e,n){return{field:M(t,o.field,e,"field"),value:f(t,o.bindValue,`${e}.bindValue`,n)}}function Xt(t,e){let n=_(t,o.normKind);if(!n)throw new y("normKind is required",e);if(v(n,o.NORM_TRIM_END))return"trim-end";throw new y(`Unknown NormalizeKind: ${n.publisher}/${n.package_}/${n.name}`,e)}var qe=new Set(["iso-date","iso-datetime","short-date","long-date","year","month-year"]);function Jt(t,e){let n=z(t,o.dateFormat);if(!n)throw new y("dateFormat is required",e);if(!qe.has(n))throw new y(`Unknown dateFormat "${n}"; supported: ${[...qe].join(", ")}`,e);return n}function Yt(t,e,n){let r=_(t,o.fragmentRef);if(!r)throw new y("fragmentRef is required",e);if(!xt(n.catalog,r))throw new y(`ExpressionFragment not found: ${r.publisher}/${r.package_}/${r.name}`,e);return{kind:"call-fragment",fragmentKey:Zt(r)}}function Zt(t){return`${t.publisher}/${t.package_}/${t.name}`}function Qt(t){let e=new Map,n=[];for(let r of t){if(!(r instanceof w)||!d(r,o.ExpressionFragment))continue;let i=te(r,o.body);if(!i)continue;let a=(r.namespace||"").split("@")[0]||"",u=a.indexOf("/");if(u<0)continue;let c=a.substring(0,u),l=a.substring(u+1),m=`${c}/${l}/${r.name}`;n.push({key:m,subject:r,bodyEmb:i,pubPkgName:`${a}/${r.name}`})}for(let r of n){let i=H(r.bodyEmb,`fragment(${r.pubPkgName})`,{catalog:t,depth:0});e.set(r.key,i)}return e}function xt(t,e){for(let n of t)if(!(!(n instanceof w)||n.name!==e.name||!(n.namespace||"").startsWith(`${e.publisher}/${e.package_}@`))&&d(n,o.ExpressionFragment))return n}function Ge(t,e){let n=new Set;for(let r of A(t,o.outputs))if(r instanceof j)n.add(r.object.subject.name);else if(r instanceof b)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 Xe(t,e,n){let r=new Map,i=0;for(let a of A(t,o.formatOverrides))if(a instanceof b){for(let u of a.object)if(u instanceof P){let[c,l]=We(u,`${e}[${i++}]`);r.set(c,l)}}else if(a instanceof T){let[u,c]=We(a.object,`${e}[${i++}]`);r.set(u,c)}return r}function We(t,e){let n=_(t,o.formatTarget);if(!n)throw new y("formatTarget is required",e);let r=[];for(let c of A(t,o.metadataKeys))if(c instanceof D)r.push(c.object);else if(c instanceof b)for(let l of c.object){let m=l.value;typeof m=="string"&&r.push(m)}let i=new Map;for(let c of A(t,o.metadataRenames))if(c instanceof b){for(let l of c.object)if(l instanceof P){let m=z(l,o.fromKey),g=z(l,o.toKey);m&&g&&i.set(m,g)}}else if(c instanceof T){let l=c.object,m=z(l,o.fromKey),g=z(l,o.toKey);m&&g&&i.set(m,g)}let a=ke(t,o.trailingNewline),u=ke(t,o.omitWrapper);return[n.name,{metadataKeys:r.length>0?r:void 0,metadataRenames:i,trailingNewline:a,omitWrapper:u}]}function en(t){return t.predicate?.subject}function A(t,e){let n=[];for(let r of t.statement){let i=en(r);i&&v(i,e)&&n.push(r)}return n}function te(t,e){for(let n of A(t,e))if(n instanceof T)return n.object}function _(t,e){for(let n of A(t,e))if(n instanceof j)return he(n.object.subject)}function z(t,e){for(let n of A(t,e))if(n instanceof D)return n.object}function Je(t,e){for(let n of A(t,e))if(n instanceof C)return n.object}function ke(t,e){for(let n of A(t,e))if(n instanceof B)return n.object}function E(t,e,n){let r=z(t,e);if(r===void 0)throw new y(`${e.name} (string) is required`,n);return r}function ze(t,e,n){let r=Je(t,e);if(r===void 0)throw new y(`${e.name} (number) is required`,n);return r}function tn(t,e,n){let r=ke(t,e);if(r===void 0)throw new y(`${e.name} (boolean) is required`,n);return r}function M(t,e,n,r){let i=_(t,e);if(!i)throw new y(`${r} (URI reference) is required`,n);return i}function he(t){return{publisher:t.publisher,package_:t.package_,name:t.name}}var U=class extends Error{},ue=class{constructor(e,n,r=new Map){this.resolver=e;this.catalog=n;this.fragments=r}resolver;catalog;fragments;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 U(`Unbound variable "${e.varName}"`);return n.get(e.varName)}case"concat":{let r=[];for(let i of e.parts){let a=await this.evaluate(i,n);if(a!=null)if(Array.isArray(a))for(let u of a)r.push(u);else r.push(a)}return r}case"fallback":{let r=await this.evaluate(e.primary,n);return Ze(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 Ze(r)}case"property-read":{let r=await this.evaluate(e.source,n);return Ye(r,e.readProp)}case"traverse":{let r=await this.evaluate(e.source,n);if(!(r instanceof L))return;let i=rn(r,e.through),a=[];for(let u of i){let c=await this.resolver.resolveSubject(u,this.catalog);if(!c)continue;let l=new Map(n);l.set("input",c);let m=await this.evaluate(e.step,l);m!=null&&a.push(se(m))}return a.join("")}case"uri-name":{let r=await this.evaluate(e.source,n);return G(r)?r.name:r instanceof h?r.subject.name:r instanceof w?r.name:r instanceof P?r.name??"":void 0}case"uri-publisher":{let r=await this.evaluate(e.source,n);return be(r)?.publisher}case"uri-package":{let r=await this.evaluate(e.source,n);return be(r)?.package_}case"uri-version":{let r=await this.evaluate(e.source,n);return be(r)?.version}case"subject-uri":{let r=await this.evaluate(e.source,n);if(r instanceof w){let i=r.namespace??"",a=r.name??"";return!i||!a?void 0:`${i}/${a}`}if(r instanceof h){let i=r.subject,a=i.version;return a&&typeof a.major=="number"?`${i.publisher}/${i.package_}@${a.major}.${a.minor}.${a.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?Ye(r,e.labelSource):void 0}case"resolve-ref":{let r=await this.evaluate(e.source,n);return r instanceof w?r:r instanceof h?await this.resolver.resolveSubject(r.subject,this.catalog):G(r)?await this.resolver.resolveSubject(r,this.catalog):void 0}case"normalize":{let r=await this.evaluate(e.source,n),i=r==null?"":se(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 a=await this.evaluate(i.value,n);if(a==null||Array.isArray(a)&&a.length===0)continue;let u=i.field.name;Array.isArray(a)&&on.has(u)&&a.every(c=>sn(c))&&(a=a.map(c=>String(c)).join("")),r[u]=a}return r}case"call-fragment":{let r=this.fragments.get(e.fragmentKey);if(!r)throw new U(`ExpressionFragment ${e.fragmentKey} not found in registry`);return this.evaluate(r,n)}case"join":return(await this.evaluateList(e.source,n)).map(i=>i==null?"":se(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 a of r)i+=$(a,"Sum");return i}case"min":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new U("Min on an empty list is undefined; guard with IsSet");let i=$(r[0],"Min");for(let a=1;a<r.length;a++){let u=$(r[a],"Min");u<i&&(i=u)}return i}case"max":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new U("Max on an empty list is undefined; guard with IsSet");let i=$(r[0],"Max");for(let a=1;a<r.length;a++){let u=$(r[a],"Max");u>i&&(i=u)}return i}case"average":{let r=await this.evaluateList(e.source,n);if(r.length===0)throw new U("Average on an empty list is undefined; guard with IsSet");let i=0;for(let a of r)i+=$(a,"Average");return i/r.length}case"for-each":{let r=await this.evaluateList(e.source,n),i=[];for(let a of r){let u=new Map(n);u.set(e.loopVar,a);let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let l of c)i.push(l);else i.push(c)}return i}case"list-map":{let r=await this.evaluateList(e.source,n),i=[];for(let a of r){let u=new Map(n);u.set(e.loopVar,a),i.push(await this.evaluate(e.mapBody,u))}return i}case"filter":{let r=await this.evaluateList(e.source,n),i=[];for(let a of r){let u=new Map(n);u.set(e.loopVar,a),await this.evaluate(e.predicate,u)===!0&&i.push(a)}return i}case"partition-by":{let r=await this.evaluateList(e.source,n),i=new Map,a=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,u);let l=await this.evaluate(e.partitionKey,c),m=et(l),g=i.get(m);g||(g={kind:"Partition",key:l,members:[]},i.set(m,g),a.push(m)),g.members.push(u)}return a.map(u=>i.get(u))}case"distinct-by":{let r=await this.evaluateList(e.source,n),i=new Set,a=[];for(let u of r){let c=new Map(n);c.set(e.loopVar,u);let l=await this.evaluate(e.distinctKey,c),m=et(l);i.has(m)||(i.add(m),a.push(u))}return a}case"all-statements":{let r=await this.evaluate(e.source,n);return r instanceof L?r.statement:[]}case"statement-predicate":{let r=await this.evaluate(e.source,n);if(we(r)){let i=r.predicate;if(i instanceof h)return i}return}case"statement-value":{let r=await this.evaluate(e.source,n);return we(r)?ln(r):void 0}case"date-format":{let r=await this.evaluate(e.source,n),i=r==null?"":se(r);return i?cn(i,e.format):""}case"add":{let r=$(await this.evaluate(e.left,n),"Add"),i=$(await this.evaluate(e.right,n),"Add");return r+i}case"subtract":{let r=$(await this.evaluate(e.left,n),"Subtract"),i=$(await this.evaluate(e.right,n),"Subtract");return r-i}case"multiply":{let r=$(await this.evaluate(e.left,n),"Multiply"),i=$(await this.evaluate(e.right,n),"Multiply");return r*i}case"divide":{let r=$(await this.evaluate(e.left,n),"Divide"),i=$(await this.evaluate(e.right,n),"Divide");if(i===0)throw new U("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 a=0;a+e.windowSize<=r.length;a++){let u=r.slice(a,a+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let l=await this.evaluate(e.windowBody,c);if(l!=null)if(Array.isArray(l))for(let m of l)i.push(m);else i.push(l)}return i}case"pairwise-map":{let r=await this.evaluateList(e.source,n);if(r.length<2)return[];let i=[];for(let a=0;a+1<r.length;a++){let u=new Map(n);u.set(e.firstVar,r[a]),u.set(e.secondVar,r[a+1]);let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let l of c)i.push(l);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),a=[];for(let u of r){let c=new Map(n);c.set(e.stateVar,i),c.set(e.elementVar,u);let l=await this.evaluate(e.accumulate,c);a.push(l),i=l}return a}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 Qe(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 a of r)if(Qe(a,i))return!0;return!1}case"abs":{let r=$(await this.evaluate(e.value,n),"Abs");return Math.abs(r)}case"negate":return-$(await this.evaluate(e.value,n),"Negate");case"is-reference":{let r=await this.evaluate(e.check,n);return r instanceof h||r instanceof w}case"is-embedded":return await this.evaluate(e.check,n)instanceof P;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(!we(r))return;let i=r;return i instanceof D||i instanceof C||i instanceof B||i instanceof j||i instanceof T||i instanceof b?i.object:void 0}case"let":{let r=await this.evaluate(e.bindValue,n),i=new Map(n);return i.set(e.bindName,r),this.evaluate(e.body,i)}case"get-statement-by-name":{let r=await this.evaluate(e.inSubject,n),i=await this.evaluate(e.byName,n);if(!(r instanceof L)||typeof i!="string")return;for(let a of r.statement)if(a.predicate?.subject?.name===i)return a;return}default:{let r=e;throw new U("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 a=r.length-1;a>=1;a--){let u=new Map(n);u.set(e.firstVar,r[a-1]),u.set(e.secondVar,r[a]);let c=await this.evaluate(e.pairBody,u);if(c!=null)if(Array.isArray(c))for(let l of c)i.push(l);else i.push(c)}return i}if(e.kind==="for-each"){let r=await this.evaluateList(e.source,n),i=[];for(let a=r.length-1;a>=0;a--){let u=new Map(n);u.set(e.loopVar,r[a]);let c=await this.evaluate(e.emit,u);if(c!=null)if(Array.isArray(c))for(let l of c)i.push(l);else i.push(c)}return i}if(e.kind==="list-map"){let r=await this.evaluateList(e.source,n),i=[];for(let a=r.length-1;a>=0;a--){let u=new Map(n);u.set(e.loopVar,r[a]),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 a=r.length-e.windowSize;a>=0;a--){let u=r.slice(a,a+e.windowSize),c=new Map(n);c.set(e.windowVar,u);let l=await this.evaluate(e.windowBody,c);if(l!=null)if(Array.isArray(l))for(let m of l)i.push(m);else i.push(l)}return i}}};function Ye(t,e){if(t instanceof L)return nn(t,e);if(an(t))return v(e,o.key)?t.key:v(e,o.members)?t.members:void 0}function nn(t,e){for(let n of t.statement){let r=tt(n);if(!(!r||!v(r,e))&&(n instanceof D||n instanceof C||n instanceof B||n instanceof j||n instanceof T||n instanceof b))return n.object}}function rn(t,e){let n=[];for(let r of t.statement){let i=tt(r);if(!(!i||!v(i,e))){if(r instanceof j)n.push(r.object.subject);else if(r instanceof b)for(let a of r.object)a instanceof h&&n.push(a.subject)}}return n}function tt(t){return t.predicate?.subject}function se(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(t instanceof L)return t.name??"";if(t instanceof h)return t.subject.name;if(G(t))return t.name;let e=t.value;return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Ze(t){return t==null?!1:typeof t=="string"||Array.isArray(t)?t.length>0:typeof t=="boolean"?t===!0:!0}function G(t){return typeof t=="object"&&t!==null&&typeof t.publisher=="string"&&typeof t.package_=="string"&&typeof t.name=="string"}function an(t){return typeof t=="object"&&t!==null&&t.kind==="Partition"&&Array.isArray(t.members)}function $(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;throw new U(`${e} requires numeric elements; got ${un(t)}`)}function be(t){if(t instanceof w){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(G(t))return{publisher:t.publisher,package_:t.package_,version:"",name:t.name}}var on=new Set(["stringValue","text","rawContent","key","propertyKey","linkLabel"]);function sn(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function un(t){return t===void 0?"undefined":t===null?"null":Array.isArray(t)?`array(${t.length})`:typeof t}function cn(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()],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getUTCMonth()],u=n.getUTCDate(),c=(l,m=2)=>String(l).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`${a} ${u}`;case"long-date":return`${i} ${u}, ${r}`;case"year":return String(r);case"month-year":return`${i} ${r}`}}function Qe(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,a=r??e,u=xe(t),c=xe(e);return u&&c?u.publisher===c.publisher&&u.package_===c.package_&&u.name===c.name:typeof i=="string"&&typeof a=="string"||typeof i=="number"&&typeof a=="number"||typeof i=="boolean"&&typeof a=="boolean"?i===a:!1}function xe(t){if(t instanceof h){let e=t.subject;return{publisher:e.publisher,package_:e.package_,name:e.name}}if(t instanceof w){let e=t.namespace??"",n=e.indexOf("/"),r=e.indexOf("@",n+1);if(n<0)return;let i=e.substring(0,n),a=r>=0?e.substring(n+1,r):e.substring(n+1);return{publisher:i,package_:a,name:t.name??""}}if(G(t))return{publisher:t.publisher,package_:t.package_,name:t.name}}function we(t){return t instanceof D||t instanceof C||t instanceof B||t instanceof j||t instanceof T||t instanceof b}function ln(t){return t instanceof D||t instanceof C||t instanceof B?String(t.object??""):t instanceof j?t.object?.subject?.name??"":t instanceof T?"[embedded]":t instanceof b?(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 et(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 L){let e=t.name??"";return`k:${t.namespace??""}/${e}`}return G(t)?`u:${t.publisher}/${t.package_}/${t.name}`:`o:${JSON.stringify(t)}`}var fn={"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"},stylesheet:{formatUri:"kanonak.org/transformations/stylesheet",extension:".css"}},I=class extends Error{},ce=class{backends=new Map;constructor(){this.register(new X),this.register(new J),this.register(new Y),this.register(new Z),this.register(new Q),this.register(new x)}register(e){this.backends.set(e.backendUri,e)}async run(e){let n=e.transformationKanonaks??e.allKanonaks,r=oe(e.transformation,n);if(!r.outputs.has(e.outputFormat))throw new I(`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 I(`No backend registered for OutputFormat "${e.outputFormat}".`);let a=new ee(e.repository,e.parser,e.objectParser),u=new ue(a,e.allKanonaks,r.fragments);return r.kind==="instance"?this.runInstance(r,e,i,u):this.runSet(r,e,i,u)}async runInstance(e,n,r,i){let a=nt(n.instances,e.inputPattern.requires),u=rt(a,e.inputPattern.sortBy),c=[];for(let l of u){let m=new Map;m.set("input",l);let g=await i.evaluate(e.rule,m);$e(g,e.name,`input "${l.name}"`);let k=Se(await i.evaluate(e.artifactName,m),e.name,`input "${l.name}"`),K=ve(e.overrides.get(n.outputFormat),n.runtimeOverride),S=r.render(g,K);c.push({fileName:k,format:n.outputFormat,content:S,source:{kind:"instance",sourceName:l.name}})}return c}async runSet(e,n,r,i){let a=nt(n.instances,e.inputPattern.requires),u=rt(a,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,a){let u=new Map;u.set("inputs",n);let c=await a.evaluate(e.rule,u);$e(c,e.name,"set");let l=Se(await a.evaluate(e.artifactName,u),e.name,"set"),m=ve(e.overrides.get(r.outputFormat),r.runtimeOverride),g=i.render(c,m);return[{fileName:l,format:r.outputFormat,content:g,source:{kind:"set",memberCount:n.length}}]}async runSetWithPartition(e,n,r,i,a){let u=e.partitionBy,c=new Map,l=[];for(let g of n){let k=pn(g,u);if(k==null)continue;let K=gn(k),S=c.get(K);S||(S={keyValue:k,keyDisplay:yn(k),members:[]},c.set(K,S),l.push(K)),S.members.push(g)}let m=[];for(let g of l){let k=c.get(g),K=new Map;K.set("inputs",k.members),K.set("key",k.keyValue);let S=await a.evaluate(e.rule,K);$e(S,e.name,`partition "${k.keyDisplay}"`);let st=Se(await a.evaluate(e.artifactName,K),e.name,`partition "${k.keyDisplay}"`),ut=ve(e.overrides.get(r.outputFormat),r.runtimeOverride),ct=i.render(S,ut);m.push({fileName:st,format:r.outputFormat,content:ct,source:{kind:"set",memberCount:k.members.length,partitionKey:k.keyDisplay}})}return m}findBackend(e){let n=fn[e];if(n)return this.backends.get(n.formatUri)}};function nt(t,e){return e.length===0?t:t.filter(n=>{for(let r of e)if(!mn(n,r))return!1;return!0})}function rt(t,e){if(e.length===0)return t;let n=[...t];return n.sort((r,i)=>{for(let a of e){let u=it(r,a.byProperty),c=it(i,a.byProperty),l=dn(u,c,a.order);if(l!==0)return l}return 0}),n}function it(t,e){for(let n of t.statement){let r=Ee(n);if(!(!r||!v(r,e))){if(n instanceof D||n instanceof C||n instanceof B)return n.object;if(n instanceof b)throw new I(`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 j)throw new I(`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 dn(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 mn(t,e){for(let n of t.statement){let r=Ee(n);if(!r||!v(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 pn(t,e){for(let n of t.statement){let r=Ee(n);if(!(!r||!v(r,e))&&(n instanceof D||n instanceof C||n instanceof B||n instanceof j||n instanceof b))return n.object}}function Ee(t){return t.predicate?.subject}function gn(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 L){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 yn(t){return t==null?"":typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):t instanceof h?t.subject.name:t instanceof L?t.name??"":typeof t=="object"&&t!==null&&typeof t.name=="string"?t.name:""}function $e(t,e,n){if(typeof t!="object"||t===null||t.kind!=="Document")throw new I(`Transformation "${e}" rule did not yield a Document for ${n}. Got: ${at(t)}`)}function Se(t,e,n){if(typeof t=="string")return t;if(Array.isArray(t)&&t.every(kn))return t.map(r=>String(r)).join("");throw new I(`Transformation "${e}" artifactName did not yield a string for ${n}. Got: ${at(t)}`)}function kn(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function at(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}function ve(t,e){if(!t&&!e)return;let n={metadataRenames:e?.metadataRenames??t?.metadataRenames??new Map},r=e?.metadataKeys??t?.metadataKeys;r!==void 0&&(n.metadataKeys=r);let i=e?.trailingNewline??t?.trailingNewline;i!==void 0&&(n.trailingNewline=i);let a=e?.omitWrapper??t?.omitWrapper;return a!==void 0&&(n.omitWrapper=a),n}var O=class extends Error{constructor(n,r){super(n);this.cause=r;this.name="RenderError"}cause},ot={publisher:"kanonak.org",package_:"derivation",name:"default"},je=class{constructor(e,n=new Ve,r=new Ae){this.repository=e;this.parser=n;this.objectParser=r}repository;parser;objectParser;runner=new ce;cachedCatalog=void 0;invalidate(){this.cachedCatalog=void 0}async findDerivation(e){let n=await this.getCatalog(),r=N(n,e.resource);if(!(r instanceof w))return;let i=e.variant??ot;return Ke(r,e.format,i,n)}async render(e){let n=await this.findDerivation(e);if(!n)throw new O(`No derivation found for ${F(e.resource)} \u2192 format ${F(e.format)}`+(e.variant?` variant ${F(e.variant)}`:""));let r={transformation:{publisher:n.transformation.publisher,package_:n.transformation.package_,name:n.transformation.name},input:e.resource,format:e.format};return e.omitWrapper!==void 0&&(r.omitWrapper=e.omitWrapper),this.runTransformation(r)}async runTransformation(e){let n=await this.getCatalog(),r=N(n,e.transformation);if(!(r instanceof w))throw new O(`Transformation not found: ${F(e.transformation)}`);let i=N(n,e.input);if(!(i instanceof w))throw new O(`Input resource not found: ${F(e.input)}`);let a=oe(r,n),u=hn(a.outputs,e.format);if(!u)throw new O(`Transformation ${F(e.transformation)} declares outputs [${[...a.outputs].join(", ")}], none of which corresponds to format ${F(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,...e.omitWrapper!==void 0?{runtimeOverride:{metadataRenames:new Map,omitWrapper:e.omitWrapper}}:{}})}catch(l){throw new O(`Transformation execution failed: ${l.message}`,l)}if(c.length===0)throw new O("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 F(t){return`${t.publisher}/${t.package_}/${t.name}`}function hn(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{x as CssBackend,ot as DEFAULT_VARIANT,V as DOCAST,ft as DOCAST_PKG,lt as DOCAST_PUB,ue as ExpressionEngineV3,U as ExpressionEvalErrorV3,Z as HtmlBackend,Y as JsonBackend,X as MarkdownFrontmatterBackend,ee as ReferenceResolver,O as RenderError,fn as SUPPORTED_FORMATS_V3,Q as SvgBackend,o as TX_V3,Ft as TX_V3_PKG,Mt as TX_V3_PUB,On as TX_V3_VERSION_MAJOR,J as TomlBackend,je as TransformationEngine,y as TransformationLoadErrorV3,I as TransformationRunnerErrorV3,ce as TransformationRunnerV3,oe as compileTransformationV3,me as renderMarkdownToHtml};