@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.
Files changed (44) hide show
  1. package/COMMERCIAL-LICENSE.md +74 -0
  2. package/LICENSE.md +660 -0
  3. package/README.md +537 -3
  4. package/dist/ast/types.js +2 -0
  5. package/dist/cli.js +197 -0
  6. package/dist/diagnostics/errors.js +94 -0
  7. package/dist/editor/completion.js +313 -0
  8. package/dist/editor/highlighting.js +224 -0
  9. package/dist/editor/moduleAnalysis.js +206 -0
  10. package/dist/editor/refactoring.js +46 -0
  11. package/dist/editor/sourceRanges.js +50 -0
  12. package/dist/editor/symbols.js +203 -0
  13. package/dist/formatter/formatAmx.js +79 -0
  14. package/dist/index.js +10 -0
  15. package/dist/parser/parseDocument.js +114 -0
  16. package/dist/parser/parseExpression.js +768 -0
  17. package/dist/parser/parseFor.js +53 -0
  18. package/dist/parser/parseFrontMatter.js +65 -0
  19. package/dist/parser/parseStatements.js +667 -0
  20. package/dist/parser/stringScanner.js +71 -0
  21. package/dist/renderer/chartModel.js +476 -0
  22. package/dist/renderer/narrativeModel.js +561 -0
  23. package/dist/renderer/renderHtml.js +521 -0
  24. package/dist/renderer/reportDocx.js +725 -0
  25. package/dist/renderer/reportPaths.js +31 -0
  26. package/dist/renderer/reportPdf.js +314 -0
  27. package/dist/renderer/reportPreparation.js +196 -0
  28. package/dist/runtime/csvTextSerialization.js +8 -0
  29. package/dist/runtime/dataText.js +191 -0
  30. package/dist/runtime/docxDestination.js +55 -0
  31. package/dist/runtime/environment.js +105 -0
  32. package/dist/runtime/evaluateDocument.js +32 -0
  33. package/dist/runtime/evaluateExpression.js +888 -0
  34. package/dist/runtime/externalUnits.js +91 -0
  35. package/dist/runtime/inputData.js +508 -0
  36. package/dist/runtime/measurement.js +110 -0
  37. package/dist/runtime/moduleLoader.js +279 -0
  38. package/dist/runtime/outputData.js +303 -0
  39. package/dist/runtime/pdfDestination.js +57 -0
  40. package/dist/runtime/standardLibrary.js +145 -0
  41. package/dist/typechecker/checkDocument.js +1282 -0
  42. package/dist/typechecker/declarationRegistry.js +7 -0
  43. package/dist/typechecker/dimensionTypes.js +1 -0
  44. package/package.json +33 -4
@@ -0,0 +1,725 @@
1
+ import { AlignmentType, Bookmark, BorderStyle, Document, ExternalHyperlink, HeadingLevel, ImageRun, InternalHyperlink, LevelFormat, Packer, Paragraph, Tab, TableLayoutType, Table, TableCell, TableRow, TextRun, WidthType, Footer } from 'docx';
2
+ import { ChartRun } from 'docx/charts';
3
+ import { realpathSync } from 'node:fs';
4
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { createChartViewModel } from './chartModel';
6
+ import { fitNarrativeImage } from './narrativeModel';
7
+ const TABLE_WIDTH_TWIPS = 9_026;
8
+ // ChartRun uses 15 twips per CSS pixel; leave one pixel of page-width clearance.
9
+ const DOCX_CHART_WIDTH_PIXELS = Math.floor(TABLE_WIDTH_TWIPS / 15) - 1;
10
+ const IMAGE_WIDTH_PIXELS = 601;
11
+ const IMAGE_HEIGHT_PIXELS = 864;
12
+ const MAX_BOOKMARK_NAME_LENGTH = 40;
13
+ export function prepareDocxReport(report, context) {
14
+ return preparePreparedDocxReport(report, context);
15
+ }
16
+ export async function serializeDocxReport(report) {
17
+ return Uint8Array.from(await Packer.toBuffer(report.document));
18
+ }
19
+ function preparePreparedDocxReport(report, exportContext) {
20
+ const children = [];
21
+ const identity = report.identity;
22
+ if (identity.logo || identity.organization || identity.author || identity.status || identity.classification) {
23
+ const runs = [];
24
+ if (identity.logo)
25
+ runs.push(new ImageRun({ type: 'png', data: identity.logo.bytes, transformation: { width: 120, height: 48 }, altText: { title: identity.logo.alt, description: identity.logo.alt, name: 'Report logo' } }));
26
+ const metadata = [identity.organization, identity.author && `Author: ${identity.author}`, identity.status && `Status: ${identity.status}`, identity.classification && `Classification: ${identity.classification}`].filter((value) => Boolean(value));
27
+ if (metadata.length > 0)
28
+ runs.push(new TextRun({ text: `${runs.length ? '\n' : ''}${metadata.join('\n')}`, bold: true }));
29
+ children.push(new Paragraph({ children: runs }));
30
+ }
31
+ const usedBookmarkNames = new Set();
32
+ const bookmarks = headingBookmarks(report.items.flatMap(item => item.type === 'narrative' ? item.markdown : []), usedBookmarkNames);
33
+ const numbering = [];
34
+ let nextListReference = 0;
35
+ for (const item of report.items) {
36
+ if (item.type === 'narrative') {
37
+ const context = {
38
+ exportContext,
39
+ bookmarks,
40
+ numbering,
41
+ quoteDepth: 0,
42
+ listDepth: 0
43
+ };
44
+ children.push(...renderBlocks(item.markdown, context, () => `openamx-list-${nextListReference++}`));
45
+ }
46
+ else if (item.type === 'source')
47
+ children.push(new Paragraph({ style: 'Normal', children: [new TextRun({ text: item.text, font: 'Courier New', size: 18 })] }));
48
+ else
49
+ addEmission(children, item.emission, identity);
50
+ }
51
+ return {
52
+ document: new Document({
53
+ title: report.title,
54
+ creator: identity.author ?? 'OpenAMX',
55
+ description: 'Editable OpenAMX report',
56
+ numbering: numbering.length > 0 ? { config: numbering } : undefined,
57
+ sections: [{ children, footers: identity.footer ? { default: new Footer({ children: [new Paragraph({ text: identity.footer })] }) } : undefined }]
58
+ })
59
+ };
60
+ }
61
+ function renderBlocks(blocks, context, nextListReference) {
62
+ return blocks.flatMap(block => renderBlock(block, context, nextListReference));
63
+ }
64
+ function renderBlock(block, context, nextListReference) {
65
+ if (block.type === 'heading') {
66
+ const runs = inlineChildren(block.children, context);
67
+ const bookmark = context.bookmarks.get(block.id);
68
+ const children = bookmark ? [new Bookmark({ id: bookmark, children: runs })] : runs;
69
+ return [new Paragraph(paragraphOptions(context, { heading: headingLevel(block.depth), children }))];
70
+ }
71
+ if (block.type === 'paragraph') {
72
+ return [new Paragraph(paragraphOptions(context, { children: inlineChildren(block.children, context) }))];
73
+ }
74
+ if (block.type === 'code') {
75
+ return [new Paragraph(paragraphOptions(context, {
76
+ children: codeChildren(block.text),
77
+ shading: { fill: 'F1F4F5' },
78
+ indent: { left: 180, right: 180 },
79
+ spacing: { before: 80, after: 80 }
80
+ }))];
81
+ }
82
+ if (block.type === 'list') {
83
+ const parentItem = context.listItem;
84
+ const prefix = parentItem && !parentItem.applied ? [listMarkerParagraph(context)] : [];
85
+ return [...prefix, ...renderList(block, {
86
+ ...context,
87
+ listItem: undefined,
88
+ listDepth: context.listDepth + (parentItem ? 1 : 0)
89
+ }, nextListReference)];
90
+ }
91
+ if (block.type === 'blockquote') {
92
+ const nestedContext = {
93
+ ...context,
94
+ quoteDepth: context.quoteDepth + 1,
95
+ listItem: context.listItem
96
+ };
97
+ return renderBlocks(block.blocks, nestedContext, nextListReference);
98
+ }
99
+ if (block.type === 'table') {
100
+ const widths = tableColumnWidths(block.header.length);
101
+ const header = new TableRow({
102
+ tableHeader: true,
103
+ cantSplit: true,
104
+ children: block.header.map((cell, index) => narrativeTableCell(cell, context, widths[index], index, block.align, true))
105
+ });
106
+ const rows = block.rows.map(row => new TableRow({
107
+ cantSplit: true,
108
+ children: block.header.map((_headerCell, index) => narrativeTableCell(row[index] ?? [], context, widths[index], index, block.align, false))
109
+ }));
110
+ const table = new Table({
111
+ rows: [header, ...rows],
112
+ width: { size: 200, type: WidthType.PERCENTAGE },
113
+ columnWidths: widths,
114
+ layout: TableLayoutType.FIXED,
115
+ margins: { top: 80, bottom: 80, left: 100, right: 100 }
116
+ });
117
+ if (context.listItem && !context.listItem.applied) {
118
+ return [listMarkerParagraph(context), table];
119
+ }
120
+ return [table];
121
+ }
122
+ if (block.type === 'horizontalRule') {
123
+ return [new Paragraph(paragraphOptions(context, {
124
+ children: [new TextRun({ text: ' ' })],
125
+ border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: '8A969C', space: 1 } },
126
+ spacing: { before: 120, after: 120 }
127
+ }))];
128
+ }
129
+ return [new Paragraph(paragraphOptions(context, { children: [], includeIfEmpty: true, pageBreakBefore: true }))];
130
+ }
131
+ function paragraphOptions(context, options) {
132
+ const quoteIndent = context.quoteDepth * 360;
133
+ const listItem = context.listItem;
134
+ const listIndent = listItem ? (listItem.level + 1) * 720 : 0;
135
+ const children = [...(options.children ?? [])];
136
+ if (listItem && !listItem.applied) {
137
+ if (listItem.checked !== undefined) {
138
+ children.unshift(new TextRun({ text: listItem.checked ? '[x] ' : '[ ] ' }));
139
+ }
140
+ listItem.applied = true;
141
+ return {
142
+ ...options,
143
+ children,
144
+ numbering: { reference: listItem.reference, level: listItem.level },
145
+ ...(quoteIndent > 0 ? { indent: { left: quoteIndent } } : {})
146
+ };
147
+ }
148
+ if (listItem || quoteIndent > 0) {
149
+ return {
150
+ ...options,
151
+ children,
152
+ indent: { left: listIndent + quoteIndent }
153
+ };
154
+ }
155
+ return { ...options, children };
156
+ }
157
+ function renderList(block, context, nextListReference) {
158
+ const reference = nextListReference();
159
+ const level = Math.min(context.listDepth, 8);
160
+ context.numbering.push({
161
+ reference,
162
+ levels: Array.from({ length: 9 }, (_value, index) => ({
163
+ level: index,
164
+ format: block.ordered ? LevelFormat.DECIMAL : LevelFormat.BULLET,
165
+ text: block.ordered ? `%${index + 1}.` : ['•', '◦', '▪'][index % 3],
166
+ ...(block.ordered && index === level && block.start !== undefined ? { start: block.start } : {}),
167
+ style: { paragraph: { indent: { left: (index + 1) * 720, hanging: 360 } } }
168
+ }))
169
+ });
170
+ const output = [];
171
+ for (const item of block.items) {
172
+ const listItem = { reference, level, checked: item.checked, applied: false };
173
+ const itemContext = { ...context, listItem };
174
+ for (const child of item.blocks) {
175
+ output.push(...renderBlock(child, itemContext, nextListReference));
176
+ }
177
+ if (!listItem.applied)
178
+ output.push(listMarkerParagraph(itemContext));
179
+ }
180
+ return output;
181
+ }
182
+ function listMarkerParagraph(context) {
183
+ return new Paragraph(paragraphOptions(context, { children: [], includeIfEmpty: true }));
184
+ }
185
+ function inlineChildren(inlines, context, style = {}) {
186
+ const children = [];
187
+ for (const inline of inlines) {
188
+ if (inline.type === 'text') {
189
+ if (inline.text)
190
+ children.push(new TextRun({ text: inline.text, ...style }));
191
+ }
192
+ else if (inline.type === 'lineBreak') {
193
+ children.push(new TextRun({ break: 1, ...style }));
194
+ }
195
+ else if (inline.type === 'inlineCode') {
196
+ children.push(new TextRun({
197
+ text: inline.text,
198
+ font: 'Consolas',
199
+ size: 18,
200
+ shading: { fill: 'F1F4F5' },
201
+ ...style
202
+ }));
203
+ }
204
+ else if (inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete') {
205
+ const nestedStyle = inline.type === 'strong'
206
+ ? { ...style, bold: true }
207
+ : inline.type === 'emphasis'
208
+ ? { ...style, italics: true }
209
+ : { ...style, strike: true };
210
+ children.push(...inlineChildren(inline.children, context, nestedStyle));
211
+ }
212
+ else if (inline.type === 'link') {
213
+ const linkChildren = inlineChildren(inline.children, context, { ...style, color: '0563C1', underline: {} });
214
+ const link = inline.link;
215
+ if (link.type === 'external') {
216
+ children.push(new ExternalHyperlink({ link: link.href, children: linkChildren }));
217
+ }
218
+ else if (link.type === 'internal') {
219
+ const anchor = context.bookmarks.get(link.targetId);
220
+ if (anchor)
221
+ children.push(new InternalHyperlink({ anchor, children: linkChildren }));
222
+ else
223
+ children.push(...linkChildren);
224
+ }
225
+ else {
226
+ children.push(new ExternalHyperlink({ link: localLinkUri(link, context.exportContext), children: linkChildren }));
227
+ }
228
+ }
229
+ else if (inline.type === 'image') {
230
+ children.push(narrativeImageRun(inline.image));
231
+ }
232
+ }
233
+ return children;
234
+ }
235
+ function codeChildren(text) {
236
+ const runs = [];
237
+ const lines = text.split('\n');
238
+ lines.forEach((line, lineIndex) => {
239
+ if (lineIndex > 0)
240
+ runs.push(new TextRun({ break: 1, font: 'Consolas', size: 18 }));
241
+ const pieces = line.split('\t');
242
+ pieces.forEach((piece, pieceIndex) => {
243
+ if (pieceIndex > 0)
244
+ runs.push(new TextRun({ children: [new Tab()], font: 'Consolas', size: 18 }));
245
+ if (piece)
246
+ runs.push(new TextRun({ text: piece, font: 'Consolas', size: 18 }));
247
+ });
248
+ });
249
+ return runs.length > 0 ? runs : [new TextRun({ text: '', font: 'Consolas', size: 18 })];
250
+ }
251
+ function narrativeImageRun(image) {
252
+ const dimensions = fitNarrativeImage(image, { maxWidth: IMAGE_WIDTH_PIXELS, maxHeight: IMAGE_HEIGHT_PIXELS });
253
+ return new ImageRun({
254
+ type: image.format === 'jpeg' ? 'jpg' : 'png',
255
+ data: image.dataUri,
256
+ transformation: dimensions,
257
+ altText: { title: image.alt, description: image.alt, name: image.alt }
258
+ });
259
+ }
260
+ function narrativeTableCell(inlines, context, width, index, align, header) {
261
+ const children = inlineChildren(inlines, context, header ? { bold: true } : {});
262
+ return new TableCell({
263
+ children: [new Paragraph({
264
+ children,
265
+ alignment: tableAlignment(align[index])
266
+ })],
267
+ width: { size: width, type: WidthType.DXA },
268
+ verticalAlign: 'center',
269
+ ...(header ? { shading: { fill: 'E7EEE8' } } : {})
270
+ });
271
+ }
272
+ function tableAlignment(align) {
273
+ if (align === 'center')
274
+ return AlignmentType.CENTER;
275
+ if (align === 'right')
276
+ return AlignmentType.RIGHT;
277
+ if (align === 'left')
278
+ return AlignmentType.LEFT;
279
+ return undefined;
280
+ }
281
+ function tableColumnWidths(count) {
282
+ if (count === 0)
283
+ throw new Error('Narrative table must contain at least one column.');
284
+ const width = Math.floor(TABLE_WIDTH_TWIPS / count);
285
+ const remainder = TABLE_WIDTH_TWIPS - width * count;
286
+ return Array.from({ length: count }, (_value, index) => width + (index === 0 ? remainder : 0));
287
+ }
288
+ function headingBookmarks(blocks, usedNames) {
289
+ const bookmarks = new Map();
290
+ const visit = (items) => {
291
+ for (const block of items) {
292
+ if (block.type === 'heading') {
293
+ if (!bookmarks.has(block.id))
294
+ bookmarks.set(block.id, uniqueBookmarkName(block.id, usedNames));
295
+ }
296
+ else if (block.type === 'blockquote') {
297
+ visit(block.blocks);
298
+ }
299
+ else if (block.type === 'list') {
300
+ for (const item of block.items)
301
+ visit(item.blocks);
302
+ }
303
+ }
304
+ };
305
+ visit(blocks);
306
+ return bookmarks;
307
+ }
308
+ function uniqueBookmarkName(id, usedNames) {
309
+ const normalized = `amx_${id.replace(/[^A-Za-z0-9_]/g, '_')}`.slice(0, MAX_BOOKMARK_NAME_LENGTH);
310
+ let suffix = 0;
311
+ let candidate = normalized || 'amx_section';
312
+ while (usedNames.has(candidate)) {
313
+ suffix++;
314
+ const ending = `_${suffix}`;
315
+ candidate = `${normalized.slice(0, MAX_BOOKMARK_NAME_LENGTH - ending.length)}${ending}`;
316
+ }
317
+ usedNames.add(candidate);
318
+ return candidate;
319
+ }
320
+ function localLinkUri(link, context) {
321
+ if (!context)
322
+ throw new Error('DOCX local links require validated source-document and final-destination context.');
323
+ if (link.sourceBase !== 'document-directory')
324
+ throw new Error('DOCX local link has an unsupported source base.');
325
+ const sourceDirectory = realpathSync(dirname(resolve(context.sourceDocumentPath)));
326
+ const outputDirectory = dirname(resolve(context.destinationPath));
327
+ const sourceTarget = resolve(sourceDirectory, ...link.path.split('/'));
328
+ const relativePath = relative(outputDirectory, sourceTarget);
329
+ if (!relativePath || isAbsolute(relativePath))
330
+ throw new Error('DOCX local link target cannot be represented relative to the final DOCX destination.');
331
+ const encodedPath = relativePath.split(sep).map(segment => encodeURIComponent(segment)).join('/');
332
+ return `${encodedPath}${link.query === undefined ? '' : `?${link.query}`}${link.fragment === undefined ? '' : `#${link.fragment}`}`;
333
+ }
334
+ function addEmission(children, emission, identity) {
335
+ if (emission.kind === 'table')
336
+ addTable(children, emission);
337
+ else
338
+ addChart(children, emission, identity);
339
+ }
340
+ function addTable(children, emission) {
341
+ const title = emission.declaration.options.find(option => option.type === 'viewTitleOption');
342
+ const columns = emission.declaration.options.filter(option => option.type === 'tableColumnOption');
343
+ const caption = title?.type === 'viewTitleOption' ? title.value : emission.name;
344
+ children.push(new Paragraph({ text: caption, heading: HeadingLevel.HEADING_2 }));
345
+ const header = new TableRow({ children: columns.map(column => tableCell(column.label, true)) });
346
+ const rows = emission.data.map(value => new TableRow({
347
+ children: columns.map(column => tableCell(isRecord(value) ? valueToString(value[column.field]) : ''))
348
+ }));
349
+ children.push(new Table({ rows: [header, ...rows] }));
350
+ }
351
+ function addChart(children, emission, identity) {
352
+ const model = createChartViewModel(emission, identity);
353
+ children.push(new Paragraph({ text: model.title, heading: HeadingLevel.HEADING_2 }));
354
+ children.push(new Paragraph(model.description));
355
+ if (model.plottedPointCount === 0) {
356
+ addNoChartAlternative(children, model, 'Chart not shown: no plottable data.');
357
+ return;
358
+ }
359
+ if (model.kind === 'scatter') {
360
+ const chartSeries = scatterChartSeries(model);
361
+ if (chartSeries.some(series => series.points.length === 0)) {
362
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent a scatter group with no plottable points.');
363
+ return;
364
+ }
365
+ const run = new ChartRun({
366
+ type: 'scatter',
367
+ title: chartTitle(model, identity.accent),
368
+ altText: chartAltText(model),
369
+ series: chartSeries,
370
+ markers: true,
371
+ lines: 'none',
372
+ legend: chartSeries.length > 1 ? {} : false,
373
+ xAxis: chartValueAxis(model.axes.find(axis => axis.role === 'x')),
374
+ yAxis: chartValueAxis(model.axes.find(axis => axis.role === 'y')),
375
+ transformation: docxChartDimensions(model)
376
+ });
377
+ children.push(new Paragraph({ children: [run] }));
378
+ addChartTable(children, model);
379
+ return;
380
+ }
381
+ if (model.kind === 'line' && numericXAxis(model)) {
382
+ const plotted = numericLineScatterSeries(model);
383
+ if (plotted.series.length === 0) {
384
+ addNoChartAlternative(children, model, 'Chart not shown: no plottable data.');
385
+ return;
386
+ }
387
+ const valueAxes = activeNumericLineAxes(model, plotted.activeAxisIds);
388
+ if (valueAxes.length > 1) {
389
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent all measurement axes without changing their meaning.');
390
+ return;
391
+ }
392
+ const description = [
393
+ ...plotted.omittedSeries.map(name => `Series "${name}" has no plottable coordinates and is listed only in the complete data table.`),
394
+ ...(plotted.hasGaps ? ['Null gaps break the line; continued segments are hidden from the legend.'] : [])
395
+ ];
396
+ const run = new ChartRun({
397
+ type: 'scatter',
398
+ title: chartTitle(model, identity.accent),
399
+ altText: chartAltText(model, description),
400
+ series: plotted.series,
401
+ markers: true,
402
+ lines: 'straight',
403
+ legend: model.series.length > 1
404
+ ? { hiddenEntries: plotted.hiddenLegendEntries }
405
+ : false,
406
+ xAxis: chartValueAxis(model.axes.find(axis => axis.role === 'x')),
407
+ yAxis: chartValueAxis(valueAxes[0]),
408
+ transformation: docxChartDimensions(model)
409
+ });
410
+ children.push(new Paragraph({ children: [run] }));
411
+ if (plotted.omittedSeries.length > 0) {
412
+ children.push(new Paragraph(`Series with no plottable coordinates, shown only in the complete table: ${plotted.omittedSeries.join(', ')}.`));
413
+ }
414
+ addChartTable(children, model);
415
+ return;
416
+ }
417
+ if (model.kind === 'line' && model.dateTimePresentation === 'UTC ISO 8601') {
418
+ const plotted = dateTimeLineSeries(model);
419
+ if (plotted.categories.length === 0 || !plotted.hasPlottablePoints) {
420
+ addNoChartAlternative(children, model, 'Chart not shown: no plottable data.');
421
+ return;
422
+ }
423
+ const valueAxes = model.axes.filter(axis => axis.role === 'y');
424
+ if (valueAxes.length > 2) {
425
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent all measurement axes without changing their meaning.');
426
+ return;
427
+ }
428
+ const run = new ChartRun({
429
+ type: 'line',
430
+ title: chartTitle(model, identity.accent),
431
+ altText: chartAltText(model, plotted.hasGaps ? ['DateTime rows with null x coordinates break the line; continued segments are hidden from the legend.'] : []),
432
+ categories: plotted.categories,
433
+ series: plotted.series,
434
+ markers: true,
435
+ emptyValues: 'gap',
436
+ legend: model.series.length > 1 ? { hiddenEntries: plotted.hiddenLegendEntries } : false,
437
+ valueAxis: chartValueAxis(valueAxes[0]),
438
+ ...(valueAxes.length > 1 ? { secondaryValueAxis: chartValueAxis(valueAxes[1]) } : {}),
439
+ transformation: docxChartDimensions(model)
440
+ });
441
+ children.push(new Paragraph({ children: [run] }));
442
+ addChartTable(children, model);
443
+ return;
444
+ }
445
+ const valueAxisRole = model.kind === 'bar' ? 'x' : 'y';
446
+ const valueAxes = model.axes.filter(axis => axis.role === valueAxisRole);
447
+ if (valueAxes.length > 2) {
448
+ addNoChartAlternative(children, model, 'Chart not shown: Word cannot represent all measurement axes without changing their meaning.');
449
+ return;
450
+ }
451
+ const categories = model.table.rows.map(row => chartCategory(row.values[0], model.dateTimePresentation === 'UTC ISO 8601'));
452
+ const series = model.series.map((item, seriesIndex) => {
453
+ const axisIndex = valueAxes.findIndex(axis => axis.id === item.axisId);
454
+ if (axisIndex < 0)
455
+ throw new Error(`DOCX chart series "${item.name}" has no matching value axis.`);
456
+ return {
457
+ name: item.name,
458
+ color: chartColorForDocx(item.color),
459
+ values: model.table.rows.map(row => chartNumber(row.values[seriesIndex + 1])),
460
+ ...(valueAxes.length > 1 ? { axis: axisIndex === 0 ? 'primary' : 'secondary' } : {}),
461
+ ...(model.kind === 'line' ? { markers: true } : {})
462
+ };
463
+ });
464
+ const run = new ChartRun({
465
+ type: model.kind,
466
+ title: chartTitle(model, identity.accent),
467
+ altText: chartAltText(model),
468
+ categories,
469
+ series,
470
+ legend: model.series.length > 1 ? {} : false,
471
+ ...(model.kind === 'bar' ? { categoryAxis: { reverseOrder: true } } : {}),
472
+ ...(model.kind === 'line' ? { emptyValues: 'gap' } : {}),
473
+ valueAxis: chartValueAxis(valueAxes[0]),
474
+ ...(valueAxes.length > 1 ? { secondaryValueAxis: chartValueAxis(valueAxes[1]) } : {}),
475
+ transformation: docxChartDimensions(model)
476
+ });
477
+ children.push(new Paragraph({ children: [run] }));
478
+ addChartTable(children, model);
479
+ }
480
+ function docxChartDimensions(model) {
481
+ const width = Math.min(model.dimensions.width, DOCX_CHART_WIDTH_PIXELS);
482
+ return {
483
+ width,
484
+ height: Math.round(model.dimensions.height * width / model.dimensions.width)
485
+ };
486
+ }
487
+ function addNoChartAlternative(children, model, notice) {
488
+ children.push(new Paragraph(notice));
489
+ addChartTable(children, model);
490
+ }
491
+ function addChartTable(children, model) {
492
+ const header = new TableRow({
493
+ tableHeader: true,
494
+ cantSplit: true,
495
+ children: model.table.headings.map(heading => tableCell(heading, true))
496
+ });
497
+ const rows = model.table.rows.map(row => new TableRow({
498
+ cantSplit: true,
499
+ children: row.values.map(value => tableCell(valueToString(value)))
500
+ }));
501
+ children.push(new Paragraph({ text: model.table.caption, heading: HeadingLevel.HEADING_3 }));
502
+ const columnCount = Math.max(1, model.table.headings.length);
503
+ const baseColumnWidth = Math.floor(TABLE_WIDTH_TWIPS / columnCount);
504
+ children.push(new Table({
505
+ rows: [header, ...rows],
506
+ width: { size: 200, type: WidthType.PERCENTAGE },
507
+ columnWidths: model.table.headings.map((_heading, index) => index === columnCount - 1 ? TABLE_WIDTH_TWIPS - baseColumnWidth * (columnCount - 1) : baseColumnWidth),
508
+ layout: TableLayoutType.FIXED,
509
+ margins: { top: 80, bottom: 80, left: 100, right: 100 }
510
+ }));
511
+ }
512
+ function chartAltText(model, details = []) {
513
+ return {
514
+ name: model.accessibility.tableId,
515
+ title: model.accessibility.title,
516
+ description: [model.accessibility.description, model.accessibility.summary, ...details].join(' ')
517
+ };
518
+ }
519
+ function chartTitle(model, accent) {
520
+ return { text: model.title, font: { color: chartColorForDocx(accent) } };
521
+ }
522
+ function chartValueAxis(axis) {
523
+ return axis?.name ? { title: axis.name } : undefined;
524
+ }
525
+ function chartCategory(value, dateTime) {
526
+ if (dateTime) {
527
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
528
+ throw new Error('DOCX DateTime chart categories must contain valid date-time values.');
529
+ }
530
+ return new Date(value);
531
+ }
532
+ if (value === null || value === undefined)
533
+ return '';
534
+ if (typeof value === 'string' || typeof value === 'number')
535
+ return value;
536
+ throw new Error('DOCX chart categories must be strings, numbers, or DateTime values.');
537
+ }
538
+ function chartNumber(value) {
539
+ if (value === null || value === undefined)
540
+ return null;
541
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
542
+ throw new Error('DOCX chart values must be finite numbers or null.');
543
+ }
544
+ return value;
545
+ }
546
+ function chartColorForDocx(color) {
547
+ return color.replace(/^#/, '');
548
+ }
549
+ function numericXAxis(model) {
550
+ const axis = Array.isArray(model.option.xAxis) ? model.option.xAxis[0] : model.option.xAxis;
551
+ return axis?.type === 'value';
552
+ }
553
+ function scatterChartSeries(model) {
554
+ const grouped = model.table.headings.length > 2;
555
+ const indices = new Map();
556
+ const points = model.series.map(() => []);
557
+ for (const row of model.table.rows) {
558
+ const groupValue = grouped ? row.values[2] ?? null : null;
559
+ const key = groupValue === null ? '__ungrouped__' : `${typeof groupValue}:${String(groupValue)}`;
560
+ let index = indices.get(key);
561
+ if (index === undefined) {
562
+ index = indices.size;
563
+ if (index >= points.length)
564
+ throw new Error('DOCX scatter table groups do not match the chart model series.');
565
+ indices.set(key, index);
566
+ }
567
+ const x = row.values[0];
568
+ const y = row.values[1];
569
+ if (x === null || y === null)
570
+ continue;
571
+ if (typeof x !== 'number' || !Number.isFinite(x) || typeof y !== 'number' || !Number.isFinite(y)) {
572
+ throw new Error('DOCX scatter coordinates must be finite numbers or null.');
573
+ }
574
+ points[index].push({ x, y });
575
+ }
576
+ return model.series.map((series, index) => ({
577
+ name: series.name,
578
+ color: chartColorForDocx(series.color),
579
+ points: points[index]
580
+ }));
581
+ }
582
+ function numericLineScatterSeries(model) {
583
+ const series = [];
584
+ const omittedSeries = [];
585
+ const hiddenLegendEntries = [];
586
+ const activeAxisIds = new Set();
587
+ const occupiedNames = new Set(model.series.map(item => item.name));
588
+ let hasGaps = false;
589
+ for (let seriesIndex = 0; seriesIndex < model.series.length; seriesIndex++) {
590
+ const item = model.series[seriesIndex];
591
+ const segments = [];
592
+ let current = [];
593
+ const finishSegment = () => {
594
+ if (current.length > 0)
595
+ segments.push(current);
596
+ current = [];
597
+ };
598
+ for (const row of model.table.rows) {
599
+ const x = row.values[0];
600
+ const y = row.values[seriesIndex + 1];
601
+ if (x === null || y === null) {
602
+ if (current.length > 0)
603
+ hasGaps = true;
604
+ finishSegment();
605
+ continue;
606
+ }
607
+ if (typeof x !== 'number' || !Number.isFinite(x) || typeof y !== 'number' || !Number.isFinite(y)) {
608
+ throw new Error('Numeric-X line chart coordinates must be finite numbers or null.');
609
+ }
610
+ current.push({ x, y });
611
+ }
612
+ finishSegment();
613
+ if (segments.length === 0) {
614
+ omittedSeries.push(item.name);
615
+ continue;
616
+ }
617
+ if (item.axisId)
618
+ activeAxisIds.add(item.axisId);
619
+ segments.forEach((segment, segmentIndex) => {
620
+ let name = item.name;
621
+ if (segmentIndex > 0) {
622
+ let suffix = segmentIndex + 1;
623
+ name = `${item.name} (OpenAMX segment ${suffix})`;
624
+ while (occupiedNames.has(name))
625
+ name = `${item.name} (OpenAMX segment ${++suffix})`;
626
+ occupiedNames.add(name);
627
+ hiddenLegendEntries.push(name);
628
+ }
629
+ series.push({
630
+ name,
631
+ color: chartColorForDocx(item.color),
632
+ points: segment
633
+ });
634
+ });
635
+ }
636
+ return { series, omittedSeries, hiddenLegendEntries, activeAxisIds: [...activeAxisIds], hasGaps };
637
+ }
638
+ function dateTimeLineSeries(model) {
639
+ const categories = [];
640
+ const rowCategoryIndices = [];
641
+ for (const row of model.table.rows) {
642
+ const value = row.values[0];
643
+ if (value === null) {
644
+ rowCategoryIndices.push(undefined);
645
+ continue;
646
+ }
647
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
648
+ throw new Error('DOCX DateTime chart categories must contain valid date-time values or null.');
649
+ }
650
+ rowCategoryIndices.push(categories.length);
651
+ categories.push(new Date(value));
652
+ }
653
+ const series = [];
654
+ const hiddenLegendEntries = [];
655
+ const occupiedNames = new Set(model.series.map(item => item.name));
656
+ let hasPlottablePoints = false;
657
+ let hasGaps = false;
658
+ for (let seriesIndex = 0; seriesIndex < model.series.length; seriesIndex++) {
659
+ const item = model.series[seriesIndex];
660
+ const segments = [];
661
+ let current = Array(categories.length).fill(null);
662
+ let hasCategory = false;
663
+ const finishSegment = () => {
664
+ if (hasCategory)
665
+ segments.push(current);
666
+ current = Array(categories.length).fill(null);
667
+ hasCategory = false;
668
+ };
669
+ for (let rowIndex = 0; rowIndex < model.table.rows.length; rowIndex++) {
670
+ const categoryIndex = rowCategoryIndices[rowIndex];
671
+ if (categoryIndex === undefined) {
672
+ if (hasCategory)
673
+ hasGaps = true;
674
+ finishSegment();
675
+ continue;
676
+ }
677
+ hasCategory = true;
678
+ const value = chartNumber(model.table.rows[rowIndex].values[seriesIndex + 1]);
679
+ current[categoryIndex] = value;
680
+ if (value !== null)
681
+ hasPlottablePoints = true;
682
+ }
683
+ finishSegment();
684
+ if (segments.length === 0 && categories.length > 0) {
685
+ segments.push(Array(categories.length).fill(null));
686
+ }
687
+ segments.forEach((values, segmentIndex) => {
688
+ let name = item.name;
689
+ if (segmentIndex > 0) {
690
+ let suffix = segmentIndex + 1;
691
+ name = `${item.name} (OpenAMX segment ${suffix})`;
692
+ while (occupiedNames.has(name))
693
+ name = `${item.name} (OpenAMX segment ${++suffix})`;
694
+ occupiedNames.add(name);
695
+ hiddenLegendEntries.push(name);
696
+ }
697
+ series.push({
698
+ name,
699
+ color: chartColorForDocx(item.color),
700
+ values
701
+ });
702
+ });
703
+ }
704
+ return { categories, series, hiddenLegendEntries, hasPlottablePoints, hasGaps };
705
+ }
706
+ function activeNumericLineAxes(model, activeAxisIds) {
707
+ const activeIds = new Set(activeAxisIds);
708
+ return model.axes.filter(axis => axis.role === 'y' && activeIds.has(axis.id));
709
+ }
710
+ function tableCell(value, bold = false) {
711
+ return new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: value, bold })] })] });
712
+ }
713
+ function headingLevel(level) {
714
+ return [HeadingLevel.HEADING_1, HeadingLevel.HEADING_2, HeadingLevel.HEADING_3, HeadingLevel.HEADING_4, HeadingLevel.HEADING_5, HeadingLevel.HEADING_6][level - 1];
715
+ }
716
+ function isRecord(value) {
717
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
718
+ }
719
+ function valueToString(value) {
720
+ if (value === null || value === undefined)
721
+ return '(null)';
722
+ if (Array.isArray(value))
723
+ return value.map(valueToString).join(', ');
724
+ return String(value);
725
+ }