@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.
- package/COMMERCIAL-LICENSE.md +73 -73
- package/LICENSE.md +659 -659
- package/README.md +538 -513
- package/dist/cli.js +14 -3
- package/dist/editor/completion.js +96 -5
- package/dist/editor/highlighting.js +36 -3
- package/dist/editor/moduleAnalysis.js +8 -2
- package/dist/editor/refactoring.js +1 -1
- package/dist/editor/sourceRanges.js +1 -0
- package/dist/editor/symbols.js +109 -3
- package/dist/parser/parseExpression.js +14 -0
- package/dist/parser/parseIf.js +180 -0
- package/dist/parser/parseStatements.js +85 -7
- package/dist/renderer/narrativeModel.js +561 -0
- package/dist/renderer/renderHtml.js +199 -61
- package/dist/renderer/reportDocx.js +653 -91
- package/dist/renderer/reportPaths.js +31 -0
- package/dist/renderer/reportPdf.js +137 -25
- package/dist/renderer/reportPreparation.js +25 -37
- package/dist/runtime/environment.js +2 -0
- package/dist/runtime/evaluateExpression.js +116 -8
- package/dist/runtime/inputData.js +20 -18
- package/dist/runtime/moduleLoader.js +16 -2
- package/dist/runtime/outputData.js +18 -12
- package/dist/typechecker/checkDocument.js +254 -13
- package/package.json +1 -1
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { AmxError } from '../diagnostics/errors';
|
|
4
|
+
export function canonicalDirectory(path, message = 'Project root must be an existing directory') {
|
|
5
|
+
try {
|
|
6
|
+
const canonical = realpathSync(path);
|
|
7
|
+
if (!statSync(canonical).isDirectory()) {
|
|
8
|
+
throw new AmxError({ code: 'AMX6001', message, file: path });
|
|
9
|
+
}
|
|
10
|
+
return canonical;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error instanceof AmxError)
|
|
14
|
+
throw error;
|
|
15
|
+
throw new AmxError({ code: 'AMX6001', message, file: path });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function isContained(root, candidate) {
|
|
19
|
+
const relation = relative(root, candidate);
|
|
20
|
+
return relation !== '..' && !relation.startsWith(`..${sep}`) && relation !== '';
|
|
21
|
+
}
|
|
22
|
+
export function hasSymlink(root, candidate) {
|
|
23
|
+
const relation = relative(root, candidate);
|
|
24
|
+
let current = root;
|
|
25
|
+
for (const segment of relation.split(sep)) {
|
|
26
|
+
current = resolve(current, segment);
|
|
27
|
+
if (existsSync(current) && lstatSync(current).isSymbolicLink())
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import * as echarts from 'echarts';
|
|
2
2
|
import pdfmake from 'pdfmake';
|
|
3
|
-
import { existsSync } from 'node:fs';
|
|
3
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
|
-
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { createChartViewModel } from './chartModel';
|
|
8
|
+
import { fitNarrativeImage } from './narrativeModel';
|
|
8
9
|
const packagedFontRoot = fileURLToPath(new URL('./pdfmake-fonts/', import.meta.url));
|
|
9
10
|
const fontRoot = existsSync(resolve(packagedFontRoot, 'Roboto-Regular.ttf'))
|
|
10
11
|
? packagedFontRoot
|
|
@@ -19,15 +20,17 @@ pdfmake.setFonts({
|
|
|
19
20
|
bolditalics: resolve(fontRoot, 'Roboto-MediumItalic.ttf')
|
|
20
21
|
}
|
|
21
22
|
});
|
|
22
|
-
export function preparePdfReport(report,
|
|
23
|
-
|
|
23
|
+
export function preparePdfReport(report, renderChartOrContext = renderStaticChart, context) {
|
|
24
|
+
const renderChart = typeof renderChartOrContext === 'function' ? renderChartOrContext : renderStaticChart;
|
|
25
|
+
const exportContext = typeof renderChartOrContext === 'function' ? context : renderChartOrContext;
|
|
26
|
+
return preparePreparedPdfReport(report, renderChart, exportContext);
|
|
24
27
|
}
|
|
25
28
|
export async function serializePdfReport(report) {
|
|
26
29
|
const pdf = pdfmake.createPdf(report.definition);
|
|
27
30
|
const buffer = await pdf.getBuffer();
|
|
28
31
|
return Uint8Array.from(buffer);
|
|
29
32
|
}
|
|
30
|
-
function preparePreparedPdfReport(report, renderChart) {
|
|
33
|
+
function preparePreparedPdfReport(report, renderChart, context) {
|
|
31
34
|
const content = [];
|
|
32
35
|
const identity = report.identity;
|
|
33
36
|
const metadata = [
|
|
@@ -48,7 +51,7 @@ function preparePreparedPdfReport(report, renderChart) {
|
|
|
48
51
|
}
|
|
49
52
|
for (const item of report.items) {
|
|
50
53
|
if (item.type === 'narrative')
|
|
51
|
-
|
|
54
|
+
addNarrativeBlocks(content, item.markdown, context);
|
|
52
55
|
else if (item.type === 'source')
|
|
53
56
|
content.push({ text: item.text, style: 'source' });
|
|
54
57
|
else
|
|
@@ -66,37 +69,146 @@ function preparePreparedPdfReport(report, renderChart) {
|
|
|
66
69
|
heading: { fontSize: 14, bold: true, color: identity.accent, margin: [0, 14, 0, 6] },
|
|
67
70
|
source: { font: 'Roboto', fontSize: 8, color: '#405459', margin: [0, 5, 0, 10] },
|
|
68
71
|
caption: { fontSize: 8, color: '#405459', margin: [0, 3, 0, 6] },
|
|
72
|
+
code: { font: 'Roboto', fontSize: 8, background: '#f1f4f5', margin: [0, 3, 0, 8] },
|
|
73
|
+
blockquote: { color: '#405459', margin: [12, 2, 0, 8] },
|
|
69
74
|
metadata: { fontSize: 9, color: '#18282D', margin: [0, 0, 0, 2] }
|
|
70
75
|
},
|
|
71
76
|
content
|
|
72
77
|
}
|
|
73
78
|
};
|
|
74
79
|
}
|
|
75
|
-
function
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
content.push({ text:
|
|
80
|
+
function addNarrativeBlocks(content, blocks, context) {
|
|
81
|
+
for (const block of blocks) {
|
|
82
|
+
if (block.type === 'heading') {
|
|
83
|
+
content.push({
|
|
84
|
+
text: inlineRuns(block.children, context),
|
|
85
|
+
style: block.depth === 1 ? 'title' : 'heading',
|
|
86
|
+
...(block.depth > 1 ? { fontSize: Math.max(9, 16 - block.depth) } : {}),
|
|
87
|
+
id: block.id
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
else if (block.type === 'paragraph') {
|
|
91
|
+
content.push({ text: inlineRuns(block.children, context), margin: [0, 0, 0, 7] });
|
|
92
|
+
}
|
|
93
|
+
else if (block.type === 'code') {
|
|
94
|
+
content.push({ text: block.text, style: 'code', preserveLeadingSpaces: true });
|
|
95
|
+
}
|
|
96
|
+
else if (block.type === 'list') {
|
|
97
|
+
const items = block.items.map(item => {
|
|
98
|
+
const children = [];
|
|
99
|
+
addNarrativeBlocks(children, item.blocks, context);
|
|
100
|
+
if (item.checked !== undefined && children.length > 0) {
|
|
101
|
+
const first = children[0];
|
|
102
|
+
if (isPlainRecord(first) && Array.isArray(first.text)) {
|
|
103
|
+
first.text = [{ text: item.checked ? '[x] ' : '[ ] ' }, ...first.text];
|
|
104
|
+
}
|
|
105
|
+
else if (isPlainRecord(first) && typeof first.text === 'string') {
|
|
106
|
+
first.text = `${item.checked ? '[x] ' : '[ ] '}${first.text}`;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return children.length === 1 ? children[0] : children;
|
|
110
|
+
});
|
|
111
|
+
content.push(block.ordered
|
|
112
|
+
? { ol: items, ...(block.start === undefined ? {} : { start: block.start }), margin: [0, 0, 0, 7] }
|
|
113
|
+
: { ul: items, margin: [0, 0, 0, 7] });
|
|
114
|
+
}
|
|
115
|
+
else if (block.type === 'blockquote') {
|
|
116
|
+
const quoted = [];
|
|
117
|
+
addNarrativeBlocks(quoted, block.blocks, context);
|
|
118
|
+
content.push({ stack: quoted, style: 'blockquote' });
|
|
87
119
|
}
|
|
88
|
-
else if (
|
|
89
|
-
|
|
90
|
-
|
|
120
|
+
else if (block.type === 'table') {
|
|
121
|
+
const cell = (children, header, alignment) => ({
|
|
122
|
+
text: inlineRuns(children, context),
|
|
123
|
+
...(header ? { bold: true, fillColor: '#e7eee8' } : {}),
|
|
124
|
+
...(alignment ? { alignment } : {})
|
|
125
|
+
});
|
|
126
|
+
content.push({
|
|
127
|
+
table: {
|
|
128
|
+
headerRows: 1,
|
|
129
|
+
keepWithHeaderRows: 1,
|
|
130
|
+
widths: block.header.map(() => '*'),
|
|
131
|
+
body: [
|
|
132
|
+
block.header.map((children, index) => cell(children, true, block.align[index])),
|
|
133
|
+
...block.rows.map(row => row.map((children, index) => cell(children, false, block.align[index])))
|
|
134
|
+
]
|
|
135
|
+
},
|
|
136
|
+
layout: 'lightHorizontalLines',
|
|
137
|
+
fontSize: 8
|
|
138
|
+
});
|
|
91
139
|
}
|
|
92
|
-
else if (
|
|
93
|
-
|
|
140
|
+
else if (block.type === 'horizontalRule') {
|
|
141
|
+
content.push({
|
|
142
|
+
canvas: [{ type: 'line', x1: 0, y1: 2, x2: 493, y2: 2, lineWidth: 0.5, lineColor: '#9AA8AC' }],
|
|
143
|
+
margin: [0, 6, 0, 6]
|
|
144
|
+
});
|
|
94
145
|
}
|
|
95
146
|
else {
|
|
96
|
-
|
|
147
|
+
content.push({ text: '', pageBreak: 'before' });
|
|
97
148
|
}
|
|
98
149
|
}
|
|
99
|
-
|
|
150
|
+
}
|
|
151
|
+
function inlineRuns(inlines, context, style = {}) {
|
|
152
|
+
const runs = [];
|
|
153
|
+
for (const inline of inlines) {
|
|
154
|
+
if (inline.type === 'text') {
|
|
155
|
+
runs.push({ text: inline.text, ...style });
|
|
156
|
+
}
|
|
157
|
+
else if (inline.type === 'lineBreak') {
|
|
158
|
+
runs.push({ text: '\n', ...style });
|
|
159
|
+
}
|
|
160
|
+
else if (inline.type === 'inlineCode') {
|
|
161
|
+
runs.push({ text: inline.text, font: 'Roboto', background: '#f1f4f5', ...style });
|
|
162
|
+
}
|
|
163
|
+
else if (inline.type === 'strong' || inline.type === 'emphasis' || inline.type === 'delete') {
|
|
164
|
+
const nestedStyle = inline.type === 'strong'
|
|
165
|
+
? { ...style, bold: true }
|
|
166
|
+
: inline.type === 'emphasis'
|
|
167
|
+
? { ...style, italics: true }
|
|
168
|
+
: { ...style, decoration: 'lineThrough' };
|
|
169
|
+
runs.push(...inlineRuns(inline.children, context, nestedStyle));
|
|
170
|
+
}
|
|
171
|
+
else if (inline.type === 'link') {
|
|
172
|
+
const linkStyle = {
|
|
173
|
+
...style,
|
|
174
|
+
...(inline.link.type === 'external' ? { link: inline.link.href } : {}),
|
|
175
|
+
...(inline.link.type === 'internal' ? { linkToDestination: inline.link.targetId } : {}),
|
|
176
|
+
...(inline.link.type === 'local' ? { link: localLinkUri(inline.link, context) } : {})
|
|
177
|
+
};
|
|
178
|
+
runs.push(...inlineRuns(inline.children, context, linkStyle));
|
|
179
|
+
}
|
|
180
|
+
else if (inline.type === 'image') {
|
|
181
|
+
runs.push(imageRun(inline.image, style));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return runs;
|
|
185
|
+
}
|
|
186
|
+
function imageRun(image, style) {
|
|
187
|
+
const dimensions = fitNarrativeImage(image, { maxWidth: 493, maxHeight: 739 });
|
|
188
|
+
return {
|
|
189
|
+
image: image.dataUri,
|
|
190
|
+
width: dimensions.width,
|
|
191
|
+
height: dimensions.height,
|
|
192
|
+
alt: image.alt,
|
|
193
|
+
...style
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function localLinkUri(link, context) {
|
|
197
|
+
if (!context)
|
|
198
|
+
throw new Error('PDF local links require validated source-document and final-destination context.');
|
|
199
|
+
if (link.sourceBase !== 'document-directory')
|
|
200
|
+
throw new Error('PDF local link has an unsupported source base.');
|
|
201
|
+
const sourceDirectory = realpathSync(dirname(resolve(context.sourceDocumentPath)));
|
|
202
|
+
const outputDirectory = dirname(resolve(context.destinationPath));
|
|
203
|
+
const sourceTarget = resolve(sourceDirectory, ...link.path.split('/'));
|
|
204
|
+
const relativePath = relative(outputDirectory, sourceTarget);
|
|
205
|
+
if (!relativePath || isAbsolute(relativePath))
|
|
206
|
+
throw new Error('PDF local link target cannot be represented relative to the final PDF destination.');
|
|
207
|
+
const encodedPath = relativePath.split(sep).map(segment => encodeURIComponent(segment)).join('/');
|
|
208
|
+
return `${encodedPath}${link.query === undefined ? '' : `?${link.query}`}${link.fragment === undefined ? '' : `#${link.fragment}`}`;
|
|
209
|
+
}
|
|
210
|
+
function isPlainRecord(value) {
|
|
211
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
100
212
|
}
|
|
101
213
|
function addEmission(content, emission, identity, renderChart) {
|
|
102
214
|
if (emission.kind === 'table')
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { existsSync, lstatSync, readFileSync
|
|
2
|
-
import {
|
|
1
|
+
import { existsSync, lstatSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
3
|
import sharp from 'sharp';
|
|
4
4
|
import { AmxError } from '../diagnostics/errors';
|
|
5
5
|
import { formatAmx } from '../formatter/formatAmx';
|
|
6
6
|
import { parseExpression } from '../parser/parseExpression';
|
|
7
7
|
import { evaluateExpression } from '../runtime/evaluateExpression';
|
|
8
8
|
import { isMeasurement } from '../runtime/measurement';
|
|
9
|
+
import { prepareNarratives } from './narrativeModel';
|
|
10
|
+
import { canonicalDirectory, hasSymlink, isContained } from './reportPaths';
|
|
9
11
|
const REPORT_FIELDS = new Set(['organization', 'logo', 'logoAlt', 'accent', 'author', 'status', 'classification', 'footer', 'sourceVisible']);
|
|
10
12
|
const TEXT_LIMITS = { organization: 120, logoAlt: 120, author: 120, status: 80, classification: 80, footer: 300 };
|
|
11
13
|
export async function prepareReport(doc, env, options = {}) {
|
|
@@ -14,6 +16,17 @@ export async function prepareReport(doc, env, options = {}) {
|
|
|
14
16
|
validateReport(projectReport, '.openamx/project.json', options.projectRoot);
|
|
15
17
|
validateReport(frontMatter, 'frontmatter', options.file);
|
|
16
18
|
const identity = await resolveIdentity(projectReport, frontMatter, options);
|
|
19
|
+
const narrativeSources = doc.nodes.flatMap(node => node.type === 'narrative'
|
|
20
|
+
? [{ content: node.content, line: node.source?.line }]
|
|
21
|
+
: []);
|
|
22
|
+
const narratives = await prepareNarratives(narrativeSources, {
|
|
23
|
+
file: options.file,
|
|
24
|
+
projectRoot: options.projectRoot,
|
|
25
|
+
interpolate: (expression, line) => {
|
|
26
|
+
const value = evaluateExpression(parseExpression(expression, line === undefined ? undefined : { line, column: 1 }), env, options.file);
|
|
27
|
+
return valueToString(value);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
17
30
|
const emissionsByNode = new Map();
|
|
18
31
|
for (const emission of env.viewEmissions) {
|
|
19
32
|
const emissions = emissionsByNode.get(emission.documentNodeIndex) ?? [];
|
|
@@ -21,9 +34,18 @@ export async function prepareReport(doc, env, options = {}) {
|
|
|
21
34
|
emissionsByNode.set(emission.documentNodeIndex, emissions);
|
|
22
35
|
}
|
|
23
36
|
const items = [];
|
|
37
|
+
let narrativeIndex = 0;
|
|
24
38
|
for (const [index, node] of doc.nodes.entries()) {
|
|
25
39
|
if (node.type === 'narrative') {
|
|
26
|
-
|
|
40
|
+
const narrative = narratives[narrativeIndex++];
|
|
41
|
+
if (!narrative)
|
|
42
|
+
throw new Error('Prepared narrative order does not match the source document');
|
|
43
|
+
items.push(Object.freeze({
|
|
44
|
+
type: 'narrative',
|
|
45
|
+
text: narrative.text,
|
|
46
|
+
markdown: narrative.blocks,
|
|
47
|
+
diagnostics: narrative.diagnostics
|
|
48
|
+
}));
|
|
27
49
|
continue;
|
|
28
50
|
}
|
|
29
51
|
if (node.type !== 'executableCodeBlock')
|
|
@@ -141,13 +163,6 @@ async function prepareLogo(path, alt, projectRoot, file) {
|
|
|
141
163
|
fail('AMX6001', 'Report logo is not a supported image', file);
|
|
142
164
|
}
|
|
143
165
|
}
|
|
144
|
-
function substituteInlines(content, env, file, line) {
|
|
145
|
-
return content.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_full, expression) => {
|
|
146
|
-
if (!expression.trim())
|
|
147
|
-
return '';
|
|
148
|
-
return valueToString(evaluateExpression(parseExpression(expression.trim(), line === undefined ? undefined : { line, column: 1 }), env, file));
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
166
|
function valueToString(value) {
|
|
152
167
|
if (value === null || value === undefined)
|
|
153
168
|
return '';
|
|
@@ -176,33 +191,6 @@ export function effectiveReportAccent(accent) {
|
|
|
176
191
|
.reduce((total, value, index) => total + value * [0.2126, 0.7152, 0.0722][index], 0);
|
|
177
192
|
return (1.05 / (luminance + 0.05)) >= 4.5 ? accent : '#146C94';
|
|
178
193
|
}
|
|
179
|
-
function canonicalDirectory(path) {
|
|
180
|
-
try {
|
|
181
|
-
const canonical = realpathSync(path);
|
|
182
|
-
if (!statSync(canonical).isDirectory())
|
|
183
|
-
fail('AMX6001', 'Project root must be an existing directory', path);
|
|
184
|
-
return canonical;
|
|
185
|
-
}
|
|
186
|
-
catch (error) {
|
|
187
|
-
if (error instanceof AmxError)
|
|
188
|
-
throw error;
|
|
189
|
-
fail('AMX6001', 'Project root must be an existing directory', path);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
function isContained(root, candidate) {
|
|
193
|
-
const relation = relative(root, candidate);
|
|
194
|
-
return relation !== '..' && !relation.startsWith(`..${sep}`) && relation !== '';
|
|
195
|
-
}
|
|
196
|
-
function hasSymlink(root, candidate) {
|
|
197
|
-
const relation = relative(root, candidate);
|
|
198
|
-
let current = root;
|
|
199
|
-
for (const segment of relation.split(sep)) {
|
|
200
|
-
current = resolve(current, segment);
|
|
201
|
-
if (existsSync(current) && lstatSync(current).isSymbolicLink())
|
|
202
|
-
return true;
|
|
203
|
-
}
|
|
204
|
-
return false;
|
|
205
|
-
}
|
|
206
194
|
function fail(code, message, file) {
|
|
207
195
|
throw new AmxError({ code, message, file });
|
|
208
196
|
}
|
|
@@ -79,13 +79,13 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
|
79
79
|
}
|
|
80
80
|
const record = actual;
|
|
81
81
|
const fieldNames = new Set(declaration.fields.map(field => field.name));
|
|
82
|
-
const recordRegistry = fieldRegistry(declaration, env.dimensionRegistry);
|
|
83
82
|
for (const field of declaration.fields) {
|
|
83
|
+
const fieldScope = fieldRegistry(field, env.dimensionRegistry);
|
|
84
84
|
if (!Object.prototype.hasOwnProperty.call(record, field.name)) {
|
|
85
|
-
report(`Missing computed field '${field.name}'`, checkedType(field.annotation,
|
|
85
|
+
report(`Missing computed field '${field.name}'`, checkedType(field.annotation, fieldScope), 'missing', `${dataPath}.${field.name}`, field.source);
|
|
86
86
|
}
|
|
87
87
|
else {
|
|
88
|
-
visit(record[field.name], checkedType(field.annotation,
|
|
88
|
+
visit(record[field.name], checkedType(field.annotation, fieldScope), `${dataPath}.${field.name}`, field.source);
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
for (const name of Object.keys(record).filter(name => !fieldNames.has(name)).sort()) {
|
|
@@ -96,6 +96,18 @@ function validateRuntimeValue(value, expected, env, source, file, valuePath) {
|
|
|
96
96
|
if (diagnostics.length)
|
|
97
97
|
throwInputErrors(diagnostics);
|
|
98
98
|
}
|
|
99
|
+
function evaluateFieldDefault(field, env, file) {
|
|
100
|
+
if (!field.defaultExpression)
|
|
101
|
+
return null;
|
|
102
|
+
const currentRegistry = env.dimensionRegistry;
|
|
103
|
+
env.dimensionRegistry = fieldRegistry(field, currentRegistry);
|
|
104
|
+
try {
|
|
105
|
+
return evaluateExpression(field.defaultExpression, env, file);
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
env.dimensionRegistry = currentRegistry;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
99
111
|
function checkedType(reference, scope) {
|
|
100
112
|
const registry = scope instanceof Environment ? scope.dimensionRegistry : scope;
|
|
101
113
|
if (reference.type === 'namedType') {
|
|
@@ -154,13 +166,19 @@ export function evaluateExpression(node, env, file) {
|
|
|
154
166
|
const record = {};
|
|
155
167
|
for (const field of declaration.fields) {
|
|
156
168
|
record[field.name] = supplied.has(field.name) ? supplied.get(field.name)
|
|
157
|
-
: field.defaultExpression ?
|
|
169
|
+
: field.defaultExpression ? evaluateFieldDefault(field, env, file) : null;
|
|
158
170
|
}
|
|
159
171
|
validateRuntimeValue(record, { kind: 'named', name: node.name }, env, node.source, file, `record ${node.name}`);
|
|
160
172
|
return record;
|
|
161
173
|
}
|
|
162
|
-
case 'fieldAccess':
|
|
174
|
+
case 'fieldAccess': {
|
|
175
|
+
if (node.receiver.type === 'identifier') {
|
|
176
|
+
const enumeration = env.enumValues.get(node.receiver.name);
|
|
177
|
+
if (enumeration)
|
|
178
|
+
return enumeration[node.field];
|
|
179
|
+
}
|
|
163
180
|
return evaluateExpression(node.receiver, env, file)[node.field];
|
|
181
|
+
}
|
|
164
182
|
case 'listAccess':
|
|
165
183
|
return evalListAccess(node, env, file);
|
|
166
184
|
case 'numberLiteral':
|
|
@@ -219,6 +237,8 @@ export function evaluateExpression(node, env, file) {
|
|
|
219
237
|
return evalUnary(node, env, file);
|
|
220
238
|
case 'conditionalExpression':
|
|
221
239
|
return evalConditional(node, env, file);
|
|
240
|
+
case 'bracedIfExpression':
|
|
241
|
+
return evalBracedIfExpression(node, env, file);
|
|
222
242
|
case 'listLiteral':
|
|
223
243
|
return evalListLiteral(node, env, file);
|
|
224
244
|
case 'functionCall':
|
|
@@ -385,6 +405,58 @@ function evalConditional(node, env, file) {
|
|
|
385
405
|
? evaluateExpression(node.consequent, env, file)
|
|
386
406
|
: evaluateExpression(node.alternate, env, file);
|
|
387
407
|
}
|
|
408
|
+
class ConditionalValueReturn {
|
|
409
|
+
value;
|
|
410
|
+
constructor(value) {
|
|
411
|
+
this.value = value;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
class ForExpressionReturn {
|
|
415
|
+
value;
|
|
416
|
+
constructor(value) {
|
|
417
|
+
this.value = value;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const conditionalReturnDepth = new WeakMap();
|
|
421
|
+
const forExpressionDepth = new WeakMap();
|
|
422
|
+
function withDepth(depths, env, run) {
|
|
423
|
+
depths.set(env, (depths.get(env) ?? 0) + 1);
|
|
424
|
+
try {
|
|
425
|
+
return run();
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
const depth = depths.get(env) - 1;
|
|
429
|
+
if (depth)
|
|
430
|
+
depths.set(env, depth);
|
|
431
|
+
else
|
|
432
|
+
depths.delete(env);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function evaluateScopedStatements(statements, env, file) {
|
|
436
|
+
const existing = new Set(Object.keys(env.toObject()));
|
|
437
|
+
try {
|
|
438
|
+
evaluateStatements(statements, env, file);
|
|
439
|
+
}
|
|
440
|
+
finally {
|
|
441
|
+
for (const name of Object.keys(env.toObject())) {
|
|
442
|
+
if (!existing.has(name))
|
|
443
|
+
env.delete(name);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
function evalBracedIfExpression(node, env, file) {
|
|
448
|
+
const branch = toBoolean(evaluateExpression(node.test, env, file)) ? node.consequent : node.alternate;
|
|
449
|
+
const closingSource = branch === node.consequent ? node.consequentSource : node.alternateSource;
|
|
450
|
+
try {
|
|
451
|
+
withDepth(conditionalReturnDepth, env, () => evaluateScopedStatements(branch, env, file));
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
if (error instanceof ConditionalValueReturn)
|
|
455
|
+
return error.value;
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
458
|
+
return staticError('AMX3021', 'Every possible path in an if expression must return a value', closingSource ?? node.source, file);
|
|
459
|
+
}
|
|
388
460
|
function evalListLiteral(node, env, file) {
|
|
389
461
|
return node.elements.map(el => evaluateExpression(el, env, file));
|
|
390
462
|
}
|
|
@@ -732,6 +804,20 @@ function evaluateStatement(statement, env, file) {
|
|
|
732
804
|
case 'typeDeclaration':
|
|
733
805
|
env.recordTypes.set(statement.name, statement);
|
|
734
806
|
return;
|
|
807
|
+
case 'enumDeclaration': {
|
|
808
|
+
const values = statement.resolvedValues ?? statement.members.map((member, index) => {
|
|
809
|
+
if (!member.value)
|
|
810
|
+
return index + 1;
|
|
811
|
+
if (member.value.type === 'numberLiteral' || member.value.type === 'stringLiteral')
|
|
812
|
+
return member.value.value;
|
|
813
|
+
return staticError('AMX3020', 'Only constant values can be assigned to enum members', member.valueSource ?? member.value.source, file);
|
|
814
|
+
});
|
|
815
|
+
const enumeration = {};
|
|
816
|
+
statement.members.forEach((member, index) => { enumeration[member.name] = values[index]; });
|
|
817
|
+
env.enumDeclarations.set(statement.name, statement);
|
|
818
|
+
env.enumValues.set(statement.name, enumeration);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
735
821
|
case 'functionDeclaration':
|
|
736
822
|
env.functions.set(statement.name, statement);
|
|
737
823
|
return;
|
|
@@ -775,10 +861,24 @@ function evaluateStatement(statement, env, file) {
|
|
|
775
861
|
case 'forStatement':
|
|
776
862
|
evalForStatement(statement, env, file);
|
|
777
863
|
return;
|
|
864
|
+
case 'bracedIfStatement':
|
|
865
|
+
evalBracedIfStatement(statement, env, file);
|
|
866
|
+
return;
|
|
778
867
|
case 'returnStatement':
|
|
868
|
+
if (conditionalReturnDepth.has(env)) {
|
|
869
|
+
throw new ConditionalValueReturn(evaluateExpression(statement.expression, env, file));
|
|
870
|
+
}
|
|
871
|
+
if (forExpressionDepth.has(env)) {
|
|
872
|
+
throw new ForExpressionReturn(evaluateExpression(statement.expression, env, file));
|
|
873
|
+
}
|
|
779
874
|
throwInvalidReturnContext(statement.source, file);
|
|
780
875
|
}
|
|
781
876
|
}
|
|
877
|
+
function evalBracedIfStatement(node, env, file) {
|
|
878
|
+
const branch = toBoolean(evaluateExpression(node.test, env, file)) ? node.consequent : node.alternate;
|
|
879
|
+
if (branch)
|
|
880
|
+
evaluateScopedStatements(branch, env, file);
|
|
881
|
+
}
|
|
782
882
|
function mutationTarget(name, env, source, file) {
|
|
783
883
|
const target = env.get(name, source, file);
|
|
784
884
|
if (!Array.isArray(target))
|
|
@@ -852,16 +952,24 @@ function evalForStatement(node, env, file) {
|
|
|
852
952
|
function evalForExpression(node, env, file) {
|
|
853
953
|
const values = evaluateLoopIterable(node.iterable, env, file);
|
|
854
954
|
const results = [];
|
|
855
|
-
withLoopBinding(node.variable, values, env, () => {
|
|
955
|
+
withDepth(forExpressionDepth, env, () => withLoopBinding(node.variable, values, env, () => {
|
|
856
956
|
for (const statement of node.body) {
|
|
857
957
|
if (statement.type === 'returnStatement') {
|
|
858
958
|
results.push(evaluateExpression(statement.expression, env, file));
|
|
859
959
|
}
|
|
860
960
|
else {
|
|
861
|
-
|
|
961
|
+
try {
|
|
962
|
+
evaluateStatement(statement, env, file);
|
|
963
|
+
}
|
|
964
|
+
catch (error) {
|
|
965
|
+
if (error instanceof ForExpressionReturn)
|
|
966
|
+
results.push(error.value);
|
|
967
|
+
else
|
|
968
|
+
throw error;
|
|
969
|
+
}
|
|
862
970
|
}
|
|
863
971
|
}
|
|
864
|
-
});
|
|
972
|
+
}));
|
|
865
973
|
return results;
|
|
866
974
|
}
|
|
867
975
|
function evaluateLoopIterable(node, env, file) {
|
|
@@ -20,20 +20,22 @@ export function describeInputSchema(declaration, types, registry) {
|
|
|
20
20
|
&& declaration.annotation.element?.type === 'namedType'
|
|
21
21
|
? types.get(declaration.annotation.element.name)
|
|
22
22
|
: undefined;
|
|
23
|
-
const
|
|
24
|
-
const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
|
|
23
|
+
const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, fieldRegistry(field, registry)));
|
|
25
24
|
return {
|
|
26
25
|
name: declaration.name,
|
|
27
26
|
type: typeName(declaration.annotation),
|
|
28
27
|
acceptedFormats: csvCompatible ? ['json', 'csv'] : ['json'],
|
|
29
28
|
...(registry ? measurementSchema(declaration.annotation, registry) : {}),
|
|
30
|
-
...(recordType ? { fields: recordType.fields.map(field =>
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
29
|
+
...(recordType ? { fields: recordType.fields.map(field => {
|
|
30
|
+
const fieldScope = fieldRegistry(field, registry);
|
|
31
|
+
return {
|
|
32
|
+
name: field.name,
|
|
33
|
+
type: typeName(field.annotation),
|
|
34
|
+
optional: field.optional,
|
|
35
|
+
hasDefault: field.defaultExpression !== undefined,
|
|
36
|
+
...(fieldScope ? measurementSchema(field.annotation, fieldScope) : {})
|
|
37
|
+
};
|
|
38
|
+
}) } : {})
|
|
37
39
|
};
|
|
38
40
|
}
|
|
39
41
|
export function validateInputText(text, format, declaration, types, mode = 'aggregate', context = {}, registry) {
|
|
@@ -215,15 +217,15 @@ function convertJson(value, annotation, pointer, declarationSource, types, envir
|
|
|
215
217
|
report(shapeDiagnostic(`Unknown field '${key}'`, 'declared record field', describe(object[key]), propertyPointer, context, declarationSource, fieldSource));
|
|
216
218
|
}
|
|
217
219
|
const materialized = {};
|
|
218
|
-
const recordRegistry = fieldRegistry(declaration, registry);
|
|
219
220
|
for (const field of declaration.fields) {
|
|
221
|
+
const fieldScope = fieldRegistry(field, registry);
|
|
220
222
|
const propertyPointer = `${pointer}/${escapePointer(field.name)}`;
|
|
221
223
|
if (Object.prototype.hasOwnProperty.call(object, field.name)) {
|
|
222
|
-
materialized[field.name] = convertJson(object[field.name], field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source,
|
|
224
|
+
materialized[field.name] = convertJson(object[field.name], field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, fieldScope, internalDefault);
|
|
223
225
|
}
|
|
224
226
|
else if (field.defaultExpression) {
|
|
225
|
-
const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment,
|
|
226
|
-
materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source,
|
|
227
|
+
const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, fieldScope), context.file);
|
|
228
|
+
materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, fieldScope, true);
|
|
227
229
|
}
|
|
228
230
|
else if (field.optional) {
|
|
229
231
|
materialized[field.name] = null;
|
|
@@ -240,8 +242,7 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
|
|
|
240
242
|
return [];
|
|
241
243
|
}
|
|
242
244
|
const recordType = types.get(annotation.element.name);
|
|
243
|
-
const
|
|
244
|
-
const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
|
|
245
|
+
const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, fieldRegistry(field, registry)));
|
|
245
246
|
if (!scalarFields) {
|
|
246
247
|
report(shapeDiagnostic('CSV records may contain only scalar fields', 'scalar-field RecordType[]', recordType.name, '', context, declarationSource));
|
|
247
248
|
return [];
|
|
@@ -291,8 +292,9 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
|
|
|
291
292
|
const propertyPath = `record[${recordNumber}].${field.name}`;
|
|
292
293
|
if (column < 0) {
|
|
293
294
|
if (field.defaultExpression) {
|
|
294
|
-
const
|
|
295
|
-
|
|
295
|
+
const fieldScope = fieldRegistry(field, registry);
|
|
296
|
+
const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, fieldScope), context.file);
|
|
297
|
+
materialized[field.name] = convertJson(value, field.annotation, propertyPath, context.declarationSource, types, environment, report, context, field.source, fieldScope, true);
|
|
296
298
|
}
|
|
297
299
|
else if (field.optional)
|
|
298
300
|
materialized[field.name] = null;
|
|
@@ -301,7 +303,7 @@ function convertCsv(text, annotation, declarationSource, types, environment, rep
|
|
|
301
303
|
const cell = row[column];
|
|
302
304
|
if (!cell)
|
|
303
305
|
continue;
|
|
304
|
-
materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context,
|
|
306
|
+
materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context, fieldRegistry(field, registry));
|
|
305
307
|
}
|
|
306
308
|
result.push(materialized);
|
|
307
309
|
}
|