@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,91 @@
1
+ import { composeUnits, powerUnit, unitFromMetadata } from './measurement';
2
+ export class ExternalUnitTextError extends Error {
3
+ unknownUnit;
4
+ constructor(message, unknownUnit) {
5
+ super(message);
6
+ this.unknownUnit = unknownUnit;
7
+ this.name = 'ExternalUnitTextError';
8
+ }
9
+ }
10
+ const unitless = Object.freeze({
11
+ scale: 1,
12
+ vector: Object.freeze({}),
13
+ factors: Object.freeze([]),
14
+ text: '1'
15
+ });
16
+ export function parseExternalUnitText(text, registry) {
17
+ let offset = 0;
18
+ const source = text.trim();
19
+ if (!source)
20
+ throw new ExternalUnitTextError('Unit expression is empty', false);
21
+ const skipWhitespace = () => {
22
+ while (/\s/.test(source[offset] ?? ''))
23
+ offset++;
24
+ };
25
+ const consume = (token) => {
26
+ skipWhitespace();
27
+ if (!source.startsWith(token, offset))
28
+ return false;
29
+ offset += token.length;
30
+ return true;
31
+ };
32
+ const parseProduct = () => {
33
+ let unit = parseFactor();
34
+ while (true) {
35
+ if (consume('*'))
36
+ unit = validateUnit(composeUnits(unit, parseFactor()));
37
+ else if (consume('/'))
38
+ unit = validateUnit(composeUnits(unit, parseFactor(), true));
39
+ else
40
+ return unit;
41
+ }
42
+ };
43
+ const parseFactor = () => {
44
+ skipWhitespace();
45
+ let unit;
46
+ if (consume('(')) {
47
+ unit = parseProduct();
48
+ if (!consume(')'))
49
+ throw new ExternalUnitTextError("Expected ')' in unit expression", false);
50
+ }
51
+ else if (source[offset] === '1' && !/[A-Za-z0-9_]/.test(source[offset + 1] ?? '')) {
52
+ offset++;
53
+ unit = unitless;
54
+ }
55
+ else {
56
+ const match = source.slice(offset).match(/^[A-Za-z_][A-Za-z0-9_]*/);
57
+ if (!match)
58
+ throw new ExternalUnitTextError('Expected a visible unit name', false);
59
+ offset += match[0].length;
60
+ const metadata = registry.units.get(match[0]);
61
+ if (!metadata)
62
+ throw new ExternalUnitTextError(`Unknown or invisible unit '${match[0]}'`, true);
63
+ unit = unitFromMetadata(metadata);
64
+ }
65
+ if (consume('^')) {
66
+ skipWhitespace();
67
+ const exponent = source.slice(offset).match(/^[+-]?\d+/);
68
+ if (!exponent)
69
+ throw new ExternalUnitTextError('Unit powers must be signed integer literals', false);
70
+ offset += exponent[0].length;
71
+ const power = Number(exponent[0]);
72
+ if (!Number.isSafeInteger(power))
73
+ throw new ExternalUnitTextError('Unit power is outside the supported integer range', false);
74
+ unit = powerUnit(unit, power);
75
+ }
76
+ return validateUnit(unit);
77
+ };
78
+ const parsed = parseProduct();
79
+ skipWhitespace();
80
+ if (offset !== source.length)
81
+ throw new ExternalUnitTextError(`Unexpected '${source[offset]}' in unit expression`, false);
82
+ return Object.freeze({ ...parsed, text: source });
83
+ }
84
+ function validateUnit(unit) {
85
+ if (!Number.isFinite(unit.scale) || unit.scale <= 0
86
+ || Object.values(unit.vector).some(exponent => !Number.isSafeInteger(exponent))
87
+ || unit.factors.some(factor => !Number.isSafeInteger(factor.exponent))) {
88
+ throw new ExternalUnitTextError('Unit expression exceeds supported scale or exponent limits', false);
89
+ }
90
+ return unit;
91
+ }
@@ -0,0 +1,508 @@
1
+ import * as path from 'path';
2
+ import { inputError, throwInputErrors } from '../diagnostics/errors';
3
+ import { Environment } from './environment';
4
+ import { evaluateExpression } from './evaluateExpression';
5
+ import { parseStrictCsvText, parseStrictJsonText } from './dataText';
6
+ import { isMeasurement, measurement } from './measurement';
7
+ import { ExternalUnitTextError, parseExternalUnitText } from './externalUnits';
8
+ import { fieldRegistry } from '../typechecker/declarationRegistry';
9
+ function defaultsEnvironment(environment, registry) {
10
+ return registry && environment.dimensionRegistry !== registry
11
+ ? new Environment(environment.recordTypes, environment.functions, registry)
12
+ : environment;
13
+ }
14
+ export { parseStrictCsvText, parseStrictJsonText } from './dataText';
15
+ export { serializeCsvText } from './csvTextSerialization';
16
+ class StopValidation {
17
+ }
18
+ export function describeInputSchema(declaration, types, registry) {
19
+ const recordType = declaration.annotation.type === 'listType'
20
+ && declaration.annotation.element?.type === 'namedType'
21
+ ? types.get(declaration.annotation.element.name)
22
+ : undefined;
23
+ const recordRegistry = recordType ? fieldRegistry(recordType, registry) : undefined;
24
+ const csvCompatible = !!recordType && recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
25
+ return {
26
+ name: declaration.name,
27
+ type: typeName(declaration.annotation),
28
+ acceptedFormats: csvCompatible ? ['json', 'csv'] : ['json'],
29
+ ...(registry ? measurementSchema(declaration.annotation, registry) : {}),
30
+ ...(recordType ? { fields: recordType.fields.map(field => ({
31
+ name: field.name,
32
+ type: typeName(field.annotation),
33
+ optional: field.optional,
34
+ hasDefault: field.defaultExpression !== undefined,
35
+ ...(recordRegistry ? measurementSchema(field.annotation, recordRegistry) : {})
36
+ })) } : {})
37
+ };
38
+ }
39
+ export function validateInputText(text, format, declaration, types, mode = 'aggregate', context = {}, registry) {
40
+ if (mode !== 'aggregate' && mode !== 'fail-fast') {
41
+ return { diagnostics: [inputError('AMX4001', `Unsupported validation mode '${safeText(String(mode))}'`, { ...context, inputName: declaration.name })] };
42
+ }
43
+ const diagnostics = [];
44
+ const report = (diagnostic) => {
45
+ diagnostics.push(diagnostic);
46
+ if (mode === 'fail-fast')
47
+ throw new StopValidation();
48
+ };
49
+ const validationContext = { ...context, inputName: declaration.name, declarationSource: declaration.source };
50
+ const environment = new Environment(types);
51
+ let value;
52
+ try {
53
+ if (format === 'json') {
54
+ const parsed = parseStrictJsonText(text);
55
+ if (parsed.issue) {
56
+ const issue = parsed.issue;
57
+ const location = offsetLocation(text, issue.offset ?? 0);
58
+ report(inputError(issue.duplicate ? 'AMX4003' : 'AMX4002', issue.message, {
59
+ ...validationContext,
60
+ dataPath: issue.dataPath || '',
61
+ dataLine: location.line,
62
+ dataColumn: location.column
63
+ }));
64
+ return { value: undefined, diagnostics };
65
+ }
66
+ value = convertJson(parsed.value, declaration.annotation, '', declaration.source, types, environment, report, validationContext, undefined, registry);
67
+ }
68
+ else {
69
+ value = convertCsv(text, declaration.annotation, declaration.source, types, environment, report, validationContext, registry);
70
+ }
71
+ }
72
+ catch (error) {
73
+ if (!(error instanceof StopValidation))
74
+ throw error;
75
+ }
76
+ return { value, diagnostics };
77
+ }
78
+ export async function loadInputValues(declarations, types, rawMappings = [], mode = 'aggregate', entryFile, registry) {
79
+ if (mode !== 'aggregate' && mode !== 'fail-fast') {
80
+ throwInputErrors([inputError('AMX4001', `Unsupported validation mode '${safeText(String(mode))}'`, { file: entryFile })]);
81
+ }
82
+ const diagnostics = [];
83
+ const report = (diagnostic) => {
84
+ diagnostics.push(diagnostic);
85
+ if (mode === 'fail-fast')
86
+ throw new StopValidation();
87
+ };
88
+ const mappings = new Map();
89
+ const declarationNames = new Set(declarations.map(declaration => declaration.name));
90
+ try {
91
+ for (const raw of rawMappings) {
92
+ const separator = raw.indexOf('=');
93
+ const name = separator < 0 ? '' : raw.slice(0, separator);
94
+ const filePath = separator < 0 ? '' : raw.slice(separator + 1);
95
+ if (!name || !filePath) {
96
+ report(inputError('AMX4001', `Invalid --input mapping '${safeText(raw)}'; expected name=path`, { file: entryFile, dataFile: raw }));
97
+ continue;
98
+ }
99
+ if (mappings.has(name)) {
100
+ report(inputError('AMX4001', `Input '${name}' is mapped more than once`, { file: entryFile, inputName: name, dataFile: filePath }));
101
+ continue;
102
+ }
103
+ mappings.set(name, filePath);
104
+ }
105
+ for (const [name, filePath] of mappings) {
106
+ if (!declarationNames.has(name)) {
107
+ report(inputError('AMX4001', `Unknown logical input '${name}'`, { file: entryFile, inputName: name, dataFile: filePath }));
108
+ }
109
+ }
110
+ const values = new Map();
111
+ for (const declaration of declarations) {
112
+ const filePath = mappings.get(declaration.name);
113
+ if (!filePath) {
114
+ report(inputError('AMX4001', `Missing mapping for input '${declaration.name}'`, {
115
+ file: entryFile, inputName: declaration.name, declarationSource: declaration.source
116
+ }));
117
+ continue;
118
+ }
119
+ const extension = path.extname(filePath);
120
+ if (extension !== '.json' && extension !== '.csv') {
121
+ report(inputError('AMX4001', `Input '${declaration.name}' must use a lowercase .json or .csv path`, {
122
+ file: entryFile, inputName: declaration.name, dataFile: filePath, declarationSource: declaration.source
123
+ }));
124
+ continue;
125
+ }
126
+ let bytes;
127
+ try {
128
+ bytes = await Bun.file(path.resolve(filePath)).arrayBuffer();
129
+ }
130
+ catch {
131
+ report(inputError('AMX4001', `Cannot read UTF-8 input file '${filePath}'`, {
132
+ file: entryFile, inputName: declaration.name, dataFile: filePath, declarationSource: declaration.source
133
+ }));
134
+ continue;
135
+ }
136
+ let text;
137
+ try {
138
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
139
+ }
140
+ catch {
141
+ report(inputError('AMX4002', `Input file '${filePath}' is not valid UTF-8`, {
142
+ file: entryFile, inputName: declaration.name, dataFile: filePath, declarationSource: declaration.source
143
+ }));
144
+ continue;
145
+ }
146
+ const validated = validateInputText(text, extension.slice(1), declaration, types, mode, { file: entryFile, dataFile: filePath }, registry);
147
+ diagnostics.push(...validated.diagnostics);
148
+ if (validated.diagnostics.length > 0 && mode === 'fail-fast')
149
+ throw new StopValidation();
150
+ values.set(declaration.name, validated.value);
151
+ }
152
+ if (diagnostics.length)
153
+ throwInputErrors(diagnostics);
154
+ return values;
155
+ }
156
+ catch (error) {
157
+ if (error instanceof StopValidation)
158
+ throwInputErrors(diagnostics);
159
+ throw error;
160
+ }
161
+ }
162
+ function convertJson(value, annotation, pointer, declarationSource, types, environment, report, context, fieldSource, registry, internalDefault = false) {
163
+ if (annotation.type === 'nullableType') {
164
+ if (value === null)
165
+ return null;
166
+ return convertJson(value, annotation.element, pointer, declarationSource, types, environment, report, context, fieldSource, registry, internalDefault);
167
+ }
168
+ if (value === null) {
169
+ report(shapeDiagnostic('Null is not allowed for this input type', typeName(annotation), 'null', pointer, context, declarationSource, fieldSource));
170
+ return null;
171
+ }
172
+ if (annotation.type === 'listType') {
173
+ if (!Array.isArray(value)) {
174
+ report(shapeDiagnostic('Expected a JSON array', typeName(annotation), actualType(value), pointer, context, declarationSource, fieldSource));
175
+ return [];
176
+ }
177
+ return value.map((item, index) => convertJson(item, annotation.element, `${pointer}/${index}`, declarationSource, types, environment, report, context, fieldSource, registry, internalDefault));
178
+ }
179
+ const name = annotation.name;
180
+ const dimension = registry?.dimensions.get(name);
181
+ if (dimension && internalDefault && isMeasurement(value)) {
182
+ if (sameVector(value.unit.vector, dimension.vector))
183
+ return value;
184
+ report(measurementDiagnostic('AMX4005', 'Measurement default has an incompatible dimension', pointer, context, declarationSource, fieldSource, formatVector(dimension.vector, registry), formatVector(value.unit.vector, registry)));
185
+ return null;
186
+ }
187
+ if (dimension)
188
+ return convertJsonMeasurement(value, dimension.vector, pointer, declarationSource, fieldSource, context, report, registry);
189
+ if (name === 'Number' || name === 'String' || name === 'Boolean' || name === 'DateTime') {
190
+ const valid = name === 'Number' ? typeof value === 'number' && Number.isFinite(value)
191
+ : name === 'String' || name === 'DateTime' ? typeof value === 'string'
192
+ : typeof value === 'boolean';
193
+ if (!valid) {
194
+ report(shapeDiagnostic(name === 'DateTime' ? 'Expected an RFC 3339 DateTime string' : 'Input value has the wrong scalar type', name, describe(value), pointer, context, declarationSource, fieldSource));
195
+ return value;
196
+ }
197
+ if (name === 'DateTime' && !isDateTime(value)) {
198
+ report(shapeDiagnostic('Invalid RFC 3339 DateTime value', name, describe(value), pointer, context, declarationSource, fieldSource));
199
+ }
200
+ return value;
201
+ }
202
+ const declaration = types.get(name);
203
+ if (!declaration) {
204
+ report(shapeDiagnostic(`Unknown input record type '${name}'`, name, actualType(value), pointer, context, declarationSource, fieldSource));
205
+ return value;
206
+ }
207
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
208
+ report(shapeDiagnostic('Expected a JSON object', name, actualType(value), pointer, context, declarationSource, fieldSource));
209
+ return {};
210
+ }
211
+ const object = value;
212
+ const declared = new Set(declaration.fields.map(field => field.name));
213
+ for (const key of Object.keys(object).filter(key => !declared.has(key)).sort()) {
214
+ const propertyPointer = `${pointer}/${escapePointer(key)}`;
215
+ report(shapeDiagnostic(`Unknown field '${key}'`, 'declared record field', describe(object[key]), propertyPointer, context, declarationSource, fieldSource));
216
+ }
217
+ const materialized = {};
218
+ const recordRegistry = fieldRegistry(declaration, registry);
219
+ for (const field of declaration.fields) {
220
+ const propertyPointer = `${pointer}/${escapePointer(field.name)}`;
221
+ 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, recordRegistry, internalDefault);
223
+ }
224
+ else if (field.defaultExpression) {
225
+ const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, recordRegistry), context.file);
226
+ materialized[field.name] = convertJson(value, field.annotation, propertyPointer, declarationSource, types, environment, report, context, field.source, recordRegistry, true);
227
+ }
228
+ else if (field.optional) {
229
+ materialized[field.name] = null;
230
+ }
231
+ else {
232
+ report(shapeDiagnostic(`Missing required field '${field.name}'`, typeName(field.annotation), 'missing', propertyPointer, context, declarationSource, field.source));
233
+ }
234
+ }
235
+ return materialized;
236
+ }
237
+ function convertCsv(text, annotation, declarationSource, types, environment, report, context, registry) {
238
+ if (annotation.type !== 'listType' || annotation.element?.type !== 'namedType' || !types.has(annotation.element.name)) {
239
+ report(shapeDiagnostic('CSV input requires a list of one record type', 'RecordType[]', typeName(annotation), '', context, declarationSource));
240
+ return [];
241
+ }
242
+ const recordType = types.get(annotation.element.name);
243
+ const recordRegistry = fieldRegistry(recordType, registry);
244
+ const scalarFields = recordType.fields.every(field => isCsvScalar(field.annotation, recordRegistry));
245
+ if (!scalarFields) {
246
+ report(shapeDiagnostic('CSV records may contain only scalar fields', 'scalar-field RecordType[]', recordType.name, '', context, declarationSource));
247
+ return [];
248
+ }
249
+ const parsed = parseStrictCsvText(text);
250
+ if (parsed.issue) {
251
+ report(inputError('AMX4002', parsed.issue.message, { ...context, dataLine: parsed.issue.line }));
252
+ return [];
253
+ }
254
+ const rows = parsed.value ?? [];
255
+ if (!rows.length) {
256
+ report(inputError('AMX4002', 'CSV input is missing its header record', { ...context, dataLine: 1 }));
257
+ return [];
258
+ }
259
+ const headers = rows[0].map(cell => cell.value);
260
+ const fieldNames = new Set(recordType.fields.map(field => field.name));
261
+ const seenHeaders = new Set();
262
+ for (const header of [...new Set(headers.filter(header => !header))].sort()) {
263
+ report(shapeDiagnostic('CSV header names must be non-empty', 'declared field name', 'empty', headerPath(header), context, declarationSource));
264
+ }
265
+ for (const header of headers) {
266
+ if (seenHeaders.has(header))
267
+ report(shapeDiagnostic(`Duplicate CSV header '${header}'`, 'unique header', header, headerPath(header), context, declarationSource));
268
+ seenHeaders.add(header);
269
+ }
270
+ for (const header of [...new Set(headers.filter(header => !fieldNames.has(header)))].sort()) {
271
+ report(shapeDiagnostic(`Unknown CSV header '${header}'`, 'declared field name', header, headerPath(header), context, declarationSource));
272
+ }
273
+ for (const field of recordType.fields) {
274
+ if (!headers.includes(field.name) && !field.optional && !field.defaultExpression) {
275
+ report(shapeDiagnostic(`CSV header is missing required field '${field.name}'`, typeName(field.annotation), 'missing column', headerPath(field.name), context, declarationSource, field.source));
276
+ }
277
+ }
278
+ const result = [];
279
+ for (let index = 1; index < rows.length; index++) {
280
+ const row = rows[index];
281
+ const recordNumber = index;
282
+ if (row.length !== headers.length) {
283
+ report(inputError('AMX4003', `CSV record ${recordNumber} has ${row.length} fields; expected ${headers.length}`, {
284
+ ...context, dataPath: `record[${recordNumber}]`, recordNumber, dataLine: recordNumber + 1,
285
+ expected: `${headers.length} fields`, actual: `${row.length} fields`
286
+ }));
287
+ }
288
+ const materialized = {};
289
+ for (const field of recordType.fields) {
290
+ const column = headers.indexOf(field.name);
291
+ const propertyPath = `record[${recordNumber}].${field.name}`;
292
+ if (column < 0) {
293
+ if (field.defaultExpression) {
294
+ const value = evaluateExpression(field.defaultExpression, defaultsEnvironment(environment, recordRegistry), context.file);
295
+ materialized[field.name] = convertJson(value, field.annotation, propertyPath, context.declarationSource, types, environment, report, context, field.source, recordRegistry, true);
296
+ }
297
+ else if (field.optional)
298
+ materialized[field.name] = null;
299
+ continue;
300
+ }
301
+ const cell = row[column];
302
+ if (!cell)
303
+ continue;
304
+ materialized[field.name] = convertCsvCell(cell, field.annotation, propertyPath, recordNumber, column + 1, field.source, report, context, recordRegistry);
305
+ }
306
+ result.push(materialized);
307
+ }
308
+ return result;
309
+ }
310
+ function convertCsvCell(cell, annotation, dataPath, recordNumber, columnNumber, fieldSource, report, context, registry) {
311
+ const base = annotation.type === 'nullableType' ? annotation.element : annotation;
312
+ const nullable = annotation.type === 'nullableType';
313
+ const location = { ...context, recordNumber, dataLine: recordNumber + 1, dataColumn: columnNumber };
314
+ if (cell.value === '' && !cell.quoted) {
315
+ if (nullable)
316
+ return null;
317
+ report(shapeDiagnostic('Blank CSV cell represents null, but this field is not nullable', typeName(annotation), 'null', dataPath, location, undefined, fieldSource));
318
+ return null;
319
+ }
320
+ if (cell.value === '' && cell.quoted) {
321
+ if (base.type === 'namedType' && base.name === 'String')
322
+ return '';
323
+ report(shapeDiagnostic('Quoted empty CSV cell is valid only for String fields', typeName(annotation), 'empty String', dataPath, location, undefined, fieldSource));
324
+ return '';
325
+ }
326
+ if (base.type !== 'namedType')
327
+ return cell.value;
328
+ const dimension = registry?.dimensions.get(base.name);
329
+ if (dimension) {
330
+ const match = cell.value.match(/^\s*([+-]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)\s+(.+?)\s*$/);
331
+ if (!match || !Number.isFinite(Number(match[1]))) {
332
+ report(measurementDiagnostic('AMX4005', 'CSV measurement cells must contain a finite number followed by a unit expression', dataPath, location, declarationSourceFrom(context), fieldSource, 'finite number and unit', safeText(cell.value)));
333
+ return cell.value;
334
+ }
335
+ return convertMeasurement(Number(match[1]), match[2], dimension.vector, dataPath, location, declarationSourceFrom(context), fieldSource, report, registry);
336
+ }
337
+ if (base.name === 'String')
338
+ return cell.value;
339
+ if (base.name === 'Boolean') {
340
+ if (cell.value === 'true')
341
+ return true;
342
+ if (cell.value === 'false')
343
+ return false;
344
+ report(shapeDiagnostic('Boolean CSV cells must be lowercase true or false', 'Boolean', cell.value, dataPath, location, undefined, fieldSource));
345
+ return cell.value;
346
+ }
347
+ if (base.name === 'Number') {
348
+ if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(cell.value) || !Number.isFinite(Number(cell.value))) {
349
+ report(shapeDiagnostic('Invalid finite JSON-number CSV cell', 'Number', cell.value, dataPath, location, undefined, fieldSource));
350
+ return cell.value;
351
+ }
352
+ return Number(cell.value);
353
+ }
354
+ if (base.name === 'DateTime') {
355
+ if (!isDateTime(cell.value))
356
+ report(shapeDiagnostic('Invalid RFC 3339 DateTime CSV cell', 'DateTime', cell.value, dataPath, location, undefined, fieldSource));
357
+ return cell.value;
358
+ }
359
+ return cell.value;
360
+ }
361
+ function convertJsonMeasurement(value, vector, pointer, declarationSource, fieldSource, context, report, registry) {
362
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
363
+ report(measurementDiagnostic('AMX4005', 'Measurement input must use the exact {value, unit} object shape', pointer, context, declarationSource, fieldSource, '{value, unit}', actualType(value)));
364
+ return null;
365
+ }
366
+ const object = value;
367
+ const keys = Object.keys(object);
368
+ if (keys.length !== 2 || !keys.includes('value') || !keys.includes('unit')) {
369
+ report(measurementDiagnostic('AMX4005', 'Measurement input must contain exactly the value and unit fields', pointer, context, declarationSource, fieldSource, '{value, unit}', describe(value)));
370
+ return null;
371
+ }
372
+ if (typeof object.value !== 'number' || !Number.isFinite(object.value) || typeof object.unit !== 'string') {
373
+ report(measurementDiagnostic('AMX4005', 'Measurement value must be finite and unit must be a string', pointer, context, declarationSource, fieldSource, 'finite value and unit string', describe(value)));
374
+ return null;
375
+ }
376
+ return convertMeasurement(object.value, object.unit, vector, `${pointer}/unit`, context, declarationSource, fieldSource, report, registry);
377
+ }
378
+ function convertMeasurement(value, unitText, expectedVector, unitPath, context, declarationSource, fieldSource, report, registry) {
379
+ let unit;
380
+ try {
381
+ unit = parseExternalUnitText(unitText, registry);
382
+ }
383
+ catch (error) {
384
+ if (!(error instanceof ExternalUnitTextError))
385
+ throw error;
386
+ const details = {
387
+ ...context,
388
+ dataPath: unitPath,
389
+ declarationSource: declarationSource ?? context.declarationSource,
390
+ fieldSource
391
+ };
392
+ report(inputError(error.unknownUnit ? 'AMX4004' : 'AMX4004', error.message, details));
393
+ return null;
394
+ }
395
+ if (!sameVector(unit.vector, expectedVector)) {
396
+ report(measurementDiagnostic('AMX4005', 'Measurement unit has an incompatible dimension', unitPath, context, declarationSource, fieldSource, formatVector(expectedVector, registry), formatVector(unit.vector, registry)));
397
+ return null;
398
+ }
399
+ return measurement(value, unit);
400
+ }
401
+ function measurementDiagnostic(code, message, dataPath, context, declarationSource, fieldSource, expected, actual) {
402
+ return inputError(code, message, {
403
+ ...context,
404
+ dataPath,
405
+ ...(expected ? { expected } : {}),
406
+ ...(actual ? { actual: safeText(actual) } : {}),
407
+ declarationSource: declarationSource ?? context.declarationSource,
408
+ fieldSource
409
+ });
410
+ }
411
+ function declarationSourceFrom(context) {
412
+ return context.declarationSource;
413
+ }
414
+ function measurementSchema(annotation, registry) {
415
+ let base = annotation;
416
+ while (base.type !== 'namedType')
417
+ base = base.element;
418
+ const dimension = registry.dimensions.get(base.name);
419
+ if (!dimension)
420
+ return {};
421
+ return {
422
+ measurement: {
423
+ dimension: base.name,
424
+ visibleUnits: [...registry.units.values()]
425
+ .filter(unit => sameVector(unit.vector, dimension.vector))
426
+ .map(unit => unit.name)
427
+ .sort()
428
+ }
429
+ };
430
+ }
431
+ function sameVector(left, right) {
432
+ const leftEntries = left instanceof Map ? [...left] : Object.entries(left);
433
+ const rightMap = new Map(right instanceof Map ? right : Object.entries(right));
434
+ return leftEntries.length === rightMap.size && leftEntries.every(([identity, exponent]) => rightMap.get(identity) === exponent);
435
+ }
436
+ function formatVector(vector, registry) {
437
+ const entries = vector instanceof Map ? [...vector] : Object.entries(vector);
438
+ return entries.sort(([left], [right]) => left.localeCompare(right)).map(([identity, exponent]) => {
439
+ const base = [...registry.dimensions.values()].find(dimension => dimension.baseIdentity === identity);
440
+ if (!base)
441
+ throw new Error('Measurement schema references an unavailable base dimension');
442
+ return `${base.declarationName}${exponent === 1 ? '' : `^${exponent}`}`;
443
+ }).join(' * ') || 'dimensionless';
444
+ }
445
+ function shapeDiagnostic(message, expected, actual, dataPath, context, declarationSource, fieldSource) {
446
+ return inputError('AMX4003', message, {
447
+ ...context,
448
+ dataPath,
449
+ expected,
450
+ actual: safeText(actual),
451
+ declarationSource: declarationSource ?? context.declarationSource,
452
+ fieldSource
453
+ });
454
+ }
455
+ function typeName(annotation) {
456
+ if (annotation.type === 'namedType')
457
+ return annotation.name;
458
+ return annotation.type === 'listType' ? `${typeName(annotation.element)}[]` : `${typeName(annotation.element)}?`;
459
+ }
460
+ function isCsvScalar(annotation, registry) {
461
+ const base = annotation.type === 'nullableType' ? annotation.element : annotation;
462
+ return base.type === 'namedType' && (['String', 'Number', 'Boolean', 'DateTime'].includes(base.name)
463
+ || !!registry?.dimensions.has(base.name));
464
+ }
465
+ function isDateTime(value) {
466
+ const parts = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/);
467
+ if (!parts)
468
+ return false;
469
+ const [, year, month, day, hour, minute, second, offset] = parts;
470
+ const date = new Date(0);
471
+ date.setUTCFullYear(+year, +month - 1, +day);
472
+ return date.getUTCFullYear() === +year && date.getUTCMonth() === +month - 1 && date.getUTCDate() === +day
473
+ && +hour <= 23 && +minute <= 59 && +second <= 59
474
+ && (offset === 'Z' || (+offset.slice(1, 3) <= 23 && +offset.slice(4) <= 59));
475
+ }
476
+ function actualType(value) {
477
+ if (value === null)
478
+ return 'null';
479
+ if (Array.isArray(value))
480
+ return 'array';
481
+ if (typeof value === 'object')
482
+ return 'object';
483
+ return typeof value;
484
+ }
485
+ function describe(value) {
486
+ let text;
487
+ try {
488
+ text = JSON.stringify(value);
489
+ }
490
+ catch {
491
+ text = String(value);
492
+ }
493
+ return safeText(text ?? String(value));
494
+ }
495
+ function safeText(value) {
496
+ return value.replace(/[\x00-\x1f\x7f]/g, character => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`).slice(0, 160);
497
+ }
498
+ function escapePointer(value) {
499
+ return value.replace(/~/g, '~0').replace(/\//g, '~1');
500
+ }
501
+ function headerPath(value) {
502
+ return value ? `header.${value}` : 'header';
503
+ }
504
+ function offsetLocation(text, offset) {
505
+ const before = text.slice(0, offset);
506
+ const lines = before.split('\n');
507
+ return { line: lines.length, column: lines[lines.length - 1].length + 1 };
508
+ }