-
Notifications
You must be signed in to change notification settings - Fork 23
/
jssm.ts
3513 lines (2539 loc) · 92.7 KB
/
jssm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// whargarbl lots of these return arrays could/should be sets
type StateType = string;
import { reduce as reduce_to_639 } from 'reduce-to-639-1';
import { circular_buffer } from 'circular_buffer_js';
import {
JssmGenericState, JssmGenericConfig, JssmStateConfig,
JssmTransition, JssmTransitions, JssmTransitionList, // JssmTransitionRule,
JssmMachineInternalState,
JssmAllowsOverride,
JssmParseTree,
JssmStateDeclaration, JssmStateDeclarationRule,
JssmStateStyleKey, JssmStateStyleKeyList,
JssmCompileSe, JssmCompileSeStart, JssmCompileRule,
JssmLayout, JssmHistory,
JssmArrowKind,
JssmSerialization,
JssmPropertyDefinition,
FslDirection, FslDirections, FslTheme,
HookDescription, HookHandler, HookContext, HookResult, HookComplexResult,
JssmBaseTheme,
JssmRng
} from './jssm_types';
import { arrow_direction, arrow_left_kind, arrow_right_kind } from './jssm_arrow';
import { compile, make, makeTransition, wrap_parse } from './jssm_compiler';
import { theme_mapping, base_theme } from './jssm_theme';
import {
seq,
unique, find_repeated,
weighted_rand_select, weighted_sample_select,
histograph, weighted_histo_key,
array_box_if_string,
name_bind_prop_and_state, hook_name, named_hook_name,
gen_splitmix32
} from './jssm_util';
import * as constants from './jssm_constants';
const { shapes, gviz_shapes, named_colors } = constants;
import { parse } from './fsl_parser';
import { version, build_time } from './version'; // replaced from package.js in build
import { JssmError } from './jssm_error';
/*********
*
* An internal method meant to take a series of declarations and fold them into
* a single multi-faceted declaration, in the process of building a state. Not
* generally meant for external use.
*
* @internal
*
*/
function transfer_state_properties(state_decl: JssmStateDeclaration): JssmStateDeclaration {
state_decl.declarations.map( (d: JssmStateDeclarationRule) => {
switch (d.key) {
case 'shape' : state_decl.shape = d.value; break;
case 'color' : state_decl.color = d.value; break;
case 'corners' : state_decl.corners = d.value; break;
case 'line-style' : state_decl.lineStyle = d.value; break;
case 'text-color' : state_decl.textColor = d.value; break;
case 'background-color' : state_decl.backgroundColor = d.value; break;
case 'state-label' : state_decl.stateLabel = d.value; break;
case 'border-color' : state_decl.borderColor = d.value; break;
case 'state_property' : state_decl.property = { name: d.name, value: d.value }; break;
default: throw new JssmError(undefined, `Unknown state property: '${JSON.stringify(d)}'`);
}
} );
return state_decl;
}
function state_style_condense(jssk: JssmStateStyleKeyList): JssmStateConfig {
const state_style: JssmStateConfig = {};
if (Array.isArray(jssk)) {
jssk.forEach( (key, i) => {
if (typeof key !== 'object') {
throw new JssmError(this, `invalid state item ${i} in state_style_condense list: ${JSON.stringify(key)}`);
}
switch (key.key) {
case 'shape':
if (state_style.shape !== undefined) {
throw new JssmError(this, `cannot redefine 'shape' in state_style_condense, already defined`);
}
state_style.shape = key.value;
break;
case 'color':
if (state_style.color !== undefined) {
throw new JssmError(this, `cannot redefine 'color' in state_style_condense, already defined`);
}
state_style.color = key.value;
break;
case 'text-color':
if (state_style.textColor !== undefined) {
throw new JssmError(this, `cannot redefine 'text-color' in state_style_condense, already defined`);
}
state_style.textColor = key.value;
break;
case 'corners':
if (state_style.corners !== undefined) {
throw new JssmError(this, `cannot redefine 'corners' in state_style_condense, already defined`);
}
state_style.corners = key.value;
break;
case 'line-style':
if (state_style.lineStyle !== undefined) {
throw new JssmError(this, `cannot redefine 'line-style' in state_style_condense, already defined`);
}
state_style.lineStyle = key.value;
break;
case 'background-color':
if (state_style.backgroundColor !== undefined) {
throw new JssmError(this, `cannot redefine 'background-color' in state_style_condense, already defined`);
}
state_style.backgroundColor = key.value;
break;
case 'state-label':
if (state_style.stateLabel !== undefined) {
throw new JssmError(this, `cannot redefine 'state-label' in state_style_condense, already defined`);
}
state_style.stateLabel = key.value;
break;
case 'border-color':
if (state_style.borderColor !== undefined) {
throw new JssmError(this, `cannot redefine 'border-color' in state_style_condense, already defined`);
}
state_style.borderColor = key.value;
break;
default:
// TODO do that <never> trick to assert this list is complete
throw new JssmError(this, `unknown state style key in condense: ${(key as any).key}`);
}
});
} else if (jssk === undefined) {
// do nothing, undefined is legal and means we should return the empty container above
} else {
throw new JssmError(this, 'state_style_condense received a non-array');
}
return state_style;
}
// TODO add a lotta docblock here
class Machine<mDT> {
_state : StateType;
_states : Map<StateType, JssmGenericState>;
_edges : Array< JssmTransition<StateType, mDT> >;
_edge_map : Map<StateType, Map<StateType, number>>;
_named_transitions : Map<StateType, number>;
_actions : Map<StateType, Map<StateType, number>>;
_reverse_actions : Map<StateType, Map<StateType, number>>;
_reverse_action_targets : Map<StateType, Map<StateType, number>>;
_start_states : Set<StateType>;
_end_states : Set<StateType>;
_machine_author? : Array<string>;
_machine_comment? : string;
_machine_contributor? : Array<string>;
_machine_definition? : string;
_machine_language? : string;
_machine_license? : string;
_machine_name? : string;
_machine_version? : string;
_fsl_version? : string;
_raw_state_declaration? : Array<Object>;
_state_declarations : Map<StateType, JssmStateDeclaration>;
_data? : mDT;
_instance_name : string;
_rng_seed : number;
_rng : JssmRng;
_graph_layout : JssmLayout;
_dot_preamble : string;
_arrange_declaration : Array<Array<StateType>>;
_arrange_start_declaration : Array<Array<StateType>>;
_arrange_end_declaration : Array<Array<StateType>>;
_themes : FslTheme[];
_flow : FslDirection;
_has_hooks : boolean;
_has_basic_hooks : boolean;
_has_named_hooks : boolean;
_has_entry_hooks : boolean;
_has_exit_hooks : boolean;
_has_global_action_hooks : boolean;
_has_transition_hooks : boolean;
// no boolean for the single hooks, just check if they're defined
_has_forced_transitions : boolean;
_hooks : Map<string, HookHandler<mDT>>;
_named_hooks : Map<string, HookHandler<mDT>>;
_entry_hooks : Map<string, HookHandler<mDT>>;
_exit_hooks : Map<string, HookHandler<mDT>>;
_global_action_hooks : Map<string, HookHandler<mDT>>;
_any_action_hook : HookHandler<mDT> | undefined;
_standard_transition_hook : HookHandler<mDT> | undefined;
_main_transition_hook : HookHandler<mDT> | undefined;
_forced_transition_hook : HookHandler<mDT> | undefined;
_any_transition_hook : HookHandler<mDT> | undefined;
_has_post_hooks : boolean;
_has_post_basic_hooks : boolean;
_has_post_named_hooks : boolean;
_has_post_entry_hooks : boolean;
_has_post_exit_hooks : boolean;
_has_post_global_action_hooks : boolean;
_has_post_transition_hooks : boolean;
// no boolean for the single hooks, just check if they're defined
_code_allows_override : JssmAllowsOverride;
_config_allows_override : JssmAllowsOverride;
_post_hooks : Map<string, HookHandler<mDT>>;
_post_named_hooks : Map<string, HookHandler<mDT>>;
_post_entry_hooks : Map<string, HookHandler<mDT>>;
_post_exit_hooks : Map<string, HookHandler<mDT>>;
_post_global_action_hooks : Map<string, HookHandler<mDT>>;
_post_any_action_hook : HookHandler<mDT> | undefined;
_post_standard_transition_hook : HookHandler<mDT> | undefined;
_post_main_transition_hook : HookHandler<mDT> | undefined;
_post_forced_transition_hook : HookHandler<mDT> | undefined;
_post_any_transition_hook : HookHandler<mDT> | undefined;
_property_keys : Set<string>;
_default_properties : Map<string, any>;
_state_properties : Map<string, any>;
_required_properties : Set<string>;
_history : JssmHistory<mDT>;
_history_length : number;
_state_style : JssmStateConfig;
_active_state_style : JssmStateConfig;
_hooked_state_style : JssmStateConfig;
_terminal_state_style : JssmStateConfig;
_start_state_style : JssmStateConfig;
_end_state_style : JssmStateConfig;
_state_labels : Map<string, string>;
_time_source : () => number;
_create_started : number;
_created : number;
_after_mapping : Map<string, [string, number]>;
_timeout_source : ( Function, number ) => number;
_clear_timeout_source : ( h ) => void;
_timeout_handle : number | undefined;
_timeout_target : string | undefined;
_timeout_target_time : number | undefined;
// whargarbl this badly needs to be broken up, monolith master
constructor({
start_states,
end_states = [],
initial_state,
start_states_no_enforce,
complete = [],
transitions,
machine_author,
machine_comment,
machine_contributor,
machine_definition,
machine_language,
machine_license,
machine_name,
machine_version,
state_declaration,
property_definition,
state_property,
fsl_version,
dot_preamble = undefined,
arrange_declaration = [],
arrange_start_declaration = [],
arrange_end_declaration = [],
theme = ['default'],
flow = 'down',
graph_layout = 'dot',
instance_name,
history,
data,
default_state_config,
default_active_state_config,
default_hooked_state_config,
default_terminal_state_config,
default_start_state_config,
default_end_state_config,
allows_override,
config_allows_override,
rng_seed,
time_source,
timeout_source,
clear_timeout_source
}: JssmGenericConfig<StateType, mDT>) {
this._time_source = () => new Date().getTime();
this._create_started = this._time_source();
this._instance_name = instance_name;
this._states = new Map();
this._state_declarations = new Map();
this._edges = [];
this._edge_map = new Map();
this._named_transitions = new Map();
this._actions = new Map();
this._reverse_actions = new Map();
this._reverse_action_targets = new Map(); // todo
this._start_states = new Set(start_states);
this._end_states = new Set(end_states); // todo consider what to do about incorporating complete too
this._machine_author = array_box_if_string(machine_author);
this._machine_comment = machine_comment;
this._machine_contributor = array_box_if_string(machine_contributor);
this._machine_definition = machine_definition;
this._machine_language = machine_language;
this._machine_license = machine_license;
this._machine_name = machine_name;
this._machine_version = machine_version;
this._raw_state_declaration = state_declaration || [];
this._fsl_version = fsl_version;
this._arrange_declaration = arrange_declaration;
this._arrange_start_declaration = arrange_start_declaration;
this._arrange_end_declaration = arrange_end_declaration;
this._dot_preamble = dot_preamble;
this._themes = theme;
this._flow = flow;
this._graph_layout = graph_layout;
this._has_hooks = false;
this._has_basic_hooks = false;
this._has_named_hooks = false;
this._has_entry_hooks = false;
this._has_exit_hooks = false;
this._has_global_action_hooks = false;
this._has_transition_hooks = true;
// no need for a boolean for single hooks, just test for undefinedness
this._has_forced_transitions = false;
this._hooks = new Map();
this._named_hooks = new Map();
this._entry_hooks = new Map();
this._exit_hooks = new Map();
this._global_action_hooks = new Map();
this._any_action_hook = undefined;
this._standard_transition_hook = undefined;
this._main_transition_hook = undefined;
this._forced_transition_hook = undefined;
this._any_transition_hook = undefined;
this._has_post_hooks = false;
this._has_post_basic_hooks = false;
this._has_post_named_hooks = false;
this._has_post_entry_hooks = false;
this._has_post_exit_hooks = false;
this._has_post_global_action_hooks = false;
this._has_post_transition_hooks = true;
// no need for a boolean for single hooks, just test for undefinedness
this._code_allows_override = allows_override;
this._config_allows_override = config_allows_override;
if ( (allows_override === false) && (config_allows_override === true) ) {
throw new JssmError(undefined, "Code specifies no override, but config tries to permit; config may not be less strict than code");
}
this._post_hooks = new Map();
this._post_named_hooks = new Map();
this._post_entry_hooks = new Map();
this._post_exit_hooks = new Map();
this._post_global_action_hooks = new Map();
this._post_any_action_hook = undefined;
this._post_standard_transition_hook = undefined;
this._post_main_transition_hook = undefined;
this._post_forced_transition_hook = undefined;
this._post_any_transition_hook = undefined;
this._data = data;
this._property_keys = new Set();
this._default_properties = new Map();
this._state_properties = new Map();
this._required_properties = new Set();
this._state_style = state_style_condense(default_state_config);
this._active_state_style = state_style_condense(default_active_state_config);
this._hooked_state_style = state_style_condense(default_hooked_state_config);
this._terminal_state_style = state_style_condense(default_terminal_state_config);
this._start_state_style = state_style_condense(default_start_state_config);
this._end_state_style = state_style_condense(default_end_state_config);
this._history_length = history || 0;
this._history = new circular_buffer(this._history_length);
this._state_labels = new Map();
this._rng_seed = rng_seed ?? new Date().getTime();
this._rng = gen_splitmix32(this._rng_seed);
this._timeout_source = timeout_source ?? ( (f: Function, a: number) => setTimeout(f, a) );
this._clear_timeout_source = clear_timeout_source ?? ( (h: number) => clearTimeout(h) );
this._timeout_handle = undefined;
this._timeout_target = undefined;
this._timeout_target_time = undefined;
this._after_mapping = new Map();
// consolidate the state declarations
if (state_declaration) {
state_declaration.map((state_decl: JssmStateDeclaration) => {
if (this._state_declarations.has(state_decl.state)) { // no repeats
throw new JssmError(this, `Added the same state declaration twice: ${JSON.stringify(state_decl.state)}`);
}
this._state_declarations.set(state_decl.state, transfer_state_properties(state_decl));
});
}
// walk the decls for labels; aggregate them when found
[... this._state_declarations].map(sd => {
const [key, decl] = sd,
labelled = decl.declarations.filter(d => d.key === 'state-label');
if (labelled.length > 1) {
throw new JssmError(this, `state ${key} may only have one state-label; has ${labelled.length}`);
}
if (labelled.length === 1) {
this._state_labels.set(key, labelled[0].value);
}
});
// walk the transitions
transitions.map((tr: JssmTransition<StateType, mDT>) => {
if ( tr.from === undefined ) { throw new JssmError(this, `transition must define 'from': ${JSON.stringify(tr)}`); }
if ( tr.to === undefined ) { throw new JssmError(this, `transition must define 'to': ${JSON.stringify(tr)}`); }
// get the cursors. what a mess
const cursor_from: JssmGenericState
= this._states.get(tr.from)
|| { name: tr.from, from: [], to: [], complete: complete.includes(tr.from) };
if (!(this._states.has(tr.from))) {
this._new_state(cursor_from);
}
const cursor_to: JssmGenericState
= this._states.get(tr.to)
|| { name: tr.to, from: [], to: [], complete: complete.includes(tr.to) };
if (!(this._states.has(tr.to))) {
this._new_state(cursor_to);
}
// guard against existing connections being re-added
if (cursor_from.to.includes(tr.to)) {
throw new JssmError(this, `already has ${JSON.stringify(tr.from)} to ${JSON.stringify(tr.to)}`);
} else {
cursor_from.to.push(tr.to);
cursor_to.from.push(tr.from);
}
// add the edge; note its id
this._edges.push(tr);
const thisEdgeId: number = this._edges.length - 1;
if (tr.forced_only) { this._has_forced_transitions = true; }
// guard against repeating a transition name
if (tr.name) {
if (this._named_transitions.has(tr.name)) {
throw new JssmError(this, `named transition "${JSON.stringify(tr.name)}" already created`);
} else {
this._named_transitions.set(tr.name, thisEdgeId);
}
}
// set up the after mapping, if any
if (tr.after_time) {
this._after_mapping.set(tr.from, [tr.to, tr.after_time])
}
// set up the mapping, so that edges can be looked up by endpoint pairs
const from_mapping: Map<StateType, number> = this._edge_map.get(tr.from) || new Map();
if (!(this._edge_map.has(tr.from))) {
this._edge_map.set(tr.from, from_mapping);
}
// const to_mapping = from_mapping.get(tr.to);
from_mapping.set(tr.to, thisEdgeId); // already checked that this mapping doesn't exist, above
// set up the action mapping, so that actions can be looked up by origin
if (tr.action) {
// forward mapping first by action name
let actionMap: Map<StateType, number> = this._actions.get(tr.action);
if (!(actionMap)) {
actionMap = new Map();
this._actions.set(tr.action, actionMap);
}
if (actionMap.has(tr.from)) {
throw new JssmError(this, `action ${JSON.stringify(tr.action)} already attached to origin ${JSON.stringify(tr.from)}`);
} else {
actionMap.set(tr.from, thisEdgeId);
}
// reverse mapping first by state origin name
let rActionMap: Map<StateType, number> = this._reverse_actions.get(tr.from);
if (!(rActionMap)) {
rActionMap = new Map();
this._reverse_actions.set(tr.from, rActionMap);
}
// no need to test for reverse mapping pre-presence;
// forward mapping already covers collisions
rActionMap.set(tr.action, thisEdgeId);
// reverse mapping first by state target name
if (!(this._reverse_action_targets.has(tr.to))) {
this._reverse_action_targets.set(tr.to, new Map());
}
/* todo comeback
fundamental problem is roActionMap needs to be a multimap
const roActionMap = this._reverse_action_targets.get(tr.to); // wasteful - already did has - refactor
if (roActionMap) {
if (roActionMap.has(tr.action)) {
throw new JssmError(this, `ro-action ${tr.to} already attached to action ${tr.action}`);
} else {
roActionMap.set(tr.action, thisEdgeId);
}
} else {
throw new JssmError(this, `should be impossible - flow doesn\'t know .set precedes .get yet again. severe error?');
}
*/
}
});
if (Array.isArray(property_definition)) {
property_definition.forEach(pr => {
this._property_keys.add(pr.name);
if (pr.hasOwnProperty('default_value')) {
this._default_properties.set(pr.name, pr.default_value);
}
if (pr.hasOwnProperty('required') && (pr.required === true)) {
this._required_properties.add(pr.name);
}
});
}
if (Array.isArray(state_property)) {
state_property.forEach(sp => {
this._state_properties.set(sp.name, sp.default_value);
});
}
// set initial state either from the specified or the start state list. validate admission behavior.
if (initial_state) {
if (! (this._states.has(initial_state)) ) {
throw new JssmError(this, `requested start state ${initial_state} does not exist`);
}
if ( (! (start_states_no_enforce) ) && (! (start_states.includes(initial_state) )) ) {
throw new JssmError(this, `requested start state ${initial_state} is not in start state list; add {start_states_no_enforce:true} to constructor options if desired`);
}
this._state = initial_state;
} else {
this._state = start_states[0];
}
// done building, do checks
// assert all props are valid
this._state_properties.forEach( (_value, key) => {
const inside = JSON.parse(key);
if (Array.isArray(inside)) {
const j_property = inside[0];
if (typeof j_property === 'string') {
const j_state = inside[1];
if (typeof j_state === 'string') {
if (!(this.known_prop(j_property))) {
throw new JssmError(this, `State "${j_state}" has property "${j_property}" which is not globally declared`);
}
}
}
}
});
// assert all required properties are serviced
this._required_properties.forEach( dp_key => {
if (this._default_properties.has(dp_key)) {
throw new JssmError(this, `The property "${dp_key}" is required, but also has a default; these conflict`);
}
this.states().forEach(s => {
const bound_name = name_bind_prop_and_state(dp_key, s);
if (!(this._state_properties.has(bound_name))) {
throw new JssmError(this, `State "${s}" is missing required property "${dp_key}"`);
}
});
});
// assert chosen starting state is valid
if (!(this.has_state( this.state() ))) {
throw new JssmError(this, `Current start state "${this.state()}" does not exist`);
}
// assert all starting states are valid
start_states.forEach( (ss, ssi) => {
if (!(this.has_state(ss))) {
throw new JssmError(this, `Start state ${ssi} "${ss}" does not exist`);
}
});
// assert chosen starting state is valid
if (!( start_states.length === this._start_states.size )) {
throw new JssmError(this, `Start states cannot be repeated`);
}
this._created = this._time_source();
this.auto_set_state_timeout();
this._arrange_declaration.forEach( (arrange_pair: string[]) =>
arrange_pair.forEach( (possibleState: string) => {
if (!(this._states.has(possibleState))) {
throw new JssmError(this, `Cannot arrange state that does not exist "${possibleState}"`);
}
})
);
}
/********
*
* Internal method for fabricating states. Not meant for external use.
*
* @internal
*
*/
_new_state(state_config: JssmGenericState): StateType {
if (this._states.has(state_config.name)) {
throw new JssmError(this, `state ${JSON.stringify(state_config.name)} already exists`);
}
this._states.set(state_config.name, state_config);
return state_config.name;
}
/*********
*
* Get the current state of a machine.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const lswitch = jssm.from('on <=> off;');
* console.log( lswitch.state() ); // 'on'
*
* lswitch.transition('off');
* console.log( lswitch.state() ); // 'off'
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
state(): StateType {
return this._state;
}
/*********
*
* Get the label for a given state, if any; return `undefined` otherwise.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const lswitch = jssm.from('a -> b; state a: { label: "Foo!"; };');
* console.log( lswitch.label_for('a') ); // 'Foo!'
* console.log( lswitch.label_for('b') ); // undefined
* ```
*
* See also {@link display_text}.
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
label_for(state: StateType): string {
return this._state_labels.get(state);
}
/*********
*
* Get whatever the node should show as text.
*
* Currently, this means to get the label for a given state, if any;
* otherwise to return the node's name. However, this definition is expected
* to grow with time, and it is currently considered ill-advised to manually
* parse this text.
*
* See also {@link label_for}.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const lswitch = jssm.from('a -> b; state a: { label: "Foo!"; };');
* console.log( lswitch.display_text('a') ); // 'Foo!'
* console.log( lswitch.display_text('b') ); // 'b'
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
display_text(state: StateType): string {
return this._state_labels.get(state) ?? state;
}
/*********
*
* Get the current data of a machine.
*
* ```typescript
* import * as jssm from 'jssm';
*
* const lswitch = jssm.from('on <=> off;', {data: 1});
* console.log( lswitch.data() ); // 1
* ```
*
* @typeparam mDT The type of the machine data member; usually omitted
*
*/
data(): mDT {
return this._data;
}
// NEEDS_DOCS
/*********
*
* Get the current value of a given property name.
*
* ```typescript
*
* ```
*
* @param name The relevant property name to look up
*
* @returns The value behind the prop name. Because functional props are
* evaluated as getters, this can be anything.
*
*/
prop(name: string): any {
const bound_name = name_bind_prop_and_state(name, this.state());
if (this._state_properties.has(bound_name)) {
return this._state_properties.get(bound_name);
} else if (this._default_properties.has(name)) {
return this._default_properties.get(name);
} else {
return undefined;
}
}
// NEEDS_DOCS
/*********
*
* Get the current value of a given property name. If missing on the state
* and without a global default, throw, unlike {@link prop}, which would
* return `undefined` instead.
*
* ```typescript
*
* ```
*
* @param name The relevant property name to look up
*
* @returns The value behind the prop name. Because functional props are
* evaluated as getters, this can be anything.
*
*/
strict_prop(name: string): any {
const bound_name = name_bind_prop_and_state(name, this.state());
if (this._state_properties.has(bound_name)) {
return this._state_properties.get(bound_name);
} else if (this._default_properties.has(name)) {
return this._default_properties.get(name);
} else {
throw new JssmError(this, `Strictly requested a prop '${name}' which doesn't exist on current state '${this.state()}' and has no default`);
}
}
// NEEDS_DOCS
// COMEBACK add prop_map, sparse_props and strict_props to doc text when implemented
/*********
*
* Get the current value of every prop, as an object. If no current definition
* exists for a prop - that is, if the prop was defined without a default and
* the current state also doesn't define the prop - then that prop will be listed
* in the returned object with a value of `undefined`.
*
* ```typescript
* const traffic_light = sm`
*
* property can_go default true;
* property hesitate default true;
* property stop_first default false;
*
* Off -> Red => Green => Yellow => Red;
* [Red Yellow Green] ~> [Off FlashingRed];
* FlashingRed -> Red;
*
* state Red: { property stop_first true; property can_go false; };
* state Off: { property stop_first true; };
* state FlashingRed: { property stop_first true; };
* state Green: { property hesitate false; };
*
* `;
*
* traffic_light.state(); // Off
* traffic_light.props(); // { can_go: true, hesitate: true, stop_first: true; }
*
* traffic_light.go('Red');
* traffic_light.props(); // { can_go: false, hesitate: true, stop_first: true; }
*
* traffic_light.go('Green');
* traffic_light.props(); // { can_go: true, hesitate: false, stop_first: false; }
* ```
*
*/
props(): object {
const ret: object = {};
this.known_props().forEach(
p =>
ret[p] = this.prop(p)
);
return ret;