@nova-energy/openamx 0.0.0-stage → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMMERCIAL-LICENSE.md +74 -0
- package/LICENSE.md +660 -0
- package/README.md +537 -3
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +197 -0
- package/dist/diagnostics/errors.js +94 -0
- package/dist/editor/completion.js +313 -0
- package/dist/editor/highlighting.js +224 -0
- package/dist/editor/moduleAnalysis.js +206 -0
- package/dist/editor/refactoring.js +46 -0
- package/dist/editor/sourceRanges.js +50 -0
- package/dist/editor/symbols.js +203 -0
- package/dist/formatter/formatAmx.js +79 -0
- package/dist/index.js +10 -0
- package/dist/parser/parseDocument.js +114 -0
- package/dist/parser/parseExpression.js +768 -0
- package/dist/parser/parseFor.js +53 -0
- package/dist/parser/parseFrontMatter.js +65 -0
- package/dist/parser/parseStatements.js +667 -0
- package/dist/parser/stringScanner.js +71 -0
- package/dist/renderer/chartModel.js +476 -0
- package/dist/renderer/narrativeModel.js +561 -0
- package/dist/renderer/renderHtml.js +521 -0
- package/dist/renderer/reportDocx.js +725 -0
- package/dist/renderer/reportPaths.js +31 -0
- package/dist/renderer/reportPdf.js +314 -0
- package/dist/renderer/reportPreparation.js +196 -0
- package/dist/runtime/csvTextSerialization.js +8 -0
- package/dist/runtime/dataText.js +191 -0
- package/dist/runtime/docxDestination.js +55 -0
- package/dist/runtime/environment.js +105 -0
- package/dist/runtime/evaluateDocument.js +32 -0
- package/dist/runtime/evaluateExpression.js +888 -0
- package/dist/runtime/externalUnits.js +91 -0
- package/dist/runtime/inputData.js +508 -0
- package/dist/runtime/measurement.js +110 -0
- package/dist/runtime/moduleLoader.js +279 -0
- package/dist/runtime/outputData.js +303 -0
- package/dist/runtime/pdfDestination.js +57 -0
- package/dist/runtime/standardLibrary.js +145 -0
- package/dist/typechecker/checkDocument.js +1282 -0
- package/dist/typechecker/declarationRegistry.js +7 -0
- package/dist/typechecker/dimensionTypes.js +1 -0
- package/package.json +33 -4
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
/// <reference path="../types/echarts-runtime.d.ts" />
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { existsSync, lstatSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import echartsBrowserRuntime from 'echarts/dist/echarts.min.js' with { type: 'text' };
|
|
6
|
+
import { marked } from 'marked';
|
|
7
|
+
import sanitizeHtml from 'sanitize-html';
|
|
8
|
+
import { AmxError } from '../diagnostics/errors';
|
|
9
|
+
import { parseExpression } from '../parser/parseExpression';
|
|
10
|
+
import { evaluateExpression } from '../runtime/evaluateExpression';
|
|
11
|
+
import { evaluateDocumentEnvironment } from '../runtime/evaluateDocument';
|
|
12
|
+
import { formatAmx } from '../formatter/formatAmx';
|
|
13
|
+
import { createChartViewModel } from './chartModel';
|
|
14
|
+
import { fitNarrativeImage } from './narrativeModel';
|
|
15
|
+
import { hasSymlink, isContained } from './reportPaths';
|
|
16
|
+
const REPORT_MARKDOWN_POLICY = {
|
|
17
|
+
allowedTags: [
|
|
18
|
+
'a', 'blockquote', 'br', 'code', 'del', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
|
19
|
+
'hr', 'li', 'ol', 'p', 'pre', 'span', 'strong', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'ul'
|
|
20
|
+
],
|
|
21
|
+
allowedAttributes: { code: ['class'] },
|
|
22
|
+
allowedSchemes: [],
|
|
23
|
+
allowProtocolRelative: false,
|
|
24
|
+
parseStyleAttributes: false,
|
|
25
|
+
disallowedTagsMode: 'discard',
|
|
26
|
+
enforceHtmlBoundary: true,
|
|
27
|
+
transformTags: { a: sanitizeHtml.simpleTransform('span', {}, true) }
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Render an OpenAmxDocument to a complete standalone HTML5 document.
|
|
31
|
+
*
|
|
32
|
+
* - Executes all executable blocks once before rendering any document nodes.
|
|
33
|
+
* - Resolves narrative expressions against the final shared environment.
|
|
34
|
+
* - Post-substitution narrative is rendered with marked (headings, paragraphs, bullets).
|
|
35
|
+
* - Executable blocks are rendered as escaped, formatted source at their source position.
|
|
36
|
+
* - Frontmatter metadata.title (if string) is used for <title>; otherwise "OpenAMX Document".
|
|
37
|
+
* - Output is deterministic for the supported Markdown subset.
|
|
38
|
+
* - Errors inside {{ }} (e.g. AMX1004) are surfaced with the same AmxError semantics.
|
|
39
|
+
*/
|
|
40
|
+
export function renderHtml(doc, file, env, options) {
|
|
41
|
+
const environment = env ?? evaluateDocumentEnvironment(doc, file);
|
|
42
|
+
const resolvedReport = resolveReportIdentity(doc, options?.report);
|
|
43
|
+
const emissionsByNode = new Map();
|
|
44
|
+
for (const emission of environment.viewEmissions) {
|
|
45
|
+
const emissions = emissionsByNode.get(emission.documentNodeIndex) ?? [];
|
|
46
|
+
emissions.push(emission);
|
|
47
|
+
emissionsByNode.set(emission.documentNodeIndex, emissions);
|
|
48
|
+
}
|
|
49
|
+
const bodyFragments = [];
|
|
50
|
+
const sourceVisible = resolvedReport.sourceVisible !== false;
|
|
51
|
+
const header = renderReportHeader(resolvedReport, file);
|
|
52
|
+
if (header) {
|
|
53
|
+
bodyFragments.push(header);
|
|
54
|
+
}
|
|
55
|
+
for (const [nodeIndex, node] of doc.nodes.entries()) {
|
|
56
|
+
if (node.type === 'narrative') {
|
|
57
|
+
const substituted = substituteInlines(node.content, environment, file, node.source?.line);
|
|
58
|
+
const htmlFragment = renderSafeMarkdown(substituted);
|
|
59
|
+
bodyFragments.push(htmlFragment);
|
|
60
|
+
}
|
|
61
|
+
else if (node.type === 'executableCodeBlock') {
|
|
62
|
+
if (sourceVisible) {
|
|
63
|
+
const formatted = formatAmx(node.content);
|
|
64
|
+
bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(formatted)}</code></pre>`);
|
|
65
|
+
}
|
|
66
|
+
for (const emission of emissionsByNode.get(nodeIndex) ?? []) {
|
|
67
|
+
bodyFragments.push(renderViewEmission(emission, resolvedReport));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const title = doc.metadata && typeof doc.metadata.title === 'string'
|
|
72
|
+
? String(doc.metadata.title)
|
|
73
|
+
: 'OpenAMX Document';
|
|
74
|
+
const bodyHtml = bodyFragments.join('');
|
|
75
|
+
const escapedTitle = escapeHtml(title);
|
|
76
|
+
const hasViews = environment.viewEmissions.length > 0;
|
|
77
|
+
const nonce = hasViews || !!resolvedReport.accent ? randomBytes(18).toString('base64') : '';
|
|
78
|
+
const accentStyle = safeAccentStyle(resolvedReport.accent, nonce);
|
|
79
|
+
const viewAssets = hasViews ? renderViewAssets(nonce) : '';
|
|
80
|
+
return `<!doctype html>
|
|
81
|
+
<html>
|
|
82
|
+
<head>
|
|
83
|
+
<meta charset="utf-8">
|
|
84
|
+
${renderContentSecurityPolicy(nonce, hasViews)}
|
|
85
|
+
<title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
|
|
86
|
+
</head>
|
|
87
|
+
<body>
|
|
88
|
+
${bodyHtml}</body>
|
|
89
|
+
</html>`;
|
|
90
|
+
}
|
|
91
|
+
export function renderPreparedHtml(report, options = {}) {
|
|
92
|
+
const isPreview = options.mode === 'preview';
|
|
93
|
+
const previewToken = isPreview ? randomBytes(32).toString('hex') : undefined;
|
|
94
|
+
const context = {
|
|
95
|
+
mode: isPreview ? 'preview' : 'standalone',
|
|
96
|
+
...(previewToken ? { previewToken } : {}),
|
|
97
|
+
...(!isPreview && options.sourceDocumentPath ? { sourceDocumentPath: options.sourceDocumentPath } : {}),
|
|
98
|
+
...(!isPreview && options.projectRoot ? { projectRoot: options.projectRoot } : {}),
|
|
99
|
+
...(!isPreview && options.outputPath ? { outputPath: options.outputPath } : {}),
|
|
100
|
+
targets: {}
|
|
101
|
+
};
|
|
102
|
+
const bodyFragments = [];
|
|
103
|
+
const identity = report.identity;
|
|
104
|
+
const metadata = [
|
|
105
|
+
identity.organization,
|
|
106
|
+
identity.author && `Author: ${identity.author}`,
|
|
107
|
+
identity.status && `Status: ${identity.status}`,
|
|
108
|
+
identity.classification && `Classification: ${identity.classification}`
|
|
109
|
+
].filter((value) => Boolean(value));
|
|
110
|
+
if (identity.logo || metadata.length > 0) {
|
|
111
|
+
const logo = identity.logo ? `<img class="openamx-report-logo" src="${escapeHtml(identity.logo.dataUri)}" alt="${escapeHtml(identity.logo.alt)}" />` : '';
|
|
112
|
+
bodyFragments.push(`<header class="openamx-report-header"><div class="openamx-report-identity">${logo}<div class="openamx-report-meta">${metadata.map(value => `<div class="openamx-report-attr">${escapeHtml(value)}</div>`).join('')}</div></div></header>`);
|
|
113
|
+
}
|
|
114
|
+
for (const item of report.items) {
|
|
115
|
+
if (item.type === 'narrative')
|
|
116
|
+
bodyFragments.push(renderNarrativeBlocks(item.markdown, context));
|
|
117
|
+
else if (item.type === 'source')
|
|
118
|
+
bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(item.text)}</code></pre>`);
|
|
119
|
+
else
|
|
120
|
+
bodyFragments.push(renderViewEmission(item.emission, identity));
|
|
121
|
+
}
|
|
122
|
+
if (identity.footer)
|
|
123
|
+
bodyFragments.push(`<footer class="openamx-report-footer">${escapeHtml(identity.footer)}</footer>`);
|
|
124
|
+
const hasViews = report.items.some(item => item.type === 'view');
|
|
125
|
+
const hasNarrativeAssets = report.items.some(item => item.type === 'narrative' && hasHtmlAssets(item.markdown));
|
|
126
|
+
const nonce = hasViews || identity.accent !== '#146C94' || hasNarrativeAssets || isPreview ? randomBytes(18).toString('base64') : '';
|
|
127
|
+
const accentStyle = safeAccentStyle(identity.accent, nonce);
|
|
128
|
+
const viewAssets = hasViews ? renderViewAssets(nonce) : '';
|
|
129
|
+
const narrativeAssets = hasNarrativeAssets ? renderNarrativeAssets(nonce) : '';
|
|
130
|
+
const previewNavigation = previewToken ? renderPreviewNavigationBootstrap(nonce, previewToken) : '';
|
|
131
|
+
const html = `<!doctype html>
|
|
132
|
+
<html>
|
|
133
|
+
<head>
|
|
134
|
+
<meta charset="utf-8">
|
|
135
|
+
${renderContentSecurityPolicy(nonce, hasViews, isPreview)}
|
|
136
|
+
<title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${narrativeAssets ? `\n${narrativeAssets}` : ''}${viewAssets ? `\n${viewAssets}` : ''}${previewNavigation ? `\n${previewNavigation}` : ''}
|
|
137
|
+
</head>
|
|
138
|
+
<body>
|
|
139
|
+
${bodyFragments.join('')}</body>
|
|
140
|
+
</html>`;
|
|
141
|
+
if (previewToken)
|
|
142
|
+
return { html, previewToken, targets: context.targets };
|
|
143
|
+
return html;
|
|
144
|
+
}
|
|
145
|
+
function renderNarrativeBlocks(blocks, context) {
|
|
146
|
+
return blocks.map(block => {
|
|
147
|
+
switch (block.type) {
|
|
148
|
+
case 'heading':
|
|
149
|
+
return `<h${block.depth} id="${escapeHtml(block.id)}">${renderNarrativeInlines(block.children, context)}</h${block.depth}>`;
|
|
150
|
+
case 'paragraph':
|
|
151
|
+
return `<p>${renderNarrativeInlines(block.children, context)}</p>`;
|
|
152
|
+
case 'code':
|
|
153
|
+
return `<pre><code${block.language ? ` class="language-${escapeHtml(block.language)}"` : ''}>${escapeHtml(block.text)}</code></pre>`;
|
|
154
|
+
case 'list': {
|
|
155
|
+
const tag = block.ordered ? 'ol' : 'ul';
|
|
156
|
+
const start = block.ordered && block.start !== undefined && block.start !== 1 ? ` start="${block.start}"` : '';
|
|
157
|
+
return `<${tag}${start}>${block.items.map(item => `<li>${renderNarrativeBlocks(item.blocks, context)}</li>`).join('')}</${tag}>`;
|
|
158
|
+
}
|
|
159
|
+
case 'blockquote':
|
|
160
|
+
return `<blockquote>${renderNarrativeBlocks(block.blocks, context)}</blockquote>`;
|
|
161
|
+
case 'table':
|
|
162
|
+
return `<table class="openamx-narrative-table"><thead><tr>${block.header.map((cell, index) => `<th scope="col"${tableCellAlignment(block.align[index])}>${renderNarrativeInlines(cell, context)}</th>`).join('')}</tr></thead><tbody>${block.rows.map(row => `<tr>${row.map((cell, index) => `<td${tableCellAlignment(block.align[index])}>${renderNarrativeInlines(cell, context)}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
|
|
163
|
+
case 'horizontalRule':
|
|
164
|
+
return '<hr>';
|
|
165
|
+
case 'pageBreak':
|
|
166
|
+
return '<div class="openamx-page-break" aria-hidden="true"></div>';
|
|
167
|
+
}
|
|
168
|
+
}).join('');
|
|
169
|
+
}
|
|
170
|
+
function tableCellAlignment(alignment) {
|
|
171
|
+
return alignment === 'left' || alignment === 'center' || alignment === 'right' ? ` align="${alignment}"` : '';
|
|
172
|
+
}
|
|
173
|
+
function renderNarrativeInlines(inlines, context) {
|
|
174
|
+
return inlines.map(inline => {
|
|
175
|
+
switch (inline.type) {
|
|
176
|
+
case 'text': return escapeHtml(inline.text);
|
|
177
|
+
case 'lineBreak': return '<br>';
|
|
178
|
+
case 'strong': return `<strong>${renderNarrativeInlines(inline.children, context)}</strong>`;
|
|
179
|
+
case 'emphasis': return `<em>${renderNarrativeInlines(inline.children, context)}</em>`;
|
|
180
|
+
case 'delete': return `<del>${renderNarrativeInlines(inline.children, context)}</del>`;
|
|
181
|
+
case 'inlineCode': return `<code>${escapeHtml(inline.text)}</code>`;
|
|
182
|
+
case 'image': return renderNarrativeImage(inline.image, inline.title);
|
|
183
|
+
case 'link': return renderNarrativeLink(inline.link, inline.children, context);
|
|
184
|
+
}
|
|
185
|
+
}).join('');
|
|
186
|
+
}
|
|
187
|
+
function renderNarrativeImage(image, title) {
|
|
188
|
+
const dimensions = fitNarrativeImage(image, { maxWidth: 1024, maxHeight: 768 });
|
|
189
|
+
return `<img class="openamx-narrative-image" src="${escapeHtml(image.dataUri)}" alt="${escapeHtml(image.alt)}" width="${Math.round(dimensions.width)}" height="${Math.round(dimensions.height)}"${title === undefined ? '' : ` title="${escapeHtml(title)}"`}>`;
|
|
190
|
+
}
|
|
191
|
+
function renderNarrativeLink(link, children, context) {
|
|
192
|
+
const label = renderNarrativeInlines(children, context);
|
|
193
|
+
const title = link.title === undefined ? '' : ` title="${escapeHtml(link.title)}"`;
|
|
194
|
+
if (link.type === 'internal')
|
|
195
|
+
return `<a href="#${encodeURIComponent(link.targetId)}"${title}>${label}</a>`;
|
|
196
|
+
if (context.mode === 'preview') {
|
|
197
|
+
const targetId = addPreviewTarget(context, link);
|
|
198
|
+
return `<a href="#" data-openamx-target="${targetId}"${title}>${label}</a>`;
|
|
199
|
+
}
|
|
200
|
+
if (link.type === 'external')
|
|
201
|
+
return `<a href="${escapeHtml(link.href)}" rel="noopener noreferrer"${title}>${label}</a>`;
|
|
202
|
+
return `<a href="${escapeHtml(standaloneLocalLinkUri(link, context))}"${title}>${label}</a>`;
|
|
203
|
+
}
|
|
204
|
+
function addPreviewTarget(context, link) {
|
|
205
|
+
let targetId;
|
|
206
|
+
do
|
|
207
|
+
targetId = randomBytes(16).toString('hex');
|
|
208
|
+
while (context.targets[targetId]);
|
|
209
|
+
context.targets[targetId] = link.type === 'external'
|
|
210
|
+
? { kind: 'external', href: link.href }
|
|
211
|
+
: { kind: 'local', path: link.path };
|
|
212
|
+
return targetId;
|
|
213
|
+
}
|
|
214
|
+
function standaloneLocalLinkUri(link, context) {
|
|
215
|
+
if (!context.sourceDocumentPath || !context.outputPath || link.sourceBase !== 'document-directory') {
|
|
216
|
+
throw new Error('Standalone HTML local links require source-document and final-output path context.');
|
|
217
|
+
}
|
|
218
|
+
const sourceDirectory = realpathSync(dirname(resolve(context.sourceDocumentPath)));
|
|
219
|
+
const sourceRoot = context.projectRoot ? realpathSync(context.projectRoot) : sourceDirectory;
|
|
220
|
+
if (sourceDirectory !== sourceRoot && !isContained(sourceRoot, sourceDirectory)) {
|
|
221
|
+
throw new Error('HTML source document is outside the permitted project root.');
|
|
222
|
+
}
|
|
223
|
+
const sourceTarget = resolve(sourceDirectory, ...link.path.split('/'));
|
|
224
|
+
if (!isContained(sourceRoot, sourceTarget) || hasSymlink(sourceRoot, sourceTarget)
|
|
225
|
+
|| !existsSync(sourceTarget) || !lstatSync(sourceTarget).isFile()) {
|
|
226
|
+
throw new Error('HTML local link target is no longer a contained regular file.');
|
|
227
|
+
}
|
|
228
|
+
const canonicalTarget = realpathSync(sourceTarget);
|
|
229
|
+
if (!isContained(sourceRoot, canonicalTarget))
|
|
230
|
+
throw new Error('HTML local link target is outside the permitted project root.');
|
|
231
|
+
const outputDirectory = realpathSync(dirname(resolve(context.outputPath)));
|
|
232
|
+
const relativePath = relative(outputDirectory, canonicalTarget);
|
|
233
|
+
if (!relativePath || isAbsolute(relativePath))
|
|
234
|
+
throw new Error('HTML local link target cannot be represented relative to the final HTML destination.');
|
|
235
|
+
const encodedPath = relativePath.split(sep).map(segment => encodeURIComponent(segment)).join('/');
|
|
236
|
+
return `${encodedPath}${link.query === undefined ? '' : `?${link.query}`}${link.fragment === undefined ? '' : `#${link.fragment}`}`;
|
|
237
|
+
}
|
|
238
|
+
function hasHtmlAssets(blocks) {
|
|
239
|
+
return blocks.some(block => {
|
|
240
|
+
if (block.type === 'pageBreak' || block.type === 'table')
|
|
241
|
+
return true;
|
|
242
|
+
if (block.type === 'blockquote')
|
|
243
|
+
return hasHtmlAssets(block.blocks);
|
|
244
|
+
if (block.type === 'list')
|
|
245
|
+
return block.items.some(item => hasHtmlAssets(item.blocks));
|
|
246
|
+
return block.type === 'paragraph' || block.type === 'heading'
|
|
247
|
+
? hasInlineHtmlAssets(block.children)
|
|
248
|
+
: false;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
function hasInlineHtmlAssets(inlines) {
|
|
252
|
+
return inlines.some(inline => inline.type === 'image'
|
|
253
|
+
|| (inline.type === 'link' || inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete')
|
|
254
|
+
&& hasInlineHtmlAssets(inline.children));
|
|
255
|
+
}
|
|
256
|
+
function renderNarrativeAssets(nonce) {
|
|
257
|
+
return `<style nonce="${nonce}">.openamx-narrative-image{display:block;max-width:100%;height:auto}.openamx-narrative-table{border-collapse:collapse;width:100%;margin:1rem 0}.openamx-narrative-table th,.openamx-narrative-table td{border:1px solid #a8b3bd;padding:.4rem;text-align:left}.openamx-page-break{break-before:page;page-break-before:always}@media screen{.openamx-page-break{border-top:1px dashed #a8b3bd;margin:1.5rem 0}}</style>`;
|
|
258
|
+
}
|
|
259
|
+
function renderPreviewNavigationBootstrap(nonce, previewToken) {
|
|
260
|
+
const token = JSON.stringify(previewToken);
|
|
261
|
+
return `<script nonce="${nonce}">(()=>{const token=${token};let port;window.addEventListener("message",event=>{const data=event.data;if(event.source!==parent||!data||data.type!=="openamx-preview-init"||data.previewToken!==token||event.ports.length!==1)return;port=event.ports[0];port.start()},{once:true});document.addEventListener("click",event=>{const source=event.target;if(!(source instanceof Element))return;const link=source.closest("a[data-openamx-target]");if(!link)return;event.preventDefault();if(!event.isTrusted||!navigator.userActivation?.isActive||!port)return;const targetId=link.getAttribute("data-openamx-target");if(!targetId)return;port.postMessage({version:1,type:"navigate",previewToken:token,targetId})},true)})();</script>`;
|
|
262
|
+
}
|
|
263
|
+
function renderViewEmission(emission, identity) {
|
|
264
|
+
if (emission.kind === 'table')
|
|
265
|
+
return renderTable(emission);
|
|
266
|
+
return renderChart(emission, identity);
|
|
267
|
+
}
|
|
268
|
+
function renderSafeMarkdown(markdown) {
|
|
269
|
+
return sanitizeHtml(marked.parse(markdown), REPORT_MARKDOWN_POLICY);
|
|
270
|
+
}
|
|
271
|
+
function renderTable(emission) {
|
|
272
|
+
const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
|
|
273
|
+
const columns = emission.declaration.options.filter(option => option.type === 'tableColumnOption');
|
|
274
|
+
const id = viewId(emission);
|
|
275
|
+
const rows = emission.data.filter(isRecordValue);
|
|
276
|
+
const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
|
|
277
|
+
const header = columns.map(column => `<th scope="col" aria-sort="none"><button type="button" data-sort="${escapeHtml(column.field)}">${escapeHtml(column.label)}</button></th>`).join('');
|
|
278
|
+
const body = rows.map((row, index) => `<tr data-row-index="${index}">${columns.map(column => `<td>${escapeHtml(valueToString(row[column.field]))}</td>`).join('')}</tr>`).join('');
|
|
279
|
+
const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${escapeHtml(valueToString(row[column.field]))}</td>`).join('')}</tr>`).join('');
|
|
280
|
+
const payload = safeJson({ columns: columns.map(column => ({ field: column.field, label: column.label })), rows });
|
|
281
|
+
return `<section class="openamx-view openamx-table" data-view="${id}" aria-labelledby="${id}-caption">
|
|
282
|
+
<h2 id="${id}-caption" class="sr-only">${escapeHtml(caption)}</h2>
|
|
283
|
+
<div class="openamx-table-controls"><label>Filter <input type="search" data-filter aria-controls="${id}-interactive"></label><label>Rows <select data-page-size aria-controls="${id}-interactive"><option>10</option><option selected>25</option><option>50</option></select></label></div>
|
|
284
|
+
<p class="openamx-status" data-status aria-live="polite"></p>
|
|
285
|
+
<table id="${id}-interactive"><caption>${escapeHtml(caption)}</caption><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>
|
|
286
|
+
<nav class="openamx-pagination" aria-label="${escapeHtml(caption)} pages"><button type="button" data-page="previous" aria-label="Previous page">Previous</button><span data-page-label></span><button type="button" data-page="next" aria-label="Next page">Next</button></nav>
|
|
287
|
+
<script type="application/json" id="${id}-data">${payload}</script>
|
|
288
|
+
<div class="openamx-print-view"><table><caption>${escapeHtml(caption)}</caption><thead><tr>${columns.map(column => `<th scope="col">${escapeHtml(column.label)}</th>`).join('')}</tr></thead><tbody>${printBody}</tbody></table></div>
|
|
289
|
+
</section>`;
|
|
290
|
+
}
|
|
291
|
+
function renderChart(emission, identity) {
|
|
292
|
+
const accent = identity.accent && /^#[0-9A-Fa-f]{6}$/.test(identity.accent) ? identity.accent : '#146C94';
|
|
293
|
+
const model = createChartViewModel(emission, { accent });
|
|
294
|
+
const browserModel = serializeChartModel(model);
|
|
295
|
+
const id = model.table.id;
|
|
296
|
+
const titleId = `${id}-title`;
|
|
297
|
+
const descriptionId = `${id}-description`;
|
|
298
|
+
const summaryId = `${id}-summary`;
|
|
299
|
+
const seriesControls = model.series.length > 1
|
|
300
|
+
? `<div class="openamx-chart-legend" role="group" aria-label="Chart series">${model.series.map(series => `<button type="button" class="openamx-legend-toggle" data-series="${escapeHtml(series.name)}" aria-pressed="true"><span aria-hidden="true" style="--series-color:${escapeHtml(series.color)}"></span>${escapeHtml(series.name)}</button>`).join('')}</div>`
|
|
301
|
+
: '';
|
|
302
|
+
const zoomControls = browserModel.zoomable
|
|
303
|
+
? `<div class="openamx-chart-controls" role="group" aria-label="Chart zoom controls"><button type="button" data-zoom="out" aria-label="Zoom out">Zoom out</button><button type="button" data-zoom="in" aria-label="Zoom in">Zoom in</button><button type="button" data-zoom="reset">Reset zoom</button></div>`
|
|
304
|
+
: '';
|
|
305
|
+
const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${escapeHtml(valueToString(value))}</td>`).join('')}</tr>`).join('');
|
|
306
|
+
const data = safeJson(browserModel);
|
|
307
|
+
return `<figure class="openamx-view openamx-chart" id="${id}-figure" data-openamx-chart aria-labelledby="${titleId}" aria-describedby="${descriptionId} ${summaryId}">
|
|
308
|
+
<figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
|
|
309
|
+
<p id="${summaryId}" class="sr-only">${escapeHtml(model.accessibility.summary)}</p>
|
|
310
|
+
${seriesControls}${zoomControls}
|
|
311
|
+
<div id="${id}-plot" class="openamx-chart-plot" role="img" aria-label="${escapeHtml(model.title)}" aria-describedby="${descriptionId} ${summaryId} ${id}-table-caption"></div>
|
|
312
|
+
<table class="openamx-chart-data" id="${id}"><caption id="${id}-table-caption">${escapeHtml(model.table.caption)}</caption><thead><tr>${model.table.headings.map(value => `<th scope="col">${escapeHtml(value)}</th>`).join('')}</tr></thead><tbody>${textRows}</tbody></table>
|
|
313
|
+
<script type="application/json" data-chart-model>${data}</script>
|
|
314
|
+
</figure>`;
|
|
315
|
+
}
|
|
316
|
+
function serializeChartModel(model) {
|
|
317
|
+
const formatterPaths = [];
|
|
318
|
+
const option = projectSerializable(model.option, '$', formatterPaths);
|
|
319
|
+
const zoomable = model.kind === 'scatter' || (model.kind === 'line' && model.option.xAxis !== undefined
|
|
320
|
+
&& !isCategoryAxis(model.option.xAxis));
|
|
321
|
+
if (zoomable) {
|
|
322
|
+
const zoom = [{ type: 'inside', xAxisIndex: 0, ...(model.kind === 'scatter' ? { yAxisIndex: 0 } : {}), filterMode: 'none', zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: true }];
|
|
323
|
+
optionProperty(option, 'dataZoom', zoom);
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
kind: model.kind,
|
|
327
|
+
title: model.title,
|
|
328
|
+
description: model.description,
|
|
329
|
+
dimensions: model.dimensions,
|
|
330
|
+
option,
|
|
331
|
+
formatterPaths,
|
|
332
|
+
table: model.table,
|
|
333
|
+
series: model.series,
|
|
334
|
+
axes: model.axes,
|
|
335
|
+
accessibility: model.accessibility,
|
|
336
|
+
plottedPointCount: model.plottedPointCount,
|
|
337
|
+
...(model.emptyState ? { emptyState: model.emptyState } : {}),
|
|
338
|
+
...(model.dateTimePresentation ? { dateTimePresentation: model.dateTimePresentation } : {}),
|
|
339
|
+
zoomable
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function projectSerializable(value, path, formatterPaths) {
|
|
343
|
+
if (typeof value === 'function') {
|
|
344
|
+
const allowed = path === '$.tooltip.formatter'
|
|
345
|
+
|| /\.(xAxis|yAxis)(\.\d+)?\.axisLabel\.formatter$/.test(path)
|
|
346
|
+
|| /\.(xAxis|yAxis)(\.\d+)?\.axisPointer\.label\.formatter$/.test(path);
|
|
347
|
+
if (!allowed)
|
|
348
|
+
throw new Error(`Unsupported function in chart model at ${path}.`);
|
|
349
|
+
formatterPaths.push(path);
|
|
350
|
+
return undefined;
|
|
351
|
+
}
|
|
352
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
353
|
+
return value;
|
|
354
|
+
if (typeof value === 'number') {
|
|
355
|
+
if (!Number.isFinite(value))
|
|
356
|
+
throw new Error(`Non-finite chart value at ${path}.`);
|
|
357
|
+
return value;
|
|
358
|
+
}
|
|
359
|
+
if (Array.isArray(value)) {
|
|
360
|
+
return value.map((item, index) => projectSerializable(item, `${path}.${index}`, formatterPaths) ?? null);
|
|
361
|
+
}
|
|
362
|
+
if (typeof value === 'object') {
|
|
363
|
+
const projected = {};
|
|
364
|
+
for (const [key, item] of Object.entries(value)) {
|
|
365
|
+
const itemPath = `${path}.${key}`;
|
|
366
|
+
const itemProjection = projectSerializable(item, itemPath, formatterPaths);
|
|
367
|
+
if (itemProjection !== undefined)
|
|
368
|
+
projected[key] = itemProjection;
|
|
369
|
+
}
|
|
370
|
+
return projected;
|
|
371
|
+
}
|
|
372
|
+
if (value === undefined)
|
|
373
|
+
return undefined;
|
|
374
|
+
throw new Error(`Unsupported chart model value at ${path}.`);
|
|
375
|
+
}
|
|
376
|
+
function optionProperty(option, key, value) {
|
|
377
|
+
if (option === null || Array.isArray(option) || typeof option !== 'object')
|
|
378
|
+
throw new Error('Chart option projection is not an object.');
|
|
379
|
+
option[key] = value;
|
|
380
|
+
}
|
|
381
|
+
function isCategoryAxis(axis) {
|
|
382
|
+
const first = Array.isArray(axis) ? axis[0] : axis;
|
|
383
|
+
return first?.type === 'category' || first?.type === undefined;
|
|
384
|
+
}
|
|
385
|
+
function viewId(emission) {
|
|
386
|
+
return `openamx-view-${emission.documentNodeIndex}-${emission.statementIndex}`;
|
|
387
|
+
}
|
|
388
|
+
function isRecordValue(value) {
|
|
389
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
390
|
+
}
|
|
391
|
+
function safeJson(value) {
|
|
392
|
+
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');
|
|
393
|
+
}
|
|
394
|
+
function renderContentSecurityPolicy(nonce, hasViews, hasPreviewNavigation = false) {
|
|
395
|
+
const scripts = hasViews || hasPreviewNavigation ? `'nonce-${nonce}'` : "'none'";
|
|
396
|
+
const styles = hasViews || nonce ? `'nonce-${nonce}'` : "'none'";
|
|
397
|
+
const styleAttributes = hasViews ? "; style-src-attr 'unsafe-inline'" : '';
|
|
398
|
+
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${scripts}; style-src ${styles}${styleAttributes}; img-src data:; font-src data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; worker-src 'none'; media-src 'none'">`;
|
|
399
|
+
}
|
|
400
|
+
function safeAccentStyle(accent, nonce) {
|
|
401
|
+
if (!accent || !/^#[0-9A-Fa-f]{6}$/.test(accent) || accent.toLowerCase() === '#146c94')
|
|
402
|
+
return '';
|
|
403
|
+
return `<style nonce="${nonce}">:root{--openamx-accent:${accent};}</style>`;
|
|
404
|
+
}
|
|
405
|
+
function renderChartBootstrap() {
|
|
406
|
+
return `(()=>{
|
|
407
|
+
const charts=new Map();
|
|
408
|
+
const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,char=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[char]));
|
|
409
|
+
const iso=value=>{const date=new Date(typeof value==='number'?value:Date.parse(value));return Number.isNaN(date.getTime())?'':date.toISOString()};
|
|
410
|
+
const locate=(object,path)=>path.slice(2).split('.').reduce((current,key)=>current==null?undefined:current[/^\\d+$/.test(key)?Number(key):key],object);
|
|
411
|
+
const rowLabel=(value,model)=>{const row=model.table.rows.find(item=>item.id===String(value));return row?String(row.values[0]??''):String(value??'')};
|
|
412
|
+
const axisLabel=(value,model)=>model.dateTimePresentation?iso(value):rowLabel(value,model);
|
|
413
|
+
const formatTooltip=(input,model)=>{const entries=(Array.isArray(input)?input:[input]).filter(item=>item&&typeof item==='object');return entries.map(entry=>{const series=model.series.find(item=>item.id===entry.seriesId||item.name===entry.seriesName);const values=Array.isArray(entry.value)?entry.value:[];if(model.kind==='scatter'){const x=values[0]??null,y=values[1]??null;const xUnit=model.axes.find(item=>item.role==='x')?.name,yUnit=model.axes.find(item=>item.role==='y')?.name;return '<div><strong>'+escapeHtml(entry.seriesName||'')+'</strong><br>x: '+escapeHtml(x)+(xUnit?' '+escapeHtml(xUnit):'')+'<br>y: '+escapeHtml(y)+(yUnit?' '+escapeHtml(yUnit):'')+'</div>'}const rawCategory=entry.axisValue??values[0]??entry.name;const category=model.dateTimePresentation?iso(rawCategory):rowLabel(rawCategory,model);const value=model.kind==='line'?values[1]:entry.value;const categoryUnit=model.kind==='line'?model.axes.find(item=>item.role==='x')?.name:undefined;const coordinate=escapeHtml(category)+(categoryUnit?' '+escapeHtml(categoryUnit):'');return '<div><strong>'+escapeHtml(entry.seriesName||'')+'</strong><br>'+coordinate+': '+escapeHtml(value)+(series?.unit?.text?' '+escapeHtml(series.unit.text):'')+'</div>'}).join('')};
|
|
414
|
+
const setZoom=(chart,zoom)=>{const current=chart.getOption().dataZoom?.[0]??{start:0,end:100};chart.setOption({dataZoom:[{...current,...zoom}]})};
|
|
415
|
+
const restoreFormatters=model=>{for(const path of model.formatterPaths){const key=path.split('.').at(-1),parentPath=path.slice(0,path.lastIndexOf('.')),parent=locate(model.option,parentPath);if(!parent)throw new Error('Chart formatter path is invalid.');if(path==='$.tooltip.formatter')parent[key]=params=>formatTooltip(params,model);else if(parentPath.endsWith('.axisPointer.label'))parent[key]=params=>iso(params?.value);else parent[key]=value=>axisLabel(value,model)}};
|
|
416
|
+
const initialize=root=>{const payloadNode=root.querySelector('[data-chart-model]'),plot=root.querySelector('.openamx-chart-plot');if(!payloadNode||!plot)return;const model=JSON.parse(payloadNode.textContent||'null');restoreFormatters(model);const chart=echarts.init(plot,null,{renderer:'canvas'});chart.setOption(model.option);root.querySelectorAll('[data-series]').forEach(button=>button.addEventListener('click',()=>chart.dispatchAction({type:'legendToggleSelect',name:button.dataset.series})));chart.on('legendselectchanged',event=>root.querySelectorAll('[data-series]').forEach(button=>button.setAttribute('aria-pressed',String(event.selected?.[button.dataset.series]!==false))));root.querySelectorAll('[data-zoom]').forEach(button=>button.addEventListener('click',()=>{const current=chart.getOption().dataZoom?.[0]??{start:0,end:100},span=(current.end??100)-(current.start??0);if(button.dataset.zoom==='reset')setZoom(chart,{start:0,end:100});else{const next=Math.max(5,Math.min(100,span*(button.dataset.zoom==='in'?.75:1.33))),center=((current.start??0)+(current.end??100))/2;setZoom(chart,{start:Math.max(0,center-next/2),end:Math.min(100,center+next/2)})}}));const resizeObserver=new ResizeObserver(()=>chart.resize());resizeObserver.observe(plot);charts.set(root,{chart,resizeObserver})};
|
|
417
|
+
const dispose=root=>{const item=charts.get(root);if(!item)return;item.resizeObserver.disconnect();item.chart.dispose();charts.delete(root)};
|
|
418
|
+
const start=()=>{
|
|
419
|
+
document.querySelectorAll('[data-openamx-chart]').forEach(initialize);
|
|
420
|
+
const mutationObserver=new MutationObserver(()=>{for(const root of charts.keys())if(!document.documentElement.contains(root))dispose(root)});mutationObserver.observe(document.documentElement,{childList:true,subtree:true});
|
|
421
|
+
window.addEventListener('pagehide',()=>{for(const root of charts.keys())dispose(root);mutationObserver.disconnect()},{once:true});
|
|
422
|
+
};
|
|
423
|
+
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
|
|
424
|
+
})();`;
|
|
425
|
+
}
|
|
426
|
+
function renderViewAssets(nonce) {
|
|
427
|
+
const assets = `<style>
|
|
428
|
+
.openamx-view{margin:1.5rem 0}.openamx-view table{border-collapse:collapse;width:100%}.openamx-view th,.openamx-view td{border:1px solid #a8b3bd;padding:.4rem;text-align:left}.openamx-view th button{font:inherit;font-weight:700;background:none;border:0;padding:0;cursor:pointer}.openamx-table-controls{display:flex;gap:1rem;flex-wrap:wrap;margin:.5rem 0}.openamx-status{min-height:1.4em}.openamx-pagination{display:flex;gap:.75rem;align-items:center;margin:.5rem 0}.openamx-chart svg{display:block;width:100%;max-width:40rem;height:auto;border:1px solid #a8b3bd}.openamx-chart figcaption{display:flex;flex-direction:column;gap:.25rem}.openamx-chart-data{margin-top:.75rem}.openamx-print-view,.openamx-print-chart{display:none}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media print{.openamx-table-controls,.openamx-status,.openamx-pagination,.openamx-table>table,.openamx-chart>svg,.openamx-chart-data{display:none}.openamx-print-view,.openamx-print-chart{display:block}.openamx-view{break-inside:avoid}.openamx-view th{background:#eee}.openamx-view thead{display:table-header-group}}
|
|
429
|
+
</style>
|
|
430
|
+
<script>
|
|
431
|
+
document.addEventListener('DOMContentLoaded',()=>{for(const root of document.querySelectorAll('[data-view].openamx-table')){const table=root.querySelector('table[id$="-interactive"]'),body=table?.querySelector('tbody'),filter=root.querySelector('[data-filter]'),size=root.querySelector('[data-page-size]'),status=root.querySelector('[data-status]'),pageLabel=root.querySelector('[data-page-label]');if(!table||!body||!filter||!size||!status||!pageLabel)continue;const payload=JSON.parse(document.getElementById(root.dataset.view+'-data').textContent),rows=[...body.querySelectorAll('tr')],original=rows.map((row,index)=>({row,index,text:row.textContent?.toLowerCase()??''}));let page=0,pageSize=25,sortField='',ascending=true;const update=()=>{let visible=original.filter(item=>item.text.includes(filter.value.toLowerCase()));if(sortField){visible.sort((a,b)=>{const av=payload.rows[a.index][sortField],bv=payload.rows[b.index][sortField];if(av===null&&bv!==null)return 1;if(av!==null&&bv===null)return -1;let result=av===bv?0:av<bv?-1:1;return (ascending?result:-result)||a.index-b.index})}visible.forEach(item=>body.appendChild(item.row));const pages=Math.max(1,Math.ceil(visible.length/pageSize));page=Math.min(page,pages-1);rows.forEach(row=>row.hidden=true);visible.slice(page*pageSize,(page+1)*pageSize).forEach(item=>item.row.hidden=false);status.textContent=visible.length===0?(filter.value?'No matching rows':'No rows'):'Showing '+(page*pageSize+1)+'-'+Math.min((page+1)*pageSize,visible.length)+' of '+visible.length+' rows';pageLabel.textContent='Page '+(page+1)+' of '+pages;root.querySelector('[data-page="previous"]').disabled=page===0;root.querySelector('[data-page="next"]').disabled=page>=pages-1};filter.addEventListener('input',()=>{page=0;update()});size.addEventListener('change',()=>{pageSize=Number(size.value);page=0;update()});root.querySelectorAll('[data-sort]').forEach(button=>button.addEventListener('click',()=>{const next=button.dataset.sort??'';ascending=sortField===next?!ascending:true;sortField=next;table.querySelectorAll('th').forEach(th=>th.setAttribute('aria-sort',th.querySelector('button')===button?(ascending?'ascending':'descending'):'none'));page=0;update()}));root.querySelector('[data-page="previous"]').addEventListener('click',()=>{page--;update()});root.querySelector('[data-page="next"]').addEventListener('click',()=>{page++;update()});update()}});
|
|
432
|
+
</script>`;
|
|
433
|
+
return assets
|
|
434
|
+
.replace('<style>', `<style nonce="${nonce}">`)
|
|
435
|
+
.replace('<script>', `<script nonce="${nonce}">`)
|
|
436
|
+
.replace('</script>', `</script><style nonce="${nonce}">.openamx-chart-plot{width:100%;min-width:320px;height:360px}.openamx-chart-legend,.openamx-chart-controls{display:flex;align-items:center;flex-wrap:wrap;gap:.5rem;margin:.5rem 0}.openamx-legend-toggle{display:inline-flex;align-items:center;gap:.4rem}.openamx-legend-toggle span{width:.75rem;height:.75rem;border-radius:50%;background:var(--series-color);flex:none}.openamx-legend-toggle[aria-pressed="false"]{opacity:.55}@media print{.openamx-chart-controls,.openamx-chart-legend{display:none!important}.openamx-chart-plot{min-width:0;break-inside:avoid}.openamx-chart-data{display:table!important}}</style><script nonce="${nonce}">${echartsBrowserRuntime}</script><script nonce="${nonce}">${renderChartBootstrap()}</script>`);
|
|
437
|
+
}
|
|
438
|
+
function renderReportHeader(report, _file) {
|
|
439
|
+
const org = report.organization?.trim();
|
|
440
|
+
const author = report.author?.trim();
|
|
441
|
+
const status = report.status?.trim();
|
|
442
|
+
const classification = report.classification?.trim();
|
|
443
|
+
const footer = report.footer?.trim();
|
|
444
|
+
const logo = report.logo?.trim();
|
|
445
|
+
if (!org && !author && !status && !classification && !logo && !footer) {
|
|
446
|
+
return '';
|
|
447
|
+
}
|
|
448
|
+
const logoMarkup = logo ? `<img class="openamx-report-logo" src="${escapeHtml(logo)}" alt="${escapeHtml(report.logoAlt ?? 'Report logo')}" />` : '';
|
|
449
|
+
const meta = [
|
|
450
|
+
org ? `<div class="openamx-report-attr">${escapeHtml(org)}</div>` : '',
|
|
451
|
+
author ? `<div class="openamx-report-attr">Author: ${escapeHtml(author)}</div>` : '',
|
|
452
|
+
status ? `<div class="openamx-report-attr">Status: ${escapeHtml(status)}</div>` : '',
|
|
453
|
+
classification ? `<div class="openamx-report-attr">Classification: ${escapeHtml(classification)}</div>` : '',
|
|
454
|
+
footer ? `<div class="openamx-report-attr">${escapeHtml(footer)}</div>` : '',
|
|
455
|
+
].filter(Boolean).join('');
|
|
456
|
+
return `<header class="openamx-report-header"><div class="openamx-report-identity">${logoMarkup}<div class="openamx-report-meta">${meta || '<div class="openamx-report-attr">OpenAMX report</div>'}</div></div></header>`;
|
|
457
|
+
}
|
|
458
|
+
function resolveReportIdentity(doc, override) {
|
|
459
|
+
const metadata = (doc.metadata ?? {});
|
|
460
|
+
const frontMatterReport = isRecord(metadata.report) ? metadata.report : {};
|
|
461
|
+
const merged = { ...frontMatterReport, ...override };
|
|
462
|
+
const sourceVisible = merged.sourceVisible === undefined ? true : Boolean(merged.sourceVisible);
|
|
463
|
+
const logo = typeof merged.logo === 'string' ? merged.logo : undefined;
|
|
464
|
+
if (logo)
|
|
465
|
+
throw new AmxError({ code: 'AMX6001', message: 'Logo reports require shared report preparation' });
|
|
466
|
+
return {
|
|
467
|
+
organization: stringOrUndefined(merged.organization),
|
|
468
|
+
logo: undefined,
|
|
469
|
+
logoAlt: stringOrUndefined(merged.logoAlt),
|
|
470
|
+
accent: stringOrUndefined(merged.accent),
|
|
471
|
+
author: stringOrUndefined(merged.author),
|
|
472
|
+
status: stringOrUndefined(merged.status),
|
|
473
|
+
classification: stringOrUndefined(merged.classification),
|
|
474
|
+
footer: stringOrUndefined(merged.footer),
|
|
475
|
+
sourceVisible,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
function stringOrUndefined(value) {
|
|
479
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
|
|
480
|
+
}
|
|
481
|
+
function isRecord(value) {
|
|
482
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
483
|
+
}
|
|
484
|
+
function substituteInlines(content, env, file, narrativeLine) {
|
|
485
|
+
// Non-nested {{ expr }} substitution. Expressions cannot contain literal "}}" per v0.1.
|
|
486
|
+
return content.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_full, exprText) => {
|
|
487
|
+
const trimmed = exprText.trim();
|
|
488
|
+
if (trimmed.length === 0) {
|
|
489
|
+
return '';
|
|
490
|
+
}
|
|
491
|
+
// Attach approximate source for better diagnostics (narrative block start line).
|
|
492
|
+
const source = narrativeLine !== undefined ? { line: narrativeLine, column: 1 } : undefined;
|
|
493
|
+
const exprNode = parseExpression(trimmed, source);
|
|
494
|
+
const value = evaluateExpression(exprNode, env, file);
|
|
495
|
+
return escapeHtml(valueToString(value));
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
function valueToString(v) {
|
|
499
|
+
if (v === null || v === undefined)
|
|
500
|
+
return '';
|
|
501
|
+
if (typeof v === 'string')
|
|
502
|
+
return v;
|
|
503
|
+
if (typeof v === 'number') {
|
|
504
|
+
// Present integers without trailing .0 for natural readability in text.
|
|
505
|
+
return Number.isInteger(v) ? String(v) : String(v);
|
|
506
|
+
}
|
|
507
|
+
if (typeof v === 'boolean')
|
|
508
|
+
return String(v); // "true" / "false"
|
|
509
|
+
if (Array.isArray(v)) {
|
|
510
|
+
// Simple deterministic representation for lists inside narrative text.
|
|
511
|
+
return v.map(valueToString).join(', ');
|
|
512
|
+
}
|
|
513
|
+
return String(v);
|
|
514
|
+
}
|
|
515
|
+
function escapeHtml(s) {
|
|
516
|
+
return s
|
|
517
|
+
.replace(/&/g, '&')
|
|
518
|
+
.replace(/</g, '<')
|
|
519
|
+
.replace(/>/g, '>')
|
|
520
|
+
.replace(/"/g, '"');
|
|
521
|
+
}
|