dal-engine-core-js-lib-dev 0.0.3 → 0.0.5

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/dist/index.esm.js CHANGED
@@ -1,23 +1,49 @@
1
- /**
2
- * Base class for all objects in design.
3
- */
1
+ class DALEngineError extends Error {
2
+ constructor (message) {
3
+ super(message);
4
+ }
5
+ }
6
+
7
+ class GraphWithNameExistsError extends DALEngineError {
8
+ constructor (name) {
9
+ let msg = `Graph with name "${name}" already exists.`;
10
+ super(msg);
11
+ }
12
+ }
13
+
14
+ class UnknownGraph extends DALEngineError {
15
+ constructor (name) {
16
+ let msg = `Graph with name "${name}" does not exist.`;
17
+ super(msg);
18
+ }
19
+ }
20
+
4
21
  class Base {
5
22
  /**
6
- * Initialize the base class.
23
+ * Initialize the base class of all members of the design.
24
+ * The dal_engine_uid is a unique identifier for each instance.
25
+ * When the design is serialized, the dal_engine_uid is used
26
+ * to identify when the design is being loaded from file.
7
27
  * @param {String} name
8
28
  */
9
29
  constructor () {
10
- this.uid = crypto.randomUUID();
30
+ this.dal_engine_uid = crypto.randomUUID();
11
31
  }
12
32
 
33
+ /**
34
+ * Returns the type of object as specifed in TYPES.js.
35
+ * (e.g. participant, behavior, invariant, graph node, etc.)
36
+ * @returns {Number} The type of node.
37
+ */
13
38
  getType () {
14
39
  return this.type;
15
40
  }
16
41
  }
17
42
 
18
- class DALEngineError extends Error {
19
- constructor (message) {
20
- super(message);
43
+ class BehaviorAlreadyExistsError extends DALEngineError {
44
+ constructor (name) {
45
+ let msg = `Node with Behavior name "${name}" already exists in the graph.`;
46
+ super(msg);
21
47
  }
22
48
  }
23
49
 
@@ -31,6 +57,18 @@ class InvalidTransitionError extends DALEngineError {
31
57
  }
32
58
  }
33
59
 
60
+ class MissingAttributes extends DALEngineError {
61
+ constructor (type, attribute) {
62
+ let msg;
63
+ if (Array.isArray(attribute) && attribute.length > 1) {
64
+ msg = `"${type}" must be initialized with the attributes "${attribute}".`;
65
+ } else {
66
+ msg = `"${type}" must be initialized with the attribute "${attribute}".`;
67
+ }
68
+ super(msg);
69
+ }
70
+ }
71
+
34
72
  class UnknownBehaviorError extends DALEngineError {
35
73
  constructor (behaviorName) {
36
74
  super(`The behavior named "${behaviorName}" was not found in graph.`);
@@ -40,38 +78,69 @@ class UnknownBehaviorError extends DALEngineError {
40
78
  }
41
79
  }
42
80
 
81
+ /**
82
+ * Checks if the provided object was loaded from a file. This is determind by
83
+ * checking if the argument is an object and has a "dal_engine_uid" attribute,
84
+ * which is added to all objects when they are created and is written to file
85
+ * when the object is serialized.
86
+ *
87
+ * @param {*} obj The object to check.
88
+ * @returns {Boolean} True if the object was loaded from file, false otherwise.
89
+ */
90
+ const isLoadedFromFile = (obj) => {
91
+ return typeof obj === "object" && obj !== null
92
+ && !Array.isArray(obj) && Object.hasOwn(obj, "dal_engine_uid");
93
+ };
94
+
95
+ class ParticipantAlreadyExistsError extends DALEngineError {
96
+ constructor (name) {
97
+ let msg = `Participant with name "${name}" already exists in the behavior.`;
98
+ super(msg);
99
+ }
100
+ }
101
+
102
+ class UnknownParticipantError extends DALEngineError {
103
+ constructor (participantName) {
104
+ super(`The participant named "${participantName}" was not found in the behavior.`);
105
+ }
106
+ }
107
+
43
108
  let ENGINE_TYPES$1 = {
44
109
  BEHAVIOR: 1,
45
110
  INVARIANT: 2,
46
111
  PARTICIPANT: 3,
47
- PRIMITIVE: 4,
48
- BEHAVIORAL_CONTROL_GRAPH: 5,
49
- GRAPH_NODE: 6,
112
+ BEHAVIORAL_CONTROL_GRAPH: 4,
113
+ GRAPH_NODE: 5,
50
114
  };
51
115
  ENGINE_TYPES$1 = Object.freeze(ENGINE_TYPES$1);
52
116
 
53
117
  var ENGINE_TYPES = ENGINE_TYPES$1;
54
118
 
55
- class MissingAttributes extends DALEngineError {
56
- constructor (type, attribute) {
57
- let msg;
58
- if (Array.isArray(attribute) && attribute.length > 1) {
59
- msg = `"${type}" must be initialized with the attributes "${attribute}".`;
60
- } else {
61
- msg = `"${type}" must be initialized with the attribute "${attribute}".`;
62
- }
63
- super(msg);
64
- }
65
- }
66
-
67
- /**
68
- * Class representing a Invariant in the design.
69
- */
70
119
  class Invariant extends Base {
71
120
  /**
72
- * Initialize the Invariant.
73
- * @param {String} name
74
- * @param args
121
+ * Class representing a Invariant in the design. Invariants are rules that
122
+ * define a valid world state for participants in behaviors. The invariants
123
+ * are used to check if the design has entered a semantically invalid state
124
+ * during execution.
125
+ *
126
+ * The expected attributes in args are:
127
+ * - name: Name of the invariant.
128
+ * - rule: The rule that defines the how to enforce the invariant. This
129
+ * will be formally defined in a collection of invariant rules that can
130
+ * be chosen from when creating an invariant.
131
+ *
132
+ * Currently, the only supported invariant rule is the string min length
133
+ * rule, which can be specified as follows:
134
+ * {
135
+ * "name": "MinLengthConstraint",
136
+ * "rule": {
137
+ * "type": "minLength",
138
+ * "keys": ["value", "name"],
139
+ * "value": 1,
140
+ * },
141
+ * }
142
+ *
143
+ * @param {Object} args The arguments to initialize the invariant with.
75
144
  */
76
145
  constructor (args) {
77
146
  super();
@@ -79,17 +148,13 @@ class Invariant extends Base {
79
148
  this.invariantViolated = false;
80
149
  this.invariantType = null;
81
150
  this.traceId = null;
82
- if (typeof args === "object" && Object.hasOwn(args, "uid")) {
83
- this._loadInvariantFromJSON(args);
84
- } else {
85
- this._loadArgs(args);
86
- }
151
+ (isLoadedFromFile(args) ? this._loadFromFile(args) : this._loadArgs(args));
87
152
  }
88
153
 
89
154
  /**
90
- * Loads the provided arguments.
155
+ * Loads the invariant from the provided arguments.
91
156
  * @throws {MissingAttributes} Thrown when required attr is not present.
92
- * @param {Object} args
157
+ * @param {Object} args The arguments to initialize the invariant with.
93
158
  */
94
159
  _loadArgs (args) {
95
160
  const expectedAttributes = ["name", "rule"];
@@ -106,10 +171,10 @@ class Invariant extends Base {
106
171
  }
107
172
 
108
173
  /**
109
- * Loads the participant from a JSON object.
110
- * @param {Object} invariantJSON
174
+ * Loads the invariant from file.
175
+ * @param {Object} invariantJSON The JSON object to load the invariant from.
111
176
  */
112
- _loadInvariantFromJSON (invariantJSON) {
177
+ _loadFromFile (invariantJSON) {
113
178
  for (const [key, value] of Object.entries(invariantJSON)) {
114
179
  this[key] = value;
115
180
  } // Reset these because they are set by the execution
@@ -118,9 +183,10 @@ class Invariant extends Base {
118
183
  }
119
184
 
120
185
  /**
121
- * Evaluate the invariant.
122
- * @param {*} value
123
- * @returns {Boolean}
186
+ * Evaluate the invariant by applying the invariant rule to the provided
187
+ * value. Returns a flag indicating whether the invariant was violated.
188
+ * @param {*} value The value to evaluate the invariant on.
189
+ * @returns {Boolean} Returns flag indicating if invariant was violated.
124
190
  */
125
191
  evaluate (value) {
126
192
  this.invariantViolated = false;
@@ -131,8 +197,8 @@ class Invariant extends Base {
131
197
  }
132
198
 
133
199
  /**
134
- * Enforce the string min length invariant
135
- * @param value
200
+ * Enforce the string min length invariant.
201
+ * @param {*} value The value to enforce the invariant on.
136
202
  */
137
203
  enforceMinLength (value) {
138
204
  if ("keys" in this.rule) {
@@ -168,7 +234,7 @@ class Invariant extends Base {
168
234
  * automated testing.
169
235
  *
170
236
  * Substrate invariants correspond to a trace that represents
171
- * an environment that reveals a limitation of the substrate,
237
+ * an environment which reveals a limitation of the substrate,
172
238
  * thus motivating the invariant. It is also the environment
173
239
  * in which an implementation can prove that it respects this
174
240
  * invariant.
@@ -185,14 +251,17 @@ class Invariant extends Base {
185
251
  }
186
252
  }
187
253
 
188
- /**
189
- * Class representing a participant in the design.
190
- */
191
254
  class Participant extends Base {
192
255
  /**
193
- * Initialize the semantic participant.
194
- * @param {String} name
195
- * @param args
256
+ * Class representing a participant in the design. The participants are
257
+ * entites in deisgn that participate in the behavior. They are mapped onto
258
+ * the implementation and their value is loaded from the execution. The
259
+ * participants define a valid world state for the behavior to happen in
260
+ * through invariants. When the value of the participant violates an
261
+ * invariant, the design has entered a semantically invalid state and is
262
+ * the root cause of downstream failure(s).
263
+ *
264
+ * @param {Object} args The arguments to initialize the participant.
196
265
  */
197
266
  constructor (args) {
198
267
  super();
@@ -200,11 +269,7 @@ class Participant extends Base {
200
269
  this.invariants = [];
201
270
  this.abstractionId = null;
202
271
  this.invariantViolated = false;
203
- if (typeof args === "object" && Object.hasOwn(args, "uid")) {
204
- this._loadParticipantFromJSON(args);
205
- } else {
206
- this._loadArgs(args);
207
- }
272
+ (isLoadedFromFile(args) ? this._loadFromFile(args) : this._loadArgs(args));
208
273
  }
209
274
 
210
275
  /**
@@ -228,9 +293,9 @@ class Participant extends Base {
228
293
 
229
294
  /**
230
295
  * Loads the participant from a JSON object.
231
- * @param {Object} participantJSON
296
+ * @param {Object} participantJSON The JSON object read from file.
232
297
  */
233
- _loadParticipantFromJSON (participantJSON) {
298
+ _loadFromFile (participantJSON) {
234
299
  for (const [key, value] of Object.entries(participantJSON)) {
235
300
  if (key === "invariants") {
236
301
  value.forEach(node => this.invariants.push(new Invariant(node)));
@@ -241,8 +306,8 @@ class Participant extends Base {
241
306
 
242
307
  /**
243
308
  * Adds an invariant to the participant.
244
- * @param {Invariant} invariant
245
- * @returns
309
+ * @param {Invariant} invariant The invariant to add.
310
+ * @returns {Invariant} The invariant that was added.
246
311
  */
247
312
  addInvariant (invariant) {
248
313
  this.invariants.push(invariant);
@@ -250,16 +315,18 @@ class Participant extends Base {
250
315
  }
251
316
 
252
317
  /**
253
- * Sets the value of the participant.
254
- * @param {*} value
318
+ * Sets the value of this participant.
319
+ * @param {*} value The value to set for the participant.
255
320
  */
256
321
  setValue (value) {
257
322
  this.value = value;
258
323
  }
259
324
 
260
325
  /**
261
- * Enforces the particiants invariants.
262
- * @returns {Boolean}
326
+ * Enforces the participant's invariants. Raises a flag indicating if an
327
+ * invariant was violated and counts the number of invariant violations.
328
+ *
329
+ * @returns {Boolean} Returns flag indicating if any invariant was violated.
263
330
  */
264
331
  enforceInvariants () {
265
332
  this.invariantViolated = false;
@@ -279,19 +346,23 @@ class Participant extends Base {
279
346
  * This abstraction id will be used to assign a value to the
280
347
  * participant from the execution using the logged abstraction id.
281
348
  *
282
- * @param {String} abstractionId
349
+ * @param {String} abstractionId The abstraction ID to map to the
350
+ * participant.
283
351
  */
284
352
  mapAbstraction (abstractionId) {
353
+ /**
354
+ * TODO: Much like the behavior, I am settling on a clean way to map
355
+ * the participant onto the implementation without introducing new
356
+ * unncessary layers.
357
+ */
285
358
  this.abstractionId = abstractionId;
286
359
  }
287
360
  }
288
361
 
289
- /**
290
- * Class representing a Behavior in the design.
291
- */
292
362
  class Behavior extends Base {
293
363
  /**
294
364
  * Initialize the Behavior.
365
+ *
295
366
  * @param {String} name
296
367
  * @param args
297
368
  */
@@ -301,15 +372,12 @@ class Behavior extends Base {
301
372
  this.participants = [];
302
373
  this.abstractionIds = [];
303
374
  this.invalidWorldState = false;
304
- if (typeof args === "object" && Object.hasOwn(args, "uid")) {
305
- this._loadBehaviorFromJSON(args);
306
- } else {
307
- this._loadArgs(args);
308
- }
375
+ (isLoadedFromFile(args) ? this._loadFromFile(args) : this._loadArgs(args));
309
376
  }
310
377
 
311
378
  /**
312
379
  * Loads the provided arguments.
380
+ *
313
381
  * @throws {MissingAttributes} Thrown when required attr is not present.
314
382
  * @param {Object} args
315
383
  */
@@ -328,10 +396,12 @@ class Behavior extends Base {
328
396
  }
329
397
 
330
398
  /**
331
- * Loads the behavior from a JSON object.
332
- * @param {Object} behaviorJSON
399
+ * Loads the behavior from a JSON object that was read from file.
400
+ *
401
+ * @param {Object} behaviorJSON The JSON object representing the behavior
402
+ * read from file.
333
403
  */
334
- _loadBehaviorFromJSON (behaviorJSON) {
404
+ _loadFromFile (behaviorJSON) {
335
405
  for (const [key, value] of Object.entries(behaviorJSON)) {
336
406
  if (key === "participants") {
337
407
  value.forEach(node => this.participants.push(new Participant(node)));
@@ -342,73 +412,107 @@ class Behavior extends Base {
342
412
 
343
413
  /**
344
414
  * Adds a participant to the behavior.
345
- * @param {Participant} participant
346
- * @returns
415
+ *
416
+ * @param {Participant} participant The participant to add.
417
+ * @returns {Participant} The added participant.
418
+ * @throws {ParticipantAlreadyExistsError} Thrown when a participant with
419
+ * the same name already exists in the behavior.
347
420
  */
348
421
  addParticipant (participant) {
422
+ if (this.participants.some(p => p.name === participant.name)) {
423
+ throw new ParticipantAlreadyExistsError(participant.name);
424
+ }
349
425
  this.participants.push(participant);
350
426
  return participant;
351
427
  }
352
428
 
353
429
  /**
354
- * Set the participant value.
355
- * @param {String} participantName
356
- * @param {*} value
430
+ * Sets the value of a participant and checks for invariant violations.
431
+ * If any invariant is violated, the world state for this behavior is
432
+ * marked as invalid.
433
+ *
434
+ * @param {String} name Name of the participant whose value is being set.
435
+ * @param {*} value Value to set for the participant.
436
+ * @throws {UnknownParticipantError} Thrown when a participant with the
437
+ * provided name does not exist in the behavior.
357
438
  */
358
- setParticipantValue (participantName, value) {
359
- const participant = this.participants.find(obj => obj.name === participantName);
439
+ setParticipantValue (name, value) {
440
+ const participant = this.participants.find(obj => obj.name === name);
441
+ if (!participant) {
442
+ throw new UnknownParticipantError(name);
443
+ }
360
444
  participant.value = value;
361
- const violation = participant.enforceInvariants();
362
- if (violation) {
445
+ if (participant.enforceInvariants()) {
363
446
  this.invalidWorldState = true;
364
447
  }
365
448
  }
366
449
 
367
450
  /**
368
- * Maps the abstraction id from execution to the behavior.
369
- * @param {String} abstractionId
451
+ * Maps the abstraction id from implementation to the behavior.
452
+ *
453
+ * @param {String} abstractionId ID of mapped abstraction.
370
454
  */
371
455
  addMapping (abstractionId) {
456
+ /**
457
+ * TODO: After some more thinking, it seems to me that the
458
+ * uniqe identifier should be a file name and line number.
459
+ * It doesn't make sense to create a new abstraction id,
460
+ * however, I will resolve this soon and remove this TODO.
461
+ */
372
462
  this.abstractionIds.push(abstractionId);
373
463
  }
374
464
  }
375
465
 
376
- /**
377
- * Class representing a behavioral control graph node.
378
- */
379
466
  class GraphNode extends Base {
380
467
  /**
381
- * Initialize the node.
382
- * @param {String} name
383
- * @param args
468
+ * Class representing a behavioral control graph node. Each node has a
469
+ * behavior and a list of behaviors it can transition to. The node also
470
+ * has flags to indicate if the behavior is atomic or if the node is a
471
+ * design fork.
472
+ *
473
+ * @param {Object} args The args to initialize the graph node.
384
474
  */
385
475
  constructor (args) {
386
476
  super();
387
477
  this.type = ENGINE_TYPES.GRAPH_NODE;
388
478
  this._behavior = null;
389
479
  this._goToBehaviorIds = [];
390
- if (typeof args === "object" && args !== null) {
391
- if (Object.hasOwn(args, "uid")) {
392
- this._loadNodeFromJSON(args);
393
- } else {
394
- this._behavior = args.behavior;
395
- this._goToBehaviorIds = args.goToBehaviorsIds;
396
- }
480
+ this._isAtomic = false;
481
+ this._isDesignFork = false;
482
+ (isLoadedFromFile(args) ? this._loadFromFile(args) : this._loadArgs(args));
483
+ }
484
+
485
+ /**
486
+ * Loads the provided arguments.
487
+ * @param {Object} args Arguments to initialize the graph node with.
488
+ * @throws {MissingAttributes} Thrown when required attr is not present.
489
+ */
490
+ _loadArgs (args) {
491
+ const expectedAttributes = ["behavior", "goToBehaviorIds", "isAtomic", "isDesignFork"];
492
+ if (typeof args !== "object" || args === null || Array.isArray(args)) {
493
+ // Not an object, so all attributes are missing.
494
+ throw new MissingAttributes("GraphNode", expectedAttributes);
397
495
  }
496
+ expectedAttributes.forEach((attr) => {
497
+ if (!(attr in args)) {
498
+ throw new MissingAttributes("GraphNode", attr);
499
+ }
500
+ this["_" + attr] = args[attr];
501
+ });
398
502
  }
399
503
 
400
504
  /**
401
- * Loads the nodes from a JSON object.
402
- * @param {Object} nodesJSON
505
+ * Loads the node from file.
506
+ * @param {Object} nodeJSON The JSON object read from file.
403
507
  */
404
- _loadNodeFromJSON (nodesJSON) {
405
- for (const [key, value] of Object.entries(nodesJSON)) {
508
+ _loadFromFile (nodeJSON) {
509
+ for (const [key, value] of Object.entries(nodeJSON)) {
406
510
  if (key === "behavior") {
407
511
  this._behavior = new Behavior(value);
408
- } else if (key === "goToBehaviorsIds") {
512
+ } else if (key === "goToBehaviorIds") {
409
513
  value.forEach(behaviorId => this._goToBehaviorIds.push(behaviorId));
410
514
  } else {
411
- this[key] = nodesJSON[key];
515
+ this[key] = nodeJSON[key];
412
516
  }
413
517
  } }
414
518
 
@@ -422,15 +526,14 @@ class GraphNode extends Base {
422
526
 
423
527
  /**
424
528
  * Returns the list of behavior names that this node transitions to.
425
- * @returns {Array}
529
+ * @returns {Array} List of behavior names that this node transitions to.
426
530
  */
427
531
  getGoToBehaviors () {
428
532
  return this._goToBehaviorIds;
429
533
  }
430
534
 
431
535
  /**
432
- * Adds a behavior name to the list of behaviors that this
433
- * node transitions to.
536
+ * Adds a behavior to the transitions from this node.
434
537
  * @param {String} behaviorId ID of behavior.
435
538
  */
436
539
  addGoToBehavior (behaviorId) {
@@ -438,14 +541,17 @@ class GraphNode extends Base {
438
541
  }
439
542
 
440
543
  /**
441
- * Adds a behavior name to the list of behaviors that this
442
- * node transitions to.
544
+ * Adds list of behaviors to the transitions from this node.
443
545
  * @param {Array} behaviorIds IDs of behaviors.
444
546
  */
445
547
  addGoToBehaviors (behaviorIds) {
446
548
  this._goToBehaviorIds.push(...behaviorIds);
447
549
  }
448
550
 
551
+ /**
552
+ * Remove the behavior from the list of transitions.
553
+ * @param {String} behaviorId
554
+ */
449
555
  removeGoToBehavior (behaviorId) {
450
556
  const goToIndex = this._goToBehaviorIds.indexOf(behaviorId);
451
557
  if (goToIndex > -1) {
@@ -453,6 +559,38 @@ class GraphNode extends Base {
453
559
  }
454
560
  }
455
561
 
562
+ /**
563
+ * Raises a flag to indicate if the behavior is atomic or not.
564
+ * @param {Boolean} isAtomic Flag indicates if the behavior is atomic.
565
+ */
566
+ setIsAtomic (isAtomic) {
567
+ this._isAtomic = isAtomic;
568
+ }
569
+
570
+ /**
571
+ * Returns whether the behavior is atomic or not.
572
+ * @returns {Boolean}
573
+ */
574
+ isAtomic () {
575
+ return this._isAtomic;
576
+ }
577
+
578
+ /**
579
+ * Raises a flag to indicate if this node is a fork in the design.
580
+ * @param {Boolean} forks Flag indicates if the node is a fork.
581
+ */
582
+ setIsDesignFork (forks) {
583
+ this._isDesignFork = forks;
584
+ }
585
+
586
+ /**
587
+ * Returns whether the node is a fork in the design or not.
588
+ * @returns {Boolean}
589
+ */
590
+ isDesignFork () {
591
+ return this._isDesignFork;
592
+ }
593
+
456
594
  /**
457
595
  * Checks if the provided behavior name is a valid
458
596
  * transition from this node.
@@ -470,33 +608,60 @@ class GraphNode extends Base {
470
608
  }
471
609
  }
472
610
 
473
- /**
474
- * Class representing the behavioral control graph.
475
- */
476
611
  class BehavioralControlGraph extends Base {
477
612
  /**
478
- * Initialize the behavioral control graph.
479
- * @param {String} name
480
- * @param args
613
+ * Class representing the behavioral control graph. The behavioral control
614
+ * graph is a directed graph where nodes represent behaviors and edges
615
+ * represent valid transitions between behaviors.
616
+ *
617
+ * The graph can be used to execute the design by starting at the atomic
618
+ * node and transitioning to observed behaviors. As the design is executed,
619
+ * the values of the participants are set from the observed values and the
620
+ * invariants are checked at each transition to recognize if the design has
621
+ * entered a semantically invalid state.
622
+ *
623
+ * Currently, it only has to be initialized with a name and the remaining
624
+ * attributes can be added using the provided methods. If the graph is being
625
+ * loaded from a file, then the presence of a UID in the args will select
626
+ * the relevant method to load the graph from a JSON object.
627
+ *
628
+ * @param {Object} args The args to initialize the behavioral control graph.
481
629
  */
482
630
  constructor (args) {
483
631
  super();
484
632
  this.type = ENGINE_TYPES.BEHAVIORAL_CONTROL_GRAPH;
485
633
  this.nodes = [];
486
- if (typeof args === "object" && args !== null) {
487
- if (Object.hasOwn(args, "uid")) {
488
- this._loadGraphFromJSON(args);
489
- } else {
490
- this.name = args.name;
491
- }
634
+ (isLoadedFromFile(args) ? this._loadFromFile(args) : this._loadArgs(args));
635
+ }
636
+
637
+ /**
638
+ * Loads the provided arguments.
639
+ * @throws {MissingAttributes} Thrown when required attr is not present.
640
+ * @param {Object} args
641
+ */
642
+ _loadArgs (args) {
643
+ /**
644
+ * TODO: Move the attributes to private and use getters and setters
645
+ * for them. Repeat for all the other classes.
646
+ */
647
+ const expectedAttributes = ["name"];
648
+ if (typeof args !== "object" || args === null || Array.isArray(args)) {
649
+ // Not an object, so all attributes are missing.
650
+ throw new MissingAttributes("BehavioralControlGraph", expectedAttributes);
492
651
  }
652
+ expectedAttributes.forEach((attr) => {
653
+ if (!(attr in args)) {
654
+ throw new MissingAttributes("BehavioralControlGraph", attr);
655
+ }
656
+ this[attr] = args[attr];
657
+ });
493
658
  }
494
659
 
495
660
  /**
496
661
  * Loads the graph from a JSON object..
497
662
  * @param {Object} graphJson
498
663
  */
499
- _loadGraphFromJSON (graphJson) {
664
+ _loadFromFile (graphJson) {
500
665
  for (const [key, value] of Object.entries(graphJson)) {
501
666
  if (key === "nodes") {
502
667
  value.forEach(node => this.nodes.push(new GraphNode(node)));
@@ -506,15 +671,27 @@ class BehavioralControlGraph extends Base {
506
671
  } }
507
672
 
508
673
  /**
509
- * Adds a node to the graph.
510
- * @param {Behavior} behavior
511
- * @param {Array} goToBehaviorsIds
512
- * @returns
674
+ * Adds a node to the graph with the provided arguments.
675
+ *
676
+ * @param {Behavior} behaviorId ID of the behavior represented by the node.
677
+ * @param {Array} goToBehaviorIds IDs of the behaviors that are valid
678
+ * transitions from this node.
679
+ * @param {Boolean} isAtomic Flag indicating if the behavior represented by
680
+ * the node is atomic.
681
+ * @param {Boolean} isDesignFork Flag indicating if the node is a
682
+ * design fork.
683
+ * @throws {BehaviorAlreadyExistsError} Raised when a node with the provided
684
+ * @returns {GraphNode} The created graph node.
513
685
  */
514
- _addNode (behavior, goToBehaviorsIds) {
686
+ addNode (behaviorId, goToBehaviorIds, isAtomic, isDesignFork) {
687
+ if (this.nodes.some((node) => node.getBehavior().name === behaviorId)) {
688
+ throw new BehaviorAlreadyExistsError(behaviorId);
689
+ }
515
690
  const node = new GraphNode({
516
- behavior: behavior,
517
- goToBehaviorsIds: goToBehaviorsIds,
691
+ behavior: new Behavior({name: behaviorId}),
692
+ goToBehaviorIds: goToBehaviorIds?goToBehaviorIds:[],
693
+ isAtomic: isAtomic?isAtomic:false,
694
+ isDesignFork: isDesignFork?isDesignFork:false,
518
695
  });
519
696
  this.nodes.push(node);
520
697
  return node;
@@ -526,29 +703,25 @@ class BehavioralControlGraph extends Base {
526
703
  * @param {String} behaviorName
527
704
  * @throws {UnknownBehaviorError} Raised when the provided behavior
528
705
  * does not exist in the graph.
529
- * @returns
706
+ * @returns {GraphNode} The found graph node.
530
707
  */
531
- _findNode (behaviorName) {
532
- for (let i = 0; i < this.nodes.length; i++) {
533
- const behavior = this.nodes[i].getBehavior();
534
- if (behavior.name === behaviorName) {
535
- return this.nodes[i];
536
- }
708
+ findNode (behaviorName) {
709
+ const node = this.nodes.find(
710
+ (node) => node.getBehavior().name === behaviorName
711
+ );
712
+ if (!node) {
713
+ throw new UnknownBehaviorError(behaviorName);
537
714
  }
538
- throw new UnknownBehaviorError(behaviorName);
715
+ return node;
539
716
  }
540
717
 
541
718
  /**
542
719
  * Sets the active node given the behavior name.
543
- * The execution provides the next observed
544
- * behavior and the active node indicates if
545
- * if it is a valid transition.
546
- *
547
720
  *
548
721
  * @param {String} behaviorName
549
722
  */
550
- _setCurrentBehavior (behaviorName) {
551
- const node = this._findNode(behaviorName);
723
+ setCurrentBehavior (behaviorName) {
724
+ const node = this.findNode(behaviorName);
552
725
  /**
553
726
  * TODO: Ensure it is atomic because the execution
554
727
  * will only set a behavior when its the first one.
@@ -560,13 +733,15 @@ class BehavioralControlGraph extends Base {
560
733
  /**
561
734
  * Check if the observed behavior is a valid transition
562
735
  * given the current node.
563
- * @param {String} nextBehaviorName
736
+ *
737
+ * @param {String} nextBehaviorName Name of the next behavior to
738
+ * transition to.
564
739
  * @throws {InvalidTransitionError} Raised when the provided
565
740
  * behavior is not a valid transition.
566
741
  */
567
- _goToBehavior (nextBehaviorName) {
742
+ goToBehavior (nextBehaviorName) {
568
743
  if (this.currentNode.isValidTransition(nextBehaviorName)) {
569
- this.currentNode = this._findNode(nextBehaviorName);
744
+ this.currentNode = this.findNode(nextBehaviorName);
570
745
  } else {
571
746
  throw new InvalidTransitionError(this.currentNode.getBehavior().name, nextBehaviorName);
572
747
  }
@@ -588,30 +763,174 @@ class BehavioralControlGraph extends Base {
588
763
  }
589
764
 
590
765
  /**
591
- * An object representing an engine written in Design
592
- * abstraction language. It exposes functions
593
- * configure the engine through the DAL specification.
766
+ * Class representing a collection of atomic graphs.
767
+ *
768
+ * These graphs together represent the design. Within each graph, every node
769
+ * must be part of the same tree. There cannot be multiple disconnected trees,
770
+ * if there are, then it is a separate graph in this collection. Each graph
771
+ * is identified by a unique name and is selected as the active graph when the
772
+ * atomic behavior is observed. The atomic behavior is not transitioned to from
773
+ * any other behavior, it is the root of the tree.
774
+ */
775
+ class Graphs {
776
+ constructor () {
777
+ this._graphs = {};
778
+ this.addGraph("default graph");
779
+ }
780
+
781
+ /**
782
+ * Load the graphs from file.
783
+ *
784
+ * @param {String} jsonText JSON text representing the collection of graphs.
785
+ */
786
+ loadFromJson (jsonText) {
787
+ const parsed = JSON.parse(jsonText);
788
+ Object.keys(parsed._graphs).forEach(graphId => {
789
+ this._graphs[graphId] = new BehavioralControlGraph(parsed._graphs[graphId]);
790
+ });
791
+ this._activeGraph = this._graphs[Object.keys(this._graphs)[0]];
792
+ }
793
+
794
+ /**
795
+ * Given a graph ID, creates the graph and adds it to the collection.
796
+ *
797
+ * @param {String} graphId ID of the graph.
798
+ * @returns {BehavioralControlGraph} The graph that was added.
799
+ * @throws {GraphWithNameExistsError} Raised when a graph with the provided
800
+ * name already exists in the collection of graphs.
801
+ */
802
+ addGraph (graphId) {
803
+ if (graphId in this._graphs) {
804
+ throw new GraphWithNameExistsError(graphId);
805
+ }
806
+ this._graphs[graphId] = new BehavioralControlGraph({name: graphId});
807
+ this._activeGraph = this._graphs[graphId];
808
+ return this._activeGraph;
809
+ }
810
+
811
+ /**
812
+ * Returns the graph with the given graphID from the collection.
813
+ *
814
+ * @param {String} graphId ID of the graph to return.
815
+ * @returns {BehavioralControlGraph} The graph with the given graphId.
816
+ * @throws {UnknownGraph} Raised when a graph with the provided graphId does
817
+ * not exist in the collection of graphs.
818
+ */
819
+ getGraph (graphId) {
820
+ if (graphId in this._graphs) {
821
+ return this._graphs[graphId];
822
+ } else {
823
+ throw new UnknownGraph(graphId);
824
+ }
825
+ }
826
+
827
+ /**
828
+ * Removes a graph with the given id from the collection of graphs. After
829
+ * the graph is removed, it selects the first graph in the collection of
830
+ * graphs. If there are no graphs left in the collection, it creates a new
831
+ * graph with the name "default graph" and selects it as the active graph.
832
+ *
833
+ * @param {String} graphId ID of the graph to remove.
834
+ * @throws {UnknownGraph} Raised when the provided graphId does not exist
835
+ * in the collection of graphs.
836
+ */
837
+ removeGraph (graphId) {
838
+ if (graphId in this._graphs) {
839
+ delete this._graphs[graphId];
840
+ } else {
841
+ throw new UnknownGraph(graphId);
842
+ }
843
+ // TODO: Is there a better policy for which graph to select
844
+ // after the current graph is removed?
845
+ if (Object.keys(this._graphs).length === 0) {
846
+ this.addGraph("default graph");
847
+ } else {
848
+ this._activeGraph = this._graphs[Object.keys(this._graphs)[0]];
849
+ }
850
+ }
851
+
852
+ /**
853
+ * Finds the graph with the given graphId and sets it as the active graph.
854
+ *
855
+ * @param {String} graphId Id of the graph to set as active.
856
+ * @returns {BehavioralControlGraph} The currently active graph.
857
+ * @throws {UnknownGraph} Raised when the provided graphId does not exist
858
+ * in the collection of graphs.
859
+ */
860
+ setActiveGraph (graphId) {
861
+ if (graphId in this._graphs) {
862
+ this._activeGraph = this._graphs[graphId];
863
+ } else {
864
+ throw new UnknownGraph(graphId);
865
+ }
866
+ return this._activeGraph;
867
+ }
868
+
869
+ /**
870
+ * Returns the active graph.
871
+ *
872
+ * @returns {BehavioralControlGraph} The currently active graph.
873
+ */
874
+ getActiveGraph () {
875
+ return this._activeGraph;
876
+ }
877
+
878
+ /**
879
+ * Returns a collection of all the graphs in the design.
880
+ *
881
+ * @returns {Object} The collection of all graphs in the design.
882
+ */
883
+ getGraphs () {
884
+ return this._graphs;
885
+ }
886
+
887
+ /**
888
+ * Returns a list of all the graph names in the design.
889
+ *
890
+ * @returns {Array} A list of all graph names in the design.
891
+ */
892
+ getGraphNames () {
893
+ return Object.keys(this._graphs);
894
+ }
895
+ }
896
+
897
+ /**
898
+ * This engine can be used to define and execute designs defined in a
899
+ * Design Abstraction Language (DAL).
594
900
  *
595
- * The design specified in this engine is mapped onto
596
- * the implementation using abstraction ids. The
597
- * implementation is then instrumented and the resulting
598
- * execution trace is fed back into the engine and is
599
- * automatically debugged by transforming the execution
600
- * into the behavior of the design and enforcing the
601
- * invariants.
901
+ * This class is the main interface for users to interact with the
902
+ * engine. It exposes functions to configure the engine and to execute
903
+ * the design. It also exposes functions to serialize and deserialize
904
+ * the engine to and from JSON text.
905
+ *
906
+ * A design can consist of multiple atomic behavioral control graphs and
907
+ * this class allows users to create, select, and delete graphs. It also
908
+ * allows users to add nodes to the graph and to transition between
909
+ * behaviors in the graph. It also allows users to create participants,
910
+ * behaviors, and invariants and assign them to nodes in the graph.
911
+ *
912
+ * The selected graph is determined by the atomic behavior that is observed.
913
+ * The design is executed by transitioning between behaviors in the graph.
914
+ * The values of the participants are set from the observed values and the
915
+ * invariants are checked at each transition to recognize if the design has
916
+ * entered a semantically invalid state.
602
917
  */
603
918
  class DALEngine {
604
919
  constructor (args) {
605
- this.graph = new BehavioralControlGraph();
606
- this.loadArgs(args);
920
+ this.graphs = new Graphs();
921
+ this.graph = this.graphs.getActiveGraph();
922
+ this._loadArgs(args);
923
+ console.log("Initialized DAL Engine with graphs: ", this.graphs);
607
924
  }
608
925
 
609
926
  /**
610
- * Loads the provided arguments.
611
- * @throws {MissingAttributes} Thrown when required attr is not present.
612
- * @param {Object} args
927
+ * Sets the provided arguments to the engine.
928
+ *
929
+ * @throws {MissingAttributes} Thrown when required attributes are
930
+ * not present.
931
+ * @param {Object} args Arguments to load.
613
932
  */
614
- loadArgs (args) {
933
+ _loadArgs (args) {
615
934
  const expectedAttributes = ["name"];
616
935
  if (typeof args !== "object" || args === null || Array.isArray(args)) {
617
936
  // Not an object, so all attributes are missing.
@@ -626,100 +945,187 @@ class DALEngine {
626
945
  }
627
946
 
628
947
  /**
629
- * Exports the behavioral control graph to JSON text.
630
- * @returns {String}
948
+ * Serializes the behavioral control graphs and returns the JSON text.
949
+ *
950
+ * @returns {String} Returns JSON string representing the control graphs.
631
951
  */
632
952
  serialize () {
633
- return JSON.stringify(this.graph);
953
+ return JSON.stringify(this.graphs);
634
954
  }
635
955
 
636
956
  /**
637
- * Import the behavioral control graph from JSON text.
638
- * @param {String} jsonText
957
+ * Loads the behavioral control graphs from JSON text and sets
958
+ * the active graph to the first graph in the collection of graphs.
959
+ *
960
+ * @param {String} serializedText JSON text representing the control
961
+ * graphs.
962
+ * @throws {SyntaxError|TypeError} Thrown when the JSON text is invalid.
639
963
  */
640
- deserialize (jsonText) {
641
- this.graph = new BehavioralControlGraph(JSON.parse(jsonText));
964
+ deserialize (serializedText) {
965
+ // TODO: Improve validation to throw specific error.
966
+ this.graphs = new Graphs();
967
+ this.graphs.loadFromJson(serializedText);
968
+ this.graph = this.graphs.getActiveGraph();
642
969
  }
643
970
 
644
971
  /**
645
- * Creates a participant.
646
- * @param {Object} args
647
- * @returns {Participant}
972
+ * Creates a graph with the given name and sets it as the active graph.
973
+ *
974
+ * @param {String} name Name of the graph to create.
975
+ * @throws {GraphWithNameExistsError} Thrown when a graph with the
976
+ * provided name already exists.
977
+ */
978
+ createGraph (name) {
979
+ this.graph = this.graphs.addGraph(name);
980
+ }
981
+
982
+ /**
983
+ * Sets the active graph to the graph with the given graphId.
984
+ *
985
+ * @param {String} graphId ID of the graph to set as active
986
+ * @throws {UnknownGraph} Thrown when the provided graphId does
987
+ * not exist in the collection of graphs.
988
+ */
989
+ selectGraph (graphId) {
990
+ this.graph = this.graphs.setActiveGraph(graphId);
991
+ }
992
+
993
+ /**
994
+ * Removes the graph with the given graphId
995
+ *
996
+ * @param {String} graphId Id of graph to remove.
997
+ * @throws {UnknownGraph} Thrown when the provided graphId does not
998
+ * exist in the collection of graphs.
999
+ */
1000
+ removeGraph (graphId) {
1001
+ this.graphs.removeGraph(graphId);
1002
+ this.graph = this.graphs.getActiveGraph();
1003
+ }
1004
+
1005
+ /**
1006
+ * Returns the names of all the graphs in the design.
1007
+ *
1008
+ * @returns {Array} Returns an array of graph names.
1009
+ */
1010
+ getSelectableGraphs () {
1011
+ return this.graphs.getGraphNames();
1012
+ }
1013
+
1014
+ /**
1015
+ * Creates a participant with the provided args and returns it.
1016
+ *
1017
+ * @param {Object} args Arguments to create the participant with.
1018
+ * @returns {Participant} Returns the created participant.
1019
+ * @throws {MissingAttributes} Thrown when required attributes are not
1020
+ * present in the args. See Participant class for required attributes.
648
1021
  */
649
1022
  createParticipant (args) {
650
1023
  return new Participant(args);
651
1024
  }
652
1025
 
653
1026
  /**
654
- * Creates a behavior.
655
- * @param {Object} args
656
- * @returns {Behavior}
1027
+ * Creates a behavior with the provided args and returns it.
1028
+ *
1029
+ * @param {Object} args Arguments to create the behavior with.
1030
+ * @returns {Behavior} Returns the created behavior.
1031
+ * @throws {MissingAttributes} Thrown when required attributes are not
1032
+ * present in the args. See Behavior class for required attributes.
657
1033
  */
658
1034
  createBehavior (args) {
659
1035
  return new Behavior(args);
660
1036
  }
661
1037
 
662
1038
  /**
663
- * Creates an invariant.
664
- * @param {Object} args
665
- * @returns {Invariant}
1039
+ * Creates an invariant with the provided args and returns it.
1040
+ *
1041
+ * @param {Object} args Arguments to create the invariant with.
1042
+ * @returns {Invariant} Returns the created invariant.
1043
+ * @throws {MissingAttributes} Raised when required attributes are not
1044
+ * present in the args. See Invariant class for required attributes.
666
1045
  */
667
1046
  createInvariant (args) {
668
1047
  return new Invariant(args);
669
1048
  }
670
1049
 
671
-
672
1050
  /**
673
1051
  * Returns the node in the graph with the given behavior name.
674
- * @param {String} behaviorId
675
- * @returns {GraphNode}
1052
+ *
1053
+ * @param {String} behaviorId ID of the behavior.
1054
+ * @returns {GraphNode} Returns the node in the graph with the
1055
+ * given behavior name.
1056
+ * @throws {UnknownBehaviorError} Thrown when the provided behaviorId is not
1057
+ * a valid behavior in the graph.
676
1058
  */
677
1059
  getNode (behaviorId) {
678
- return this.graph._findNode(behaviorId);
1060
+ return this.graph.findNode(behaviorId);
679
1061
  }
680
1062
 
681
1063
  /**
682
1064
  * Adds a node to the graph with the given behaviorId and goToBehaviors.
683
- * @param {String} behaviorId
684
- * @param {Array} goToBehaviorsIds
685
- * @returns {GraphNode}
1065
+ *
1066
+ * @param {String} behaviorId ID of the behavior for the node.
1067
+ * @param {Array} goToBehaviorIds IDs of the behaviors that this node
1068
+ * transitions to.
1069
+ * @param {Boolean} isAtomic Flag to indicate if this node contains an
1070
+ * atomic behavior.
1071
+ * @param {Boolean} isDesignFork Flag to indicate if this node
1072
+ * is a fork in the design.
1073
+ * @returns {GraphNode} Returns the created graph node.
1074
+ * @throws {BehaviorAlreadyExistsError} Raised when a node with the provided
1075
+ * behaviorId already exists in the graph.
686
1076
  */
687
- addNode (behaviorId, goToBehaviorsIds) {
688
- const behavior = this.createBehavior({name: behaviorId});
689
- const goToIds = goToBehaviorsIds?goToBehaviorsIds:[];
690
- return this.graph._addNode(behavior, goToIds);
1077
+ addNode (behaviorId, goToBehaviorIds, isAtomic, isDesignFork) {
1078
+ return this.graph.addNode(
1079
+ behaviorId,
1080
+ goToBehaviorIds,
1081
+ isAtomic,
1082
+ isDesignFork
1083
+ );
691
1084
  }
692
1085
 
693
1086
  /**
694
1087
  * Deletes a node from the graph with the given behaviorId and
695
1088
  * removes it from the goToBehavior list of all other nodes.
696
- * @param {String} behaviorId
1089
+ *
1090
+ * @param {String} behaviorId Behavior ID of the node to delete.
1091
+ * @returns {GraphNode} Returns the deleted graph node.
1092
+ * @throws {UnknownBehaviorError} Thrown when the provided behaviorId is not
1093
+ * a valid behavior in the graph.
697
1094
  */
698
1095
  removeNode (behaviorId) {
699
- const node = this.graph._findNode(behaviorId);
1096
+ const node = this.graph.findNode(behaviorId);
700
1097
  const nodeIndex = this.graph.nodes.indexOf(node);
701
- this.graph.nodes.splice(nodeIndex, 1);
1098
+ const removedNode = this.graph.nodes.splice(nodeIndex, 1);
702
1099
  for (const node of this.graph.nodes) {
703
1100
  node.removeGoToBehavior(behaviorId);
704
1101
  }
1102
+ return removedNode[0];
705
1103
  }
706
1104
 
707
1105
  /**
708
- * Sets the current behavior in the graph.
709
- * @param {String} behaviorId
1106
+ * Sets the current behavior in the graph. Since the behavior is not
1107
+ * being transitioned from another, it must be an atomic behavior.
1108
+ *
1109
+ * @param {String} behaviorId ID of the behavior to set as current.
1110
+ * @throws {UnknownBehaviorError} Thrown when the provided behavior is not
1111
+ * a valid behavior in the graph.
710
1112
  */
711
1113
  setCurrentBehavior (behaviorId) {
712
- this.graph._setCurrentBehavior(behaviorId);
1114
+ this.graph.setCurrentBehavior(behaviorId);
713
1115
  }
714
1116
 
715
-
716
1117
  /**
717
- * Transitions the graph to the given behavior if it
718
- * is a valid transition from the current behavior.
1118
+ * For the current node in the graph, transitions to the node with the given
1119
+ * behaviorId if it is a valid transition.
1120
+ *
719
1121
  * @param {String} nextBehaviorId ID of the next behavior.
1122
+ * @throws {UnknownBehaviorError} Thrown when the provided behavior is not
1123
+ * a valid behavior in the graph.
1124
+ * @throws {InvalidTransitionError} Thrown when the provided behavior is not
1125
+ * a valid transition from the current node.
720
1126
  */
721
1127
  goToBehavior (nextBehaviorId) {
722
- this.graph._goToBehavior(nextBehaviorId);
1128
+ this.graph.goToBehavior(nextBehaviorId);
723
1129
  }
724
1130
  }
725
1131