@nova-energy/openamx 0.15.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,17 @@
1
1
  import { AmxError, staticError } from '../diagnostics/errors';
2
2
  import { fieldRegistry, setDeclaringRegistry } from '../typechecker/declarationRegistry';
3
- import { evaluateExpression } from './evaluateExpression';
3
+ import { evaluateExpression, evaluateLoopIterable, toBoolean, withLoopBinding } from './evaluateExpression';
4
4
  import { Environment } from './environment';
5
5
  const capturedContexts = new WeakMap();
6
+ const expandedElementsByModel = new WeakMap();
7
+ function hasDiagramControls(content) {
8
+ return content.some(node => node.type !== 'diagramElement');
9
+ }
10
+ function assertLegacyDiagramSerializationSupported(model) {
11
+ if (hasDiagramControls(model.declaration.content)) {
12
+ throw new Error('Version 1 control-bearing diagram models are missing expanded instances.');
13
+ }
14
+ }
6
15
  function serializeValue(value, ancestors = new Set()) {
7
16
  if (value === undefined)
8
17
  return ['undefined'];
@@ -107,10 +116,168 @@ function mapValue(value, field) {
107
116
  throw new Error(`Invalid key in serialized diagram context map '${field}'.`);
108
117
  return value;
109
118
  }
119
+ function serializeBindingValue(value, ancestors = new Set()) {
120
+ if (value === undefined || value === null || typeof value === 'boolean'
121
+ || typeof value === 'number' || typeof value === 'string')
122
+ return serializeValue(value);
123
+ if (!value || typeof value !== 'object')
124
+ throw new Error('Unsupported diagram instance binding value.');
125
+ if (ancestors.has(value))
126
+ throw new Error('Diagram instance binding contains a cyclic value.');
127
+ ancestors.add(value);
128
+ try {
129
+ if (Array.isArray(value))
130
+ return ['array', value.map(item => serializeBindingValue(item, ancestors))];
131
+ const prototype = Object.getPrototypeOf(value);
132
+ if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length > 0) {
133
+ throw new Error('Unsupported diagram instance binding value.');
134
+ }
135
+ return ['object', Object.entries(value).map(([key, item]) => [key, serializeBindingValue(item, ancestors)])];
136
+ }
137
+ finally {
138
+ ancestors.delete(value);
139
+ }
140
+ }
141
+ function assertDiagramBindingValue(value, ancestors = new Set()) {
142
+ if (value === undefined || value === null || typeof value === 'boolean'
143
+ || typeof value === 'number' || typeof value === 'string')
144
+ return;
145
+ if (!value || typeof value !== 'object')
146
+ throw new Error('Unsupported serialized diagram instance binding value.');
147
+ if (ancestors.has(value))
148
+ throw new Error('Serialized diagram instance binding contains a cyclic value.');
149
+ ancestors.add(value);
150
+ try {
151
+ if (Array.isArray(value)) {
152
+ value.forEach(item => assertDiagramBindingValue(item, ancestors));
153
+ return;
154
+ }
155
+ const prototype = Object.getPrototypeOf(value);
156
+ if (prototype !== Object.prototype && prototype !== null) {
157
+ throw new Error('Unsupported serialized diagram instance binding value.');
158
+ }
159
+ Object.values(value).forEach(item => assertDiagramBindingValue(item, ancestors));
160
+ }
161
+ finally {
162
+ ancestors.delete(value);
163
+ }
164
+ }
165
+ function collectDiagramElementPaths(content, paths = new Map(), prefix = []) {
166
+ content.forEach((node, index) => {
167
+ const path = [...prefix, { type: 'content', index }];
168
+ if (node.type === 'diagramElement') {
169
+ if (paths.has(node))
170
+ throw new Error('A diagram primitive appears at multiple AST paths.');
171
+ paths.set(node, path);
172
+ }
173
+ else if (node.type === 'diagramForBlock') {
174
+ collectDiagramElementPaths(node.content, paths, path);
175
+ }
176
+ else {
177
+ collectDiagramElementPaths(node.consequent, paths, [...path, { type: 'branch', branch: 'consequent' }]);
178
+ if (node.alternate) {
179
+ collectDiagramElementPaths(node.alternate, paths, [...path, { type: 'branch', branch: 'alternate' }]);
180
+ }
181
+ }
182
+ });
183
+ return paths;
184
+ }
185
+ function resolveDiagramElementPath(content, sourcePath) {
186
+ if (!Array.isArray(sourcePath))
187
+ throw new Error('Invalid serialized diagram instance source path.');
188
+ let currentContent = content;
189
+ let pathIndex = 0;
190
+ let controlOriginating = false;
191
+ const bindingNames = [];
192
+ while (pathIndex < sourcePath.length) {
193
+ const segment = sourcePath[pathIndex++];
194
+ if (!segment || typeof segment !== 'object' || Array.isArray(segment)
195
+ || segment.type !== 'content' || !Number.isSafeInteger(segment.index) || segment.index < 0) {
196
+ throw new Error('Invalid serialized diagram instance source path.');
197
+ }
198
+ const node = currentContent[segment.index];
199
+ if (!node)
200
+ throw new Error('Serialized diagram instance source path does not resolve.');
201
+ if (node.type === 'diagramElement') {
202
+ if (pathIndex !== sourcePath.length)
203
+ throw new Error('Serialized diagram instance source path continues past a primitive.');
204
+ return { element: node, bindingNames, controlOriginating };
205
+ }
206
+ controlOriginating = true;
207
+ if (node.type === 'diagramForBlock') {
208
+ bindingNames.push(node.variable);
209
+ currentContent = node.content;
210
+ continue;
211
+ }
212
+ const branch = sourcePath[pathIndex++];
213
+ if (!branch || typeof branch !== 'object' || Array.isArray(branch)
214
+ || branch.type !== 'branch' || (branch.branch !== 'consequent' && branch.branch !== 'alternate')) {
215
+ throw new Error('Invalid serialized diagram instance branch path.');
216
+ }
217
+ currentContent = branch.branch === 'consequent' ? node.consequent : node.alternate ?? [];
218
+ if (branch.branch === 'alternate' && !node.alternate) {
219
+ throw new Error('Serialized diagram instance source path does not resolve.');
220
+ }
221
+ }
222
+ throw new Error('Serialized diagram instance source path does not resolve to a primitive.');
223
+ }
224
+ function serializeDiagramInstances(model, instances) {
225
+ const paths = collectDiagramElementPaths(model.declaration.content);
226
+ return instances.map(instance => {
227
+ const sourcePath = paths.get(instance.element);
228
+ if (!sourcePath)
229
+ throw new Error('Diagram instance source is absent from its declaration.');
230
+ return {
231
+ identity: instance.identity,
232
+ sourcePath,
233
+ bindings: instance.bindings.map(binding => ({
234
+ name: binding.name,
235
+ value: serializeBindingValue(binding.value)
236
+ }))
237
+ };
238
+ });
239
+ }
240
+ function deserializeDiagramInstances(content, value) {
241
+ if (!Array.isArray(value))
242
+ throw new Error('Invalid serialized diagram instance list.');
243
+ let controlCount = 0;
244
+ const instances = value.map((raw, index) => {
245
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)
246
+ || !('identity' in raw) || !('bindings' in raw)
247
+ || !Number.isSafeInteger(raw.identity) || raw.identity !== index || !Array.isArray(raw.bindings)) {
248
+ throw new Error('Invalid serialized diagram instance descriptor.');
249
+ }
250
+ const descriptor = raw;
251
+ const rawBindings = descriptor.bindings;
252
+ const resolved = resolveDiagramElementPath(content, descriptor.sourcePath);
253
+ if (resolved.controlOriginating && ++controlCount > generatedElementLimit) {
254
+ throw new Error('Serialized diagram instance list exceeds the generated element limit.');
255
+ }
256
+ if (rawBindings.length !== resolved.bindingNames.length) {
257
+ throw new Error('Serialized diagram instance has incomplete loop bindings.');
258
+ }
259
+ const bindings = rawBindings.map((binding, bindingIndex) => {
260
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)
261
+ || !('name' in binding) || !('value' in binding)) {
262
+ throw new Error('Invalid serialized diagram instance loop binding.');
263
+ }
264
+ const entry = binding;
265
+ if (entry.name !== resolved.bindingNames[bindingIndex] || typeof entry.name !== 'string') {
266
+ throw new Error('Invalid serialized diagram instance loop binding.');
267
+ }
268
+ const bindingValue = deserializeValue(entry.value);
269
+ assertDiagramBindingValue(bindingValue);
270
+ return Object.freeze({ name: entry.name, value: bindingValue });
271
+ });
272
+ return Object.freeze({ identity: descriptor.identity, element: resolved.element, bindings: Object.freeze(bindings) });
273
+ });
274
+ return Object.freeze(instances);
275
+ }
110
276
  export function serializeDiagramSceneModel(model) {
111
277
  const env = capturedContexts.get(model);
112
278
  if (!env)
113
279
  throw new Error('Diagram model has no captured AMX evaluation context');
280
+ const instances = expandedElementsByModel.get(model) ?? directDiagramElements(model.declaration.content);
114
281
  const context = {
115
282
  values: env.toObject(),
116
283
  immutableValues: Object.entries(env.toObject()).filter(([, value]) => env.isImmutable(value)).map(([name]) => name),
@@ -135,26 +302,43 @@ export function serializeDiagramSceneModel(model) {
135
302
  }
136
303
  };
137
304
  const payload = {
138
- version: 1,
305
+ version: 2,
139
306
  model: serializeValue(model),
140
- context: serializeValue(context)
307
+ context: serializeValue(context),
308
+ instances: serializeDiagramInstances(model, instances),
309
+ instanceCount: instances.length
141
310
  };
142
311
  return JSON.stringify(payload);
143
312
  }
144
313
  export function deserializeDiagramSceneModel(serialized) {
145
314
  const payload = JSON.parse(serialized);
146
315
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)
147
- || !('version' in payload) || payload.version !== 1
316
+ || !('version' in payload) || (payload.version !== 1 && payload.version !== 2)
148
317
  || !('model' in payload) || !('context' in payload)) {
149
318
  throw new Error('Invalid serialized diagram model envelope.');
150
319
  }
151
- const modelValue = deserializeValue(payload.model);
152
- const contextValue = deserializeValue(payload.context);
320
+ const envelope = payload;
321
+ const version = envelope.version;
322
+ if (version === 2) {
323
+ if (!Array.isArray(envelope.instances))
324
+ throw new Error('Invalid serialized diagram instance list.');
325
+ if (!Number.isSafeInteger(envelope.instanceCount) || envelope.instanceCount !== envelope.instances.length) {
326
+ throw new Error('Serialized diagram instance count does not match its payload.');
327
+ }
328
+ }
329
+ const modelValue = deserializeValue(envelope.model);
330
+ const contextValue = deserializeValue(envelope.context);
153
331
  if (!modelValue || typeof modelValue !== 'object' || Array.isArray(modelValue)
154
332
  || !contextValue || typeof contextValue !== 'object' || Array.isArray(contextValue)) {
155
333
  throw new Error('Invalid serialized diagram model or evaluation context.');
156
334
  }
157
335
  const model = freezeData(modelValue);
336
+ if (!model.declaration || !Array.isArray(model.declaration.content)) {
337
+ throw new Error('Invalid serialized diagram declaration.');
338
+ }
339
+ const instances = version === 1
340
+ ? (assertLegacyDiagramSerializationSupported(model), directDiagramElements(model.declaration.content))
341
+ : deserializeDiagramInstances(model.declaration.content, envelope.instances);
158
342
  const context = contextValue;
159
343
  if (!context.values || typeof context.values !== 'object' || Array.isArray(context.values)
160
344
  || !Array.isArray(context.immutableValues) || !context.declarationRegistries
@@ -202,6 +386,7 @@ export function deserializeDiagramSceneModel(serialized) {
202
386
  setDeclaringRegistry(declaration, item.declaration);
203
387
  }
204
388
  capturedContexts.set(model, env);
389
+ expandedElementsByModel.set(model, instances);
205
390
  return model;
206
391
  }
207
392
  function cloneData(value, seen = new Map()) {
@@ -287,6 +472,73 @@ function cloneEnvironment(source) {
287
472
  }
288
473
  return copy;
289
474
  }
475
+ const generatedElementLimit = 64;
476
+ function directDiagramElements(content) {
477
+ if (hasDiagramControls(content)) {
478
+ throw new Error('Control-bearing diagram models are missing their expanded per-instance bindings.');
479
+ }
480
+ return Object.freeze(content.map((node, identity) => {
481
+ if (node.type !== 'diagramElement')
482
+ throw new Error('Unexpected diagram control in static content.');
483
+ return Object.freeze({ identity, element: node, bindings: Object.freeze([]) });
484
+ }));
485
+ }
486
+ function expandDiagramContent(content, env, file) {
487
+ const instances = [];
488
+ const bindings = [];
489
+ let generatedCount = 0;
490
+ const visit = (nodes, controlOriginating) => {
491
+ for (const node of nodes) {
492
+ if (node.type === 'diagramElement') {
493
+ if (controlOriginating) {
494
+ if (generatedCount >= generatedElementLimit) {
495
+ staticError('AMXD6004', 'Number of elements in this diagram exceed the maximum (64)', node.source ?? node.nameSource, file);
496
+ }
497
+ generatedCount++;
498
+ }
499
+ instances.push(Object.freeze({
500
+ identity: instances.length,
501
+ element: node,
502
+ bindings: Object.freeze(bindings.map(binding => Object.freeze({
503
+ name: binding.name,
504
+ value: cloneData(binding.value)
505
+ })))
506
+ }));
507
+ continue;
508
+ }
509
+ if (node.type === 'diagramForBlock') {
510
+ const values = evaluateLoopIterable(node.iterable, env, file);
511
+ withLoopBinding(node.variable, values, env, () => {
512
+ bindings.push({ name: node.variable, value: env.get(node.variable) });
513
+ try {
514
+ visit(node.content, true);
515
+ }
516
+ finally {
517
+ bindings.pop();
518
+ }
519
+ });
520
+ continue;
521
+ }
522
+ const branch = toBoolean(evaluateExpression(node.test, env, file))
523
+ ? node.consequent
524
+ : node.alternate;
525
+ if (branch)
526
+ visit(branch, true);
527
+ }
528
+ };
529
+ visit(content, false);
530
+ return Object.freeze(instances);
531
+ }
532
+ function withInstanceBindings(bindings, env, run, index = 0) {
533
+ if (index >= bindings.length)
534
+ return run();
535
+ let result;
536
+ const binding = bindings[index];
537
+ withLoopBinding(binding.name, [binding.value], env, () => {
538
+ result = withInstanceBindings(bindings, env, run, index + 1);
539
+ });
540
+ return result;
541
+ }
290
542
  function property(element, name) {
291
543
  const found = element.properties.find(item => item.name === name);
292
544
  if (!found)
@@ -307,13 +559,13 @@ function requiredNumber(element, name, env, file, timeline, time) {
307
559
  }
308
560
  return value;
309
561
  }
310
- function evaluateFrame(declaration, timeline, time, sourceEnvironment, file) {
562
+ function evaluateFrame(declaration, timeline, time, instances, sourceEnvironment, file) {
311
563
  if (typeof time !== 'number' || !Number.isFinite(time) || time < timeline.from || time > timeline.to) {
312
564
  staticError('AMXD004', 'Invalid time bounds', declaration.times[0]?.source ?? declaration.source, file);
313
565
  }
314
566
  const env = cloneEnvironment(sourceEnvironment);
315
567
  env.set(timeline.variable, time);
316
- const elements = declaration.elements.map((element) => {
568
+ const evaluateElement = (element) => {
317
569
  const readNumber = (name) => requiredNumber(element, name, env, file, timeline, time);
318
570
  const readStyle = (name) => {
319
571
  const value = property(element, name).expression;
@@ -394,7 +646,8 @@ function evaluateFrame(declaration, timeline, time, sourceEnvironment, file) {
394
646
  }
395
647
  throw error;
396
648
  }
397
- });
649
+ };
650
+ const elements = instances.map((instance) => withInstanceBindings(instance.bindings, env, () => evaluateElement(instance.element)));
398
651
  return Object.freeze({ time, elements: Object.freeze(elements) });
399
652
  }
400
653
  function evaluateDocumentNumber(expression, env, file, code, message, source) {
@@ -430,7 +683,8 @@ export function createDiagramModel(sourceDeclaration, sourceEnvironment, file, d
430
683
  staticError('AMXD004', 'Invalid time bounds', time.source ?? declaration.source, file);
431
684
  const duration = evaluateDocumentNumber(time.duration, env, file, 'AMXD005', 'Invalid playback duration value', time.durationSource ?? time.source);
432
685
  const timeline = Object.freeze({ variable: time.name, from, to, duration });
433
- const initialFrame = evaluateFrame(declaration, timeline, from, env, file);
686
+ const instances = expandDiagramContent(declaration.content, env, file);
687
+ const initialFrame = evaluateFrame(declaration, timeline, from, instances, env, file);
434
688
  const model = Object.freeze({
435
689
  name: declaration.name,
436
690
  title: titleExpression.value,
@@ -445,11 +699,13 @@ export function createDiagramModel(sourceDeclaration, sourceEnvironment, file, d
445
699
  statementIndex
446
700
  });
447
701
  capturedContexts.set(model, env);
702
+ expandedElementsByModel.set(model, instances);
448
703
  return model;
449
704
  }
450
705
  export function evaluateDiagramFrame(model, time, file = model.file) {
451
706
  const env = capturedContexts.get(model);
452
707
  if (!env)
453
708
  throw new Error('Diagram model has no captured AMX evaluation context');
454
- return evaluateFrame(model.declaration, model.timeline, time, env, file);
709
+ const instances = expandedElementsByModel.get(model) ?? directDiagramElements(model.declaration.content);
710
+ return evaluateFrame(model.declaration, model.timeline, time, instances, env, file);
455
711
  }
@@ -1,4 +1,4 @@
1
- import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
1
+ import { inputError, staticError, throwInputErrors, throwInvalidLoopIterable, throwInvalidRangeBounds, throwInvalidReturnContext, throwFunctionFallthrough, throwListOperationError, throwMeasurementDomainError } from '../diagnostics/errors';
2
2
  import { Environment } from './environment';
3
3
  import { evaluateStandardLibraryCall, isMathematicalFunction } from './standardLibrary';
4
4
  import { fieldRegistry } from '../typechecker/declarationRegistry';
@@ -464,8 +464,16 @@ class ForExpressionReturn {
464
464
  this.value = value;
465
465
  }
466
466
  }
467
+ class FunctionBodyReturn {
468
+ value;
469
+ constructor(value) {
470
+ this.value = value;
471
+ }
472
+ }
467
473
  const conditionalReturnDepth = new WeakMap();
468
474
  const forExpressionDepth = new WeakMap();
475
+ const functionReturnDepth = new WeakMap();
476
+ const scopedBindings = new WeakMap();
469
477
  function withDepth(depths, env, run) {
470
478
  depths.set(env, (depths.get(env) ?? 0) + 1);
471
479
  try {
@@ -479,16 +487,32 @@ function withDepth(depths, env, run) {
479
487
  depths.delete(env);
480
488
  }
481
489
  }
490
+ function rememberScopedBinding(name, env) {
491
+ const scopes = scopedBindings.get(env);
492
+ const currentScope = scopes?.[scopes.length - 1];
493
+ if (!currentScope || currentScope.has(name))
494
+ return;
495
+ const existed = env.has(name);
496
+ currentScope.set(name, { existed, value: existed ? env.get(name) : undefined });
497
+ }
482
498
  function evaluateScopedStatements(statements, env, file) {
483
- const existing = new Set(Object.keys(env.toObject()));
499
+ const scopes = scopedBindings.get(env) ?? [];
500
+ const bindings = new Map();
501
+ scopes.push(bindings);
502
+ scopedBindings.set(env, scopes);
484
503
  try {
485
504
  evaluateStatements(statements, env, file);
486
505
  }
487
506
  finally {
488
- for (const name of Object.keys(env.toObject())) {
489
- if (!existing.has(name))
507
+ scopes.pop();
508
+ for (const [name, previous] of bindings) {
509
+ if (previous.existed)
510
+ env.set(name, previous.value);
511
+ else
490
512
  env.delete(name);
491
513
  }
514
+ if (!scopes.length)
515
+ scopedBindings.delete(env);
492
516
  }
493
517
  }
494
518
  function evalBracedIfExpression(node, env, file) {
@@ -539,6 +563,12 @@ function functionArgumentSource(expression, fallback) {
539
563
  }
540
564
  return expression.source ?? fallback;
541
565
  }
566
+ function copyArrayTree(value) {
567
+ return Array.isArray(value) ? value.map(copyArrayTree) : value;
568
+ }
569
+ function isListParameter(type) {
570
+ return type.kind === 'list' || (type.kind === 'nullable' && type.element.kind === 'list');
571
+ }
542
572
  function evalFunctionCall(node, env, file) {
543
573
  const args = node.arguments.map(a => evaluateExpression(a, env, file));
544
574
  const userFunction = env.functions.get(node.callee);
@@ -546,15 +576,37 @@ function evalFunctionCall(node, env, file) {
546
576
  const functionRegistry = fieldRegistry(userFunction, env.dimensionRegistry);
547
577
  const parameters = {};
548
578
  userFunction.parameters.forEach((parameter, index) => {
549
- validateRuntimeValue(args[index], checkedType(parameter.annotation, functionRegistry), env, node.arguments[index]?.source ?? node.source, file, `function ${node.callee}.${parameter.name}`);
550
- parameters[parameter.name] = args[index];
579
+ const parameterType = checkedType(parameter.annotation, functionRegistry);
580
+ validateRuntimeValue(args[index], parameterType, env, node.arguments[index]?.source ?? node.source, file, `function ${node.callee}.${parameter.name}`);
581
+ const value = args[index];
582
+ parameters[parameter.name] = isListParameter(parameterType) && value !== null
583
+ ? copyArrayTree(value)
584
+ : value;
551
585
  });
552
586
  const frame = env.createCallFrame(parameters);
553
587
  frame.dimensionRegistry = functionRegistry;
554
588
  userFunction.parameters.forEach(parameter => {
555
589
  frame.bindingTypes.set(parameter.name, checkedType(parameter.annotation, functionRegistry));
556
590
  });
557
- const result = evaluateExpression(userFunction.body, frame, file);
591
+ let result;
592
+ const body = userFunction.body;
593
+ if (body.kind === 'expression') {
594
+ result = evaluateExpression(body.expression, frame, file);
595
+ }
596
+ else {
597
+ let returned = false;
598
+ try {
599
+ withDepth(functionReturnDepth, frame, () => evaluateStatements(body.statements, frame, file));
600
+ }
601
+ catch (error) {
602
+ if (!(error instanceof FunctionBodyReturn))
603
+ throw error;
604
+ returned = true;
605
+ result = error.value;
606
+ }
607
+ if (!returned)
608
+ throwFunctionFallthrough(body.closingSource, file);
609
+ }
558
610
  validateRuntimeValue(result, checkedType(userFunction.returnType, functionRegistry), env, node.source, file, `function ${node.callee} return`);
559
611
  return result;
560
612
  }
@@ -668,7 +720,7 @@ function toNumber(v, nodeForError) {
668
720
  const locInfo = loc ? ` at line ${loc.line}` : '';
669
721
  throw new Error(`Cannot convert value to number${locInfo}`);
670
722
  }
671
- function toBoolean(v) {
723
+ export function toBoolean(v) {
672
724
  if (typeof v === 'boolean')
673
725
  return v;
674
726
  if (typeof v === 'number')
@@ -899,6 +951,7 @@ function evaluateStatement(statement, env, file) {
899
951
  return;
900
952
  case 'variableDeclaration':
901
953
  {
954
+ rememberScopedBinding(statement.name, env);
902
955
  const value = evaluateExpression(statement.expression, env, file);
903
956
  const type = env.bindingTypes.get(statement.name);
904
957
  if (type)
@@ -947,6 +1000,9 @@ function evaluateStatement(statement, env, file) {
947
1000
  if (forExpressionDepth.has(env)) {
948
1001
  throw new ForExpressionReturn(evaluateExpression(statement.expression, env, file));
949
1002
  }
1003
+ if (functionReturnDepth.has(env)) {
1004
+ throw new FunctionBodyReturn(evaluateExpression(statement.expression, env, file));
1005
+ }
950
1006
  throwInvalidReturnContext(statement.source, file);
951
1007
  }
952
1008
  }
@@ -1023,7 +1079,12 @@ function evalRange(node, env, file) {
1023
1079
  }
1024
1080
  function evalForStatement(node, env, file) {
1025
1081
  const values = evaluateLoopIterable(node.iterable, env, file);
1026
- withLoopBinding(node.variable, values, env, () => evaluateStatements(node.body, env, file));
1082
+ withLoopBinding(node.variable, values, env, () => {
1083
+ if (functionReturnDepth.has(env))
1084
+ evaluateScopedStatements(node.body, env, file);
1085
+ else
1086
+ evaluateStatements(node.body, env, file);
1087
+ });
1027
1088
  }
1028
1089
  function evalForExpression(node, env, file) {
1029
1090
  const values = evaluateLoopIterable(node.iterable, env, file);
@@ -1048,13 +1109,13 @@ function evalForExpression(node, env, file) {
1048
1109
  }));
1049
1110
  return results;
1050
1111
  }
1051
- function evaluateLoopIterable(node, env, file) {
1112
+ export function evaluateLoopIterable(node, env, file) {
1052
1113
  const value = evaluateExpression(node, env, file);
1053
1114
  if (!Array.isArray(value))
1054
1115
  throwInvalidLoopIterable(node.source, file);
1055
1116
  return value.slice();
1056
1117
  }
1057
- function withLoopBinding(name, values, env, runIteration) {
1118
+ export function withLoopBinding(name, values, env, runIteration) {
1058
1119
  const existed = env.has(name);
1059
1120
  const previous = existed ? env.get(name) : undefined;
1060
1121
  try {
@@ -36,6 +36,19 @@ function reportDiagramDeclarations(doc) {
36
36
  }
37
37
  return declarations;
38
38
  }
39
+ function* authoredDiagramElements(content) {
40
+ for (const node of content) {
41
+ if (node.type === 'diagramElement')
42
+ yield node;
43
+ else if (node.type === 'diagramForBlock')
44
+ yield* authoredDiagramElements(node.content);
45
+ else {
46
+ yield* authoredDiagramElements(node.consequent);
47
+ if (node.alternate)
48
+ yield* authoredDiagramElements(node.alternate);
49
+ }
50
+ }
51
+ }
39
52
  function validateReportDiagramCaps(records) {
40
53
  let diagramCount = 0;
41
54
  let elementCount = 0;
@@ -45,7 +58,7 @@ function validateReportDiagramCaps(records) {
45
58
  if (diagramCount > 16) {
46
59
  staticError('AMXD012', 'A single report can have up to 16 diagrams maximum.', declaration.source, record.canonicalPath);
47
60
  }
48
- for (const element of declaration.elements) {
61
+ for (const element of authoredDiagramElements(declaration.content)) {
49
62
  elementCount++;
50
63
  if (elementCount > 512) {
51
64
  staticError('AMXD013', 'A single report can have up to 512 elements maximum.', element.source, record.canonicalPath);
@@ -77,6 +90,10 @@ function realpathOrFail(absolutePath, code, message, sourceFile) {
77
90
  moduleError(code, message, undefined, sourceFile);
78
91
  }
79
92
  }
93
+ function isWithinDirectory(root, candidate) {
94
+ const relative = path.relative(root, candidate);
95
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
96
+ }
80
97
  /**
81
98
  * Resolve, check, and evaluate the complete module graph reachable from `entryPath`,
82
99
  * returning the entry module's document and final evaluated environment.
@@ -84,7 +101,23 @@ function realpathOrFail(absolutePath, code, message, sourceFile) {
84
101
  export async function loadEntryModule(entryPath, options = {}) {
85
102
  const absoluteEntry = path.resolve(entryPath);
86
103
  const realEntry = realpathOrFail(absoluteEntry, 'AMX5001', `Entry module '${entryPath}' could not be read`, entryPath);
87
- const entryRoot = path.dirname(realEntry);
104
+ const importRoot = options.importRoot === undefined
105
+ ? path.dirname(realEntry)
106
+ : realpathOrFail(path.resolve(options.importRoot), 'AMX5001', `Import root '${options.importRoot}' could not be read`, entryPath);
107
+ let importRootStats;
108
+ try {
109
+ importRootStats = fs.statSync(importRoot);
110
+ }
111
+ catch {
112
+ moduleError('AMX5001', `Import root '${options.importRoot ?? importRoot}' could not be read`, undefined, entryPath);
113
+ }
114
+ if (!importRootStats.isDirectory()) {
115
+ moduleError('AMX5001', 'Import root must be a directory', undefined, entryPath);
116
+ }
117
+ if (realEntry !== importRoot && !isWithinDirectory(importRoot, realEntry)) {
118
+ moduleError('AMX5001', `Entry module '${entryPath}' resolves outside the import root directory tree`, undefined, entryPath);
119
+ }
120
+ const rootDescription = options.importRoot === undefined ? 'entry directory tree' : 'import root directory tree';
88
121
  if (options.sourceOverlay) {
89
122
  if (options.sourceOverlay.size > 100) {
90
123
  moduleError('AMX5001', 'Source overlay exceeds the 100-module limit', undefined, entryPath);
@@ -94,9 +127,8 @@ export async function loadEntryModule(entryPath, options = {}) {
94
127
  moduleError('AMX5001', 'Source overlay paths must be canonical absolute paths', undefined, entryPath);
95
128
  }
96
129
  const canonicalOverlayPath = realpathOrFail(overlayPath, 'AMX5001', 'Source overlay module could not be read', entryPath);
97
- const relativeToRoot = path.relative(entryRoot, canonicalOverlayPath);
98
- if (canonicalOverlayPath !== overlayPath || relativeToRoot === '' || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
99
- moduleError('AMX5001', 'Source overlay paths must be canonical and contained by the entry directory tree', undefined, entryPath);
130
+ if (canonicalOverlayPath !== overlayPath || !isWithinDirectory(importRoot, canonicalOverlayPath)) {
131
+ moduleError('AMX5001', `Source overlay paths must be canonical and contained by the ${rootDescription}`, undefined, entryPath);
100
132
  }
101
133
  }
102
134
  }
@@ -110,7 +142,7 @@ export async function loadEntryModule(entryPath, options = {}) {
110
142
  return existing;
111
143
  const cycleIndex = visiting.indexOf(canonicalPath);
112
144
  if (cycleIndex !== -1) {
113
- const cycle = [...visiting.slice(cycleIndex), canonicalPath].map(p => path.relative(entryRoot, p) || path.basename(p));
145
+ const cycle = [...visiting.slice(cycleIndex), canonicalPath].map(p => path.relative(importRoot, p) || path.basename(p));
114
146
  moduleError('AMX5003', `Import cycle detected: ${cycle.join(' -> ')}`, viaImportSource?.pathSource, viaImportSource?.file);
115
147
  }
116
148
  visiting.push(canonicalPath);
@@ -174,9 +206,8 @@ export async function loadEntryModule(entryPath, options = {}) {
174
206
  const importerDir = path.dirname(canonicalPath);
175
207
  const targetAbsolute = path.resolve(importerDir, importNode.path);
176
208
  const targetReal = realpathOrFail(targetAbsolute, 'AMX5001', `Module '${importNode.path}' could not be found`, canonicalPath);
177
- const relativeToRoot = path.relative(entryRoot, targetReal);
178
- if (relativeToRoot === '' || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
179
- moduleError('AMX5001', `Module '${importNode.path}' resolves outside the entry directory tree`, importNode.pathSource, canonicalPath);
209
+ if (!isWithinDirectory(importRoot, targetReal)) {
210
+ moduleError('AMX5001', `Module '${importNode.path}' resolves outside the ${rootDescription}`, importNode.pathSource, canonicalPath);
180
211
  }
181
212
  const dependency = await visit(targetReal, { pathSource: importNode.pathSource, file: canonicalPath });
182
213
  for (const importedName of importNode.names) {