@nova-energy/openamx 0.10.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  /// <reference path="../types/echarts-runtime.d.ts" />
2
2
  import { randomBytes } from 'node:crypto';
3
+ import { existsSync, lstatSync, realpathSync } from 'node:fs';
4
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
5
  import echartsBrowserRuntime from 'echarts/dist/echarts.min.js' with { type: 'text' };
4
6
  import { marked } from 'marked';
5
7
  import sanitizeHtml from 'sanitize-html';
@@ -9,6 +11,8 @@ import { evaluateExpression } from '../runtime/evaluateExpression';
9
11
  import { evaluateDocumentEnvironment } from '../runtime/evaluateDocument';
10
12
  import { formatAmx } from '../formatter/formatAmx';
11
13
  import { createChartViewModel } from './chartModel';
14
+ import { fitNarrativeImage } from './narrativeModel';
15
+ import { hasSymlink, isContained } from './reportPaths';
12
16
  const REPORT_MARKDOWN_POLICY = {
13
17
  allowedTags: [
14
18
  'a', 'blockquote', 'br', 'code', 'del', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
@@ -73,18 +77,28 @@ export function renderHtml(doc, file, env, options) {
73
77
  const nonce = hasViews || !!resolvedReport.accent ? randomBytes(18).toString('base64') : '';
74
78
  const accentStyle = safeAccentStyle(resolvedReport.accent, nonce);
75
79
  const viewAssets = hasViews ? renderViewAssets(nonce) : '';
76
- return `<!doctype html>
77
- <html>
78
- <head>
79
- <meta charset="utf-8">
80
- ${renderContentSecurityPolicy(nonce, hasViews)}
81
- <title>${escapedTitle}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
82
- </head>
83
- <body>
84
- ${bodyHtml}</body>
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>
85
89
  </html>`;
86
90
  }
87
- export function renderPreparedHtml(report) {
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
+ };
88
102
  const bodyFragments = [];
89
103
  const identity = report.identity;
90
104
  const metadata = [
@@ -99,7 +113,7 @@ export function renderPreparedHtml(report) {
99
113
  }
100
114
  for (const item of report.items) {
101
115
  if (item.type === 'narrative')
102
- bodyFragments.push(renderSafeMarkdown(item.text));
116
+ bodyFragments.push(renderNarrativeBlocks(item.markdown, context));
103
117
  else if (item.type === 'source')
104
118
  bodyFragments.push(`<pre><code class="language-amx">${escapeHtml(item.text)}</code></pre>`);
105
119
  else
@@ -108,19 +122,143 @@ export function renderPreparedHtml(report) {
108
122
  if (identity.footer)
109
123
  bodyFragments.push(`<footer class="openamx-report-footer">${escapeHtml(identity.footer)}</footer>`);
110
124
  const hasViews = report.items.some(item => item.type === 'view');
111
- const nonce = hasViews || identity.accent !== '#146C94' ? randomBytes(18).toString('base64') : '';
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') : '';
112
127
  const accentStyle = safeAccentStyle(identity.accent, nonce);
113
128
  const viewAssets = hasViews ? renderViewAssets(nonce) : '';
114
- return `<!doctype html>
115
- <html>
116
- <head>
117
- <meta charset="utf-8">
118
- ${renderContentSecurityPolicy(nonce, hasViews)}
119
- <title>${escapeHtml(report.title)}</title>${accentStyle ? `\n${accentStyle}` : ''}${viewAssets ? `\n${viewAssets}` : ''}
120
- </head>
121
- <body>
122
- ${bodyFragments.join('')}</body>
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>
123
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>`;
124
262
  }
125
263
  function renderViewEmission(emission, identity) {
126
264
  if (emission.kind === 'table')
@@ -140,14 +278,14 @@ function renderTable(emission) {
140
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('');
141
279
  const printBody = rows.map(row => `<tr>${columns.map(column => `<td>${escapeHtml(valueToString(row[column.field]))}</td>`).join('')}</tr>`).join('');
142
280
  const payload = safeJson({ columns: columns.map(column => ({ field: column.field, label: column.label })), rows });
143
- return `<section class="openamx-view openamx-table" data-view="${id}" aria-labelledby="${id}-caption">
144
- <h2 id="${id}-caption" class="sr-only">${escapeHtml(caption)}</h2>
145
- <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>
146
- <p class="openamx-status" data-status aria-live="polite"></p>
147
- <table id="${id}-interactive"><caption>${escapeHtml(caption)}</caption><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>
148
- <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>
149
- <script type="application/json" id="${id}-data">${payload}</script>
150
- <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>
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>
151
289
  </section>`;
152
290
  }
153
291
  function renderChart(emission, identity) {
@@ -166,13 +304,13 @@ function renderChart(emission, identity) {
166
304
  : '';
167
305
  const textRows = model.table.rows.map(row => `<tr>${row.values.map(value => `<td>${escapeHtml(valueToString(value))}</td>`).join('')}</tr>`).join('');
168
306
  const data = safeJson(browserModel);
169
- return `<figure class="openamx-view openamx-chart" id="${id}-figure" data-openamx-chart aria-labelledby="${titleId}" aria-describedby="${descriptionId} ${summaryId}">
170
- <figcaption><strong id="${titleId}">${escapeHtml(model.title)}</strong><span id="${descriptionId}">${escapeHtml(model.description)}</span></figcaption>
171
- <p id="${summaryId}" class="sr-only">${escapeHtml(model.accessibility.summary)}</p>
172
- ${seriesControls}${zoomControls}
173
- <div id="${id}-plot" class="openamx-chart-plot" role="img" aria-label="${escapeHtml(model.title)}" aria-describedby="${descriptionId} ${summaryId} ${id}-table-caption"></div>
174
- <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>
175
- <script type="application/json" data-chart-model>${data}</script>
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>
176
314
  </figure>`;
177
315
  }
178
316
  function serializeChartModel(model) {
@@ -253,8 +391,8 @@ function isRecordValue(value) {
253
391
  function safeJson(value) {
254
392
  return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');
255
393
  }
256
- function renderContentSecurityPolicy(nonce, hasViews) {
257
- const scripts = hasViews ? `'nonce-${nonce}'` : "'none'";
394
+ function renderContentSecurityPolicy(nonce, hasViews, hasPreviewNavigation = false) {
395
+ const scripts = hasViews || hasPreviewNavigation ? `'nonce-${nonce}'` : "'none'";
258
396
  const styles = hasViews || nonce ? `'nonce-${nonce}'` : "'none'";
259
397
  const styleAttributes = hasViews ? "; style-src-attr 'unsafe-inline'" : '';
260
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'">`;
@@ -265,32 +403,32 @@ function safeAccentStyle(accent, nonce) {
265
403
  return `<style nonce="${nonce}">:root{--openamx-accent:${accent};}</style>`;
266
404
  }
267
405
  function renderChartBootstrap() {
268
- return `(()=>{
269
- const charts=new Map();
270
- const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char]));
271
- const iso=value=>{const date=new Date(typeof value==='number'?value:Date.parse(value));return Number.isNaN(date.getTime())?'':date.toISOString()};
272
- const locate=(object,path)=>path.slice(2).split('.').reduce((current,key)=>current==null?undefined:current[/^\\d+$/.test(key)?Number(key):key],object);
273
- const rowLabel=(value,model)=>{const row=model.table.rows.find(item=>item.id===String(value));return row?String(row.values[0]??''):String(value??'')};
274
- const axisLabel=(value,model)=>model.dateTimePresentation?iso(value):rowLabel(value,model);
275
- 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('')};
276
- const setZoom=(chart,zoom)=>{const current=chart.getOption().dataZoom?.[0]??{start:0,end:100};chart.setOption({dataZoom:[{...current,...zoom}]})};
277
- 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)}};
278
- 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})};
279
- const dispose=root=>{const item=charts.get(root);if(!item)return;item.resizeObserver.disconnect();item.chart.dispose();charts.delete(root)};
280
- const start=()=>{
281
- document.querySelectorAll('[data-openamx-chart]').forEach(initialize);
282
- 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});
283
- window.addEventListener('pagehide',()=>{for(const root of charts.keys())dispose(root);mutationObserver.disconnect()},{once:true});
284
- };
285
- if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();
406
+ return `(()=>{
407
+ const charts=new Map();
408
+ const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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();
286
424
  })();`;
287
425
  }
288
426
  function renderViewAssets(nonce) {
289
- const assets = `<style>
290
- .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}}
291
- </style>
292
- <script>
293
- 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()}});
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()}});
294
432
  </script>`;
295
433
  return assets
296
434
  .replace('<style>', `<style nonce="${nonce}">`)