Options
All
  • Public
  • Public/Protected
  • All
Menu

Core finite state machine class. Holds the full graph of states and transitions, the current state, hooks, data, properties, and all runtime behavior. Typically created via the sm tagged template literal rather than constructed directly.

import { sm } from 'jssm';

const light = sm`Red 'next' => Green 'next' => Yellow 'next' => Red;`;
light.state(); // 'Red'
light.action('next'); // true
light.state(); // 'Green'

Type Parameters

  • mDT

    The machine data type — the type of the value stored in .data(). Defaults to undefined when no data is used.

Hierarchy

  • Machine

Index

Constructors

Properties

Accessors

Methods

Constructors

Properties

_actions: Map<string, Map<string, number>>
_active_state_style: Partial<JssmStateDeclaration>
_after_hooks: Map<string, HookHandler<mDT>>
_after_mapping: Map<string, [string, number]>
_any_action_hook: HookHandler<mDT>
_any_transition_hook: HookHandler<mDT>
_arrange_declaration: string[][]
_arrange_end_declaration: string[][]
_arrange_start_declaration: string[][]
_clear_timeout_source: ((h: any) => void)

Type declaration

    • (h: any): void
    • Parameters

      • h: any

      Returns void

_code_allows_override: JssmAllowsOverride
_config_allows_override: JssmAllowsOverride
_create_started: number
_created: number
_data?: mDT
_default_properties: Map<string, any>
_dot_preamble: string
_edge_map: Map<string, Map<string, number>>
_edges: JssmTransition<string, mDT>[]
_end_state_style: Partial<JssmStateDeclaration>
_end_states: Set<string>
_entry_hooks: Map<string, HookHandler<mDT>>
_everything_hook: EverythingHookHandler<mDT>
_exit_hooks: Map<string, HookHandler<mDT>>
_flow: "up" | "right" | "down" | "left"
_forced_transition_hook: HookHandler<mDT>
_fsl_version?: string
_global_action_hooks: Map<string, HookHandler<mDT>>
_graph_layout: JssmLayout
_has_after_hooks: boolean
_has_basic_hooks: boolean
_has_entry_hooks: boolean
_has_exit_hooks: boolean
_has_forced_transitions: boolean
_has_global_action_hooks: boolean
_has_hooks: boolean
_has_named_hooks: boolean
_has_post_basic_hooks: boolean
_has_post_entry_hooks: boolean
_has_post_exit_hooks: boolean
_has_post_global_action_hooks: boolean
_has_post_hooks: boolean
_has_post_named_hooks: boolean
_has_post_transition_hooks: boolean
_has_transition_hooks: boolean
_history: JssmHistory<mDT>
_history_length: number
_hooked_state_style: Partial<JssmStateDeclaration>
_hooks: Map<string, HookHandler<mDT>>
_instance_name: string
_machine_author?: string[]
_machine_comment?: string
_machine_contributor?: string[]
_machine_definition?: string
_machine_language?: string
_machine_license?: string
_machine_name?: string
_machine_version?: string
_main_transition_hook: HookHandler<mDT>
_named_hooks: Map<string, HookHandler<mDT>>
_named_transitions: Map<string, number>
_post_any_action_hook: HookHandler<mDT>
_post_any_transition_hook: HookHandler<mDT>
_post_entry_hooks: Map<string, HookHandler<mDT>>
_post_everything_hook: PostEverythingHookHandler<mDT>
_post_exit_hooks: Map<string, HookHandler<mDT>>
_post_forced_transition_hook: HookHandler<mDT>
_post_global_action_hooks: Map<string, HookHandler<mDT>>
_post_hooks: Map<string, HookHandler<mDT>>
_post_main_transition_hook: HookHandler<mDT>
_post_named_hooks: Map<string, HookHandler<mDT>>
_post_standard_transition_hook: HookHandler<mDT>
_pre_everything_hook: EverythingHookHandler<mDT>
_pre_post_everything_hook: PostEverythingHookHandler<mDT>
_property_keys: Set<string>
_raw_state_declaration?: <internal>.Object[]
_required_properties: Set<string>
_reverse_action_targets: Map<string, Map<string, number>>
_reverse_actions: Map<string, Map<string, number>>
_rng: JssmRng
_rng_seed: number
_standard_transition_hook: HookHandler<mDT>
_start_state_style: Partial<JssmStateDeclaration>
_start_states: Set<string>
_state: string
_state_declarations: Map<string, JssmStateDeclaration>
_state_labels: Map<string, string>
_state_properties: Map<string, any>
_states: Map<string, JssmGenericState>
_terminal_state_style: Partial<JssmStateDeclaration>
_themes: ("default" | "modern" | "ocean" | "bold" | "plain")[]
_time_source: (() => number)

Type declaration

    • (): number
    • Returns number

_timeout_handle: number
_timeout_source: ((Function: any, number: any) => number)

Type declaration

    • (Function: any, number: any): number
    • Parameters

      • Function: any
      • number: any

      Returns number

_timeout_target: string
_timeout_target_time: number

Accessors

  • Get the style for the active state. Does not include composition from an applied theme, or things from the underlying base stylesheet; only the modifications applied by this machine.

    const light = sm`a -> b;`;
    console.log(light.active_state_style);
    // {}

    const light = sm`a -> b; active_state: { shape: circle; };`;
    console.log(light.active_state_style);
    // { shape: 'circle' }

    Returns Partial<JssmStateDeclaration>

    The JssmStateConfig for the active state.

  • Check if a machine allows overriding state and data. Resolves the combined effect of code and config permissions — config may not be less strict than code.

    Returns JssmAllowsOverride

    The effective override permission.

  • get create_start_time(): number
  • Get the timestamp when construction began (before parsing).

    Returns number

    The start-of-construction timestamp as a number.

  • get creation_date(): Date
  • Get the creation date of this machine as a Date object.

    Returns Date

    A Date representing when the machine was created.

  • get creation_timestamp(): number
  • Get the creation timestamp (milliseconds since epoch).

    Returns number

    The timestamp as a number.

  • Get the end state style. Does not include composition from an applied theme, or things from the underlying base stylesheet; only the modifications applied by this machine.

    End states are defined in the directive end_states, and are distinct from terminal states. End states are voluntary successful endpoints for a process. Terminal states are states that cannot be exited. By example, most error states are terminal states, but not end states. Also, since some end states can be exited and are determined by hooks, such as recursive or iterative nodes, there is such a thing as an end state that is not a terminal state.

    const light = sm`a -> b;`;
    console.log(light.standard_state_style);
    // {}

    const light = sm`a -> b; end_state: { shape: circle; };`;
    console.log(light.standard_state_style);
    // { shape: 'circle' }

    Returns Partial<JssmStateDeclaration>

    The JssmStateConfig for end states.

  • get history(): [string, mDT][]
  • Get a truncated history of the recent states and data of the machine. Turned off by default; configure with .from('...', {data: 5}) by length, or set .history_length at runtime.

    History does not contain the current state. If you want that, call .history_inclusive instead.

    const foo = jssm.from(
    "a 'next' -> b 'next' -> c 'next' -> d 'next' -> e;",
    { history: 3 }
    );

    foo.action('next');
    foo.action('next');
    foo.action('next');
    foo.action('next');

    foo.history; // [ ['b',undefined], ['c',undefined], ['d',undefined] ]

    Notice that the machine's current state, e, is not in the returned list.

    Returns [string, mDT][]

  • get history_inclusive(): [string, mDT][]
  • Get a truncated history of the recent states and data of the machine, including the current state. Turned off by default; configure with .from('...', {data: 5}) by length, or set .history_length at runtime.

    History inclusive contains the current state. If you only want past states, call .history instead.

    The list returned will be one longer than the history buffer kept, as the history buffer kept gets the current state added to it to produce this list.

    const foo = jssm.from(
    "a 'next' -> b 'next' -> c 'next' -> d 'next' -> e;",
    { history: 3 }
    );

    foo.action('next');
    foo.action('next');
    foo.action('next');
    foo.action('next');

    foo.history_inclusive; // [ ['b',undefined], ['c',undefined], ['d',undefined], ['e',undefined] ]

    Notice that the machine's current state, e, is in the returned list.

    Returns [string, mDT][]

  • get history_length(): number
  • set history_length(to: number): void
  • Find out how long a history this machine is keeping. Defaults to zero. Settable directly.

    const foo = jssm.from("a -> b;");
    foo.history_length; // 0

    const bar = jssm.from("a -> b;", { history: 3 });
    foo.history_length; // 3
    foo.history_length = 5;
    foo.history_length; // 5

    Returns number

  • Find out how long a history this machine is keeping. Defaults to zero. Settable directly.

    const foo = jssm.from("a -> b;");
    foo.history_length; // 0

    const bar = jssm.from("a -> b;", { history: 3 });
    foo.history_length; // 3
    foo.history_length = 5;
    foo.history_length; // 5

    Parameters

    • to: number

    Returns void

  • Get the hooked state style. Does not include composition from an applied theme, or things from the underlying base stylesheet; only the modifications applied by this machine.

    The hooked style is only applied to nodes which have a named hook in the graph. Open hooks set through the external API aren't graphed, because that would be literally every node.

    const light = sm`a -> b;`;
    console.log(light.hooked_state_style);
    // {}

    const light = sm`a -> b; hooked_state: { shape: circle; };`;
    console.log(light.hooked_state_style);
    // { shape: 'circle' }

    Returns Partial<JssmStateDeclaration>

    The JssmStateConfig for hooked states.

  • get rng_seed(): number
  • set rng_seed(to: number): void
  • Get the current RNG seed used for probabilistic transitions.

    Returns number

    The numeric seed value.

  • Set the RNG seed. Pass undefined to reseed from the current time. Resets the internal PRNG so subsequent probabilistic operations use the new seed.

    Parameters

    • to: number

      The seed value, or undefined for time-based seeding.

    Returns void

    The numeric seed value.

  • Get the standard style for a single state. Does not include composition from an applied theme, or things from the underlying base stylesheet; only the modifications applied by this machine.

    const light = sm`a -> b;`;
    console.log(light.standard_state_style);
    // {}

    const light = sm`a -> b; state: { shape: circle; };`;
    console.log(light.standard_state_style);
    // { shape: 'circle' }

    Returns Partial<JssmStateDeclaration>

    The JssmStateConfig for standard states.

  • Get the start state style. Does not include composition from an applied theme, or things from the underlying base stylesheet; only the modifications applied by this machine.

    Start states are defined by the directive start_states, or in absentia, are the first mentioned state.

    const light = sm`a -> b;`;
    console.log(light.start_state_style);
    // {}

    const light = sm`a -> b; start_state: { shape: circle; };`;
    console.log(light.start_state_style);
    // { shape: 'circle' }

    Returns Partial<JssmStateDeclaration>

    The JssmStateConfig for start states.

  • Get the terminal state style. Does not include composition from an applied theme, or things from the underlying base stylesheet; only the modifications applied by this machine.

    Terminal state styles are automatically determined by the machine. Any state without a valid exit transition is terminal.

    const light = sm`a -> b;`;
    console.log(light.terminal_state_style);
    // {}

    const light = sm`a -> b; terminal_state: { shape: circle; };`;
    console.log(light.terminal_state_style);
    // { shape: 'circle' }

    Returns Partial<JssmStateDeclaration>

    The JssmStateConfig for terminal states.

  • get themes(): "default" | "modern" | "ocean" | "bold" | "plain" | ("default" | "modern" | "ocean" | "bold" | "plain")[]
  • set themes(to: "default" | "modern" | "ocean" | "bold" | "plain" | ("default" | "modern" | "ocean" | "bold" | "plain")[]): void
  • Get the active theme(s) for this machine. Always stored as an array internally; the union return type exists for setter compatibility.

    Returns "default" | "modern" | "ocean" | "bold" | "plain" | ("default" | "modern" | "ocean" | "bold" | "plain")[]

    The current theme or array of themes.

  • Set the active theme(s). Accepts a single theme name or an array.

    Parameters

    • to: "default" | "modern" | "ocean" | "bold" | "plain" | ("default" | "modern" | "ocean" | "bold" | "plain")[]

      A theme name or array of theme names to apply.

    Returns void

    The current theme or array of themes.

  • get uses_actions(): boolean
  • Whether any actions are defined on this machine.

    Returns boolean

    true if the machine has at least one action.

  • get uses_forced_transitions(): boolean
  • Whether any forced (~>) transitions exist in this machine.

    Returns boolean

    true if at least one forced transition is defined.

Methods

  • action(actionName: string, newData?: mDT): boolean
  • Instruct the machine to complete an action. Synonym for do.

    const light = sm`red 'next' -> green 'next' -> yellow 'next' -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;

    light.state(); // 'red'
    light.action('next'); // true
    light.state(); // 'green'

    Parameters

    • actionName: string

      The action to engage

    • Optional newData: mDT

      The data change to insert during the action

    Returns boolean

    true if the action was valid and the transition occurred, false otherwise.

  • actions(whichState?: string): string[]
  • List all actions available from this state. Please note that the order of the actions is not guaranteed.

    import { sm } from 'jssm';

    const machine = sm`
    red 'next' -> green 'next' -> yellow 'next' -> red;
    [red yellow green] 'shutdown' ~> off 'start' -> red;
    `;

    console.log( machine.state() ); // logs 'red'
    console.log( machine.actions() ); // logs ['next', 'shutdown']

    machine.action('next'); // true
    console.log( machine.state() ); // logs 'green'
    console.log( machine.actions() ); // logs ['next', 'shutdown']

    machine.action('shutdown'); // true
    console.log( machine.state() ); // logs 'off'
    console.log( machine.actions() ); // logs ['start']

    machine.action('start'); // true
    console.log( machine.state() ); // logs 'red'
    console.log( machine.actions() ); // logs ['next', 'shutdown']

    Parameters

    • whichState: string = ...

      The state whose actions to list. Defaults to the current state.

    Returns string[]

    An array of action names available from the given state.

  • all_themes(): ("default" | "modern" | "ocean" | "bold" | "plain")[]
  • List all available theme names.

    Returns ("default" | "modern" | "ocean" | "bold" | "plain")[]

    An array of theme name strings.

  • auto_set_state_timeout(): void
  • If the current state has an after timeout configured, schedule it. Called internally after each transition.

    Returns void

  • clear_state_timeout(): void
  • Cancel any pending state timeout. Safe to call when no timeout is active.

    Returns void

  • Get the full transition object for an action from the current state.

    throws

    {JssmError} If the action is not available from the current state.

    Parameters

    • action: string

      The action name.

    Returns JssmTransition<string, mDT>

    The JssmTransition object.

  • current_action_for(action: string): number
  • Get the edge index for an action from the current state.

    Parameters

    • action: string

      The action name.

    Returns number

    The edge index, or undefined if the action is not available.

  • current_state_timeout(): [string, number]
  • Get the configured after timeout for the current state, if any.

    Returns [string, number]

    A [targetState, delayMs] tuple, or undefined.

  • data(): mDT
  • Get the current data of a machine.

    import * as jssm from 'jssm';

    const lswitch = jssm.from('on <=> off;', {data: 1});
    console.log( lswitch.data() ); // 1

    Returns mDT

    A deep clone of the machine's current data value.

  • display_text(state: string): string
  • 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 label_for.

    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'

    Parameters

    • state: string

      The state to get display text for.

    Returns string

    The label if one exists, otherwise the state's name.

  • do(actionName: string, newData?: mDT): boolean
  • Instruct the machine to complete an action. Synonym for action.

    const light = sm`
    off 'start' -> red;
    red 'next' -> green 'next' -> yellow 'next' -> red;
    [red yellow green] 'shutdown' ~> off;
    `;

    light.state(); // 'off'
    light.do('start'); // true
    light.state(); // 'red'
    light.do('next'); // true
    light.state(); // 'green'
    light.do('next'); // true
    light.state(); // 'yellow'
    light.do('dance'); // !! false - no such action
    light.state(); // 'yellow'
    light.do('start'); // !! false - yellow does not have the action start
    light.state(); // 'yellow'

    Parameters

    • actionName: string

      The action to engage

    • Optional newData: mDT

      The data change to insert during the action

    Returns boolean

    true if the action was valid and the transition occurred, false otherwise.

  • dot_preamble(): string
  • Get the Graphviz DOT preamble string, injected before the graph body during visualization. Set via the FSL dot_preamble directive.

    Returns string

    The preamble string.

  • edges_between(from: string, to: string): JssmTransition<string, mDT>[]
  • Get all edges between two states (there can be multiple with different actions).

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    Returns JssmTransition<string, mDT>[]

    An array of matching JssmTransition objects.

  • flow(): "up" | "right" | "down" | "left"
  • Get the flow direction for graph layout (e.g. 'right', 'down'). Set via the FSL flow directive.

    Returns "up" | "right" | "down" | "left"

    The current flow direction.

  • force_transition(newState: string, newData?: mDT): boolean
  • Instruct the machine to complete a forced transition (which will reject if called with a normal transition call.)

    const light = sm`red -> green -> yellow -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;

    light.state(); // 'red'
    light.transition('off'); // false
    light.state(); // 'red'
    light.force_transition('off'); // true
    light.state(); // 'off'

    Parameters

    • newState: string

      The state to switch to

    • Optional newData: mDT

      The data change to insert during the transition

    Returns boolean

    true if a transition (forced or otherwise) existed and occurred, false otherwise.

  • fsl_version(): string
  • Get the FSL language version this machine was compiled under.

    Returns string

    The FSL version string.

  • get_transition_by_state_names(from: string, to: string): number
  • Look up a transition's edge index by source and target state names.

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    Returns number

    The edge index in the edges array, or undefined if no such transition exists.

  • go(newState: string, newData?: mDT): boolean
  • Instruct the machine to complete a transition. Synonym for transition.

    const light = sm`red -> green -> yellow -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;

    light.state(); // 'red'
    light.go('green'); // true
    light.state(); // 'green'

    Parameters

    • newState: string

      The state to switch to

    • Optional newData: mDT

      The data change to insert during the transition

    Returns boolean

    true if the transition was legal and occurred, false otherwise.

  • graph_layout(): string
  • Get the graph layout direction (e.g. 'LR', 'TB'). Set via the FSL graph_layout directive.

    Returns string

    The layout string, or the default if not set.

  • has_completes(): boolean
  • Check whether any state in the machine is complete.

    Returns boolean

    true if at least one state is complete.

  • has_state(whichState: string): boolean
  • Check whether the machine knows a given state.

    import * as jssm from 'jssm';

    const lswitch = jssm.from('on <=> off;');

    console.log( lswitch.has_state('off') ); // true
    console.log( lswitch.has_state('dance') ); // false

    Parameters

    • whichState: string

      The state to be checked for existence.

    Returns boolean

    true if the state exists, false otherwise.

  • has_terminals(): boolean
  • Check whether any state in the machine is terminal.

    Returns boolean

    true if at least one state has no exits.

  • has_unenterables(): boolean
  • Check whether any state in the machine is unenterable.

    Returns boolean

    true if at least one state has no incoming transitions.

  • Register a pre-transition hook on a specific edge. Fires before transitioning from from to to. If the handler returns false, the transition is blocked.

    const m = sm`a -> b -> c;`;
    m.hook('a', 'b', () => console.log('a->b'));

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    • handler: HookHandler<mDT>

      Callback invoked before the transition.

    Returns Machine<mDT>

    this for chaining.

  • hook_action(from: string, to: string, action: string, handler: HookHandler<mDT>): Machine<mDT>
  • Register a pre-transition hook on a specific action-labeled edge.

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    • action: string

      The action label that triggers this hook.

    • handler: HookHandler<mDT>

      Callback invoked before the transition.

    Returns Machine<mDT>

    this for chaining.

  • Register a hook that fires after leaving a specific state (post-exit).

    Parameters

    • from: string

      The state that was exited.

    • handler: HookHandler<mDT>

      Callback invoked after exit completes.

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook on any action-driven transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked before any action transition.

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook on any transition regardless of kind.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked before every transition.

    Returns Machine<mDT>

    this for chaining.

  • Register a hook that fires when entering a specific state.

    Parameters

    • to: string

      The state being entered.

    • handler: HookHandler<mDT>

      Callback invoked on entry.

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook that fires after all other pre-hooks on every transition. If the handler returns false, the transition is blocked. The handler receives an EverythingHookContext whose hook_name is 'everything'.

    const m = sm`a -> b -> c;`;
    m.hook_everything(({ hook_name }) => {
    console.log(`${hook_name} fired`);
    return true;
    });

    Parameters

    Returns Machine<mDT>

    this for chaining.

  • Register a hook that fires when leaving a specific state.

    Parameters

    • from: string

      The state being exited.

    • handler: HookHandler<mDT>

      Callback invoked on exit.

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook on any forced (~>) transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked before any forced transition.

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook on any edge triggered by a specific action.

    Parameters

    • action: string

      The action name to hook.

    • handler: HookHandler<mDT>

      Callback invoked before any transition with this action.

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook on any main-path (=>) transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked before any main transition.

    Returns Machine<mDT>

    this for chaining.

  • Register a post-transition hook that fires after all other post-hooks on every transition. Cannot block the transition. The handler receives an EverythingHookContext whose hook_name is 'post everything'.

    const m = sm`a -> b -> c;`;
    m.hook_post_everything(({ hook_name }) => {
    console.log(`${hook_name} fired`);
    });

    Parameters

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook that fires before all other pre-hooks on every transition. If the handler returns false, the transition is blocked. The handler receives an EverythingHookContext whose hook_name is 'pre everything'.

    const m = sm`a -> b -> c;`;
    m.hook_pre_everything(({ hook_name }) => {
    console.log(`${hook_name} fired`);
    return true;
    });

    Parameters

    Returns Machine<mDT>

    this for chaining.

  • Register a post-transition hook that fires before all other post-hooks on every transition. Cannot block the transition. The handler receives an EverythingHookContext whose hook_name is 'pre post everything'.

    const m = sm`a -> b -> c;`;
    m.hook_pre_post_everything(({ hook_name }) => {
    console.log(`${hook_name} fired`);
    });

    Parameters

    Returns Machine<mDT>

    this for chaining.

  • Register a pre-transition hook on any standard (->) transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked before any legal transition.

    Returns Machine<mDT>

    this for chaining.

  • instance_name(): string
  • Get the instance name of this machine, if one was assigned at creation.

    Returns string

    The instance name string, or undefined.

  • is_complete(): boolean
  • Check whether the current state is complete (every exit has an action).

    Returns boolean

    true if the current state is complete.

  • is_end_state(whichState: string): boolean
  • Check whether a given state is a valid start state (either because it was explicitly named as such, or because it was the first mentioned state.)

    import { sm, is_end_state } from 'jssm';

    const example = sm`a -> b;`;

    console.log( final_test.is_start_state('a') ); // false
    console.log( final_test.is_start_state('b') ); // true

    const example = sm`end_states: [a b]; a -> b;`;

    console.log( final_test.is_start_state('a') ); // true
    console.log( final_test.is_start_state('b') ); // true

    Parameters

    • whichState: string

      The name of the state to check

    Returns boolean

  • is_final(): boolean
  • Check whether the current state is final (either has no exits or is marked complete.)

    import { sm, is_final } from 'jssm';

    const final_test = sm`first -> second;`;

    console.log( final_test.is_final() ); // false
    state.transition('second');
    console.log( final_test.is_final() ); // true

    Returns boolean

  • is_start_state(whichState: string): boolean
  • Check whether a given state is a valid start state (either because it was explicitly named as such, or because it was the first mentioned state.)

    import { sm, is_start_state } from 'jssm';

    const example = sm`a -> b;`;

    console.log( final_test.is_start_state('a') ); // true
    console.log( final_test.is_start_state('b') ); // false

    const example = sm`start_states: [a b]; a -> b;`;

    console.log( final_test.is_start_state('a') ); // true
    console.log( final_test.is_start_state('b') ); // true

    Parameters

    • whichState: string

      The name of the state to check

    Returns boolean

  • is_terminal(): boolean
  • Check whether the current state is terminal (has no exits).

    Returns boolean

    true if the current state has zero exits.

  • is_unenterable(whichState: string): boolean
  • Check whether a state has no incoming transitions (unreachable after start).

    throws

    {JssmError} If the state does not exist.

    Parameters

    • whichState: string

      The state to check.

    Returns boolean

    true if the state has zero entrances.

  • known_prop(prop_name: string): boolean
  • Check whether a given string is a known property's name.

    const example = sm`property foo default 1; a->b;`;

    example.known_prop('foo'); // true
    example.known_prop('bar'); // false

    Parameters

    • prop_name: string

      The relevant property name to look up

    Returns boolean

  • known_props(): string[]
  • List all known property names. If you'd also like values, use props instead. The order of the properties is not defined, and the properties generally will not be sorted.

    const m = sm`property color default "grey"; property size default 1; a -> b;`;

    m.known_props(); // ['color', 'size']

    Returns string[]

    An array of all property name strings defined on this machine.

  • label_for(state: string): string
  • Get the label for a given state, if any; return undefined otherwise.

    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 display_text.

    Parameters

    • state: string

      The state to get the label for.

    Returns string

    The label string, or undefined if no label is set.

  • list_actions(): string[]
  • List all distinct action names defined anywhere in the machine.

    Returns string[]

    An array of action name strings.

  • Lists all edges of a machine.

    import { sm } from 'jssm';

    const lswitch = sm`on 'toggle' <=> 'toggle' off;`;

    lswitch.list_edges();
    [
    {
    from: 'on',
    to: 'off',
    kind: 'main',
    forced_only: false,
    main_path: true,
    action: 'toggle'
    },
    {
    from: 'off',
    to: 'on',
    kind: 'main',
    forced_only: false,
    main_path: true,
    action: 'toggle'
    }
    ]

    Returns JssmTransition<string, mDT>[]

    An array of all JssmTransition edge objects.

  • list_entrances(whichState?: string): string[]
  • List all entrances attached to the current state. Please note that the order of the list is not defined. This list includes both unforced and forced entrances; if this isn't desired, consider {@link list_unforced_entrances} or {@link list_forced_entrances} as appropriate.

    import { sm } from 'jssm';

    const light = sm`red 'next' -> green 'next' -> yellow 'next' -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;

    light.state(); // 'red'
    light.list_entrances(); // [ 'yellow', 'off' ]

    Parameters

    • whichState: string = ...

      The state whose entrances to have listed

    Returns string[]

  • list_exit_actions(whichState?: string): string[]
  • List all action names available as exits from a given state.

    throws

    {JssmError} If the state does not exist.

    Parameters

    • whichState: string = ...

      The state to inspect. Defaults to the current state.

    Returns string[]

    An array of action name strings.

  • list_exits(whichState?: string): string[]
  • List all exits attached to the current state. Please note that the order of the list is not defined. This list includes both unforced and forced exits; if this isn't desired, consider {@link list_unforced_exits} or {@link list_forced_exits} as appropriate.

    import { sm } from 'jssm';

    const light = sm`red 'next' -> green 'next' -> yellow 'next' -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;

    light.state(); // 'red'
    light.list_exits(); // [ 'green', 'off' ]

    Parameters

    • whichState: string = ...

      The state whose exits to have listed

    Returns string[]

  • list_named_transitions(): Map<string, number>
  • Get the map of named transitions (transitions with explicit names).

    Returns Map<string, number>

    A Map from transition name to edge index.

  • list_states_having_action(whichState: string): string[]
  • List all states that have a specific action attached. Please note that the order of the states is not guaranteed.

    import { sm } from 'jssm';

    const machine = sm`
    red 'next' -> green 'next' -> yellow 'next' -> red;
    [red yellow green] 'shutdown' ~> off 'start' -> red;
    `;

    console.log( machine.list_states_having_action('next') ); // ['red', 'green', 'yellow']
    console.log( machine.list_states_having_action('start') ); // ['off']

    Parameters

    • whichState: string

      The action to be checked for associated states

    Returns string[]

  • List all transitions attached to the current state, sorted by entrance and exit. The order of each sublist is not defined. A node could appear in both lists.

    import { sm } from 'jssm';

    const light = sm`red 'next' -> green 'next' -> yellow 'next' -> red; [red yellow green] 'shutdown' ~> off 'start' -> red;`;

    light.state(); // 'red'
    light.list_transitions(); // { entrances: [ 'yellow', 'off' ], exits: [ 'green', 'off' ] }

    Parameters

    • whichState: string = ...

      The state whose transitions to have listed

    Returns JssmTransitionList

  • lookup_transition_for(from: string, to: string): JssmTransition<string, mDT>
  • Look up the full transition object for a given source→target pair.

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    Returns JssmTransition<string, mDT>

    The JssmTransition object, or undefined if none exists.

  • machine_author(): string[]
  • Get the machine's author list. Set via the FSL machine_author directive.

    Returns string[]

    An array of author name strings.

  • machine_comment(): string
  • Get the machine's comment string. Set via the FSL machine_comment directive.

    Returns string

    The comment string.

  • machine_contributor(): string[]
  • Get the machine's contributor list. Set via the FSL machine_contributor directive.

    Returns string[]

    An array of contributor name strings.

  • machine_definition(): string
  • Get the machine's definition string. Set via the FSL machine_definition directive.

    Returns string

    The definition string.

  • machine_language(): string
  • Get the machine's language (ISO 639-1). Set via the FSL machine_language directive.

    Returns string

    The language code string.

  • machine_license(): string
  • Get the machine's license string. Set via the FSL machine_license directive.

    Returns string

    The license string.

  • machine_name(): string
  • Get the machine's name. Set via the FSL machine_name directive.

    Returns string

    The machine name string.

  • machine_version(): string
  • Get the machine's version string. Set via the FSL machine_version directive.

    Returns string

    The version string.

  • override(newState: string, newData?: mDT): void
  • Replace the current state and data with no regard to the graph.

    import { sm } from 'jssm';

    const machine = sm`a -> b -> c;`;
    console.log( machine.state() ); // 'a'

    machine.go('b');
    machine.go('c');
    console.log( machine.state() ); // 'c'

    machine.override('a');
    console.log( machine.state() ); // 'a'

    Parameters

    • newState: string
    • Optional newData: mDT

    Returns void

  • Post-transition hook on a specific edge. Fires after the transition from from to to has completed. Cannot block the transition.

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    • handler: HookHandler<mDT>

      Callback invoked after the transition.

    Returns Machine<mDT>

    this for chaining.

  • post_hook_action(from: string, to: string, action: string, handler: HookHandler<mDT>): Machine<mDT>
  • Post-transition hook on a specific action-labeled edge.

    Parameters

    • from: string

      Source state name.

    • to: string

      Target state name.

    • action: string

      The action label.

    • handler: HookHandler<mDT>

      Callback invoked after the transition.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook on any action-driven transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked after any action transition.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook on any transition regardless of kind.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked after every transition.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook that fires after entering a specific state.

    Parameters

    • to: string

      The state that was entered.

    • handler: HookHandler<mDT>

      Callback invoked after entry.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook that fires after leaving a specific state.

    Parameters

    • from: string

      The state that was exited.

    • handler: HookHandler<mDT>

      Callback invoked after exit.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook on any forced (~>) transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked after any forced transition.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook on any edge triggered by a specific action.

    Parameters

    • action: string

      The action name.

    • handler: HookHandler<mDT>

      Callback invoked after any transition with this action.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook on any main-path (=>) transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked after any main transition.

    Returns Machine<mDT>

    this for chaining.

  • Post-transition hook on any standard (->) transition.

    Parameters

    • handler: HookHandler<mDT>

      Callback invoked after any legal transition.

    Returns Machine<mDT>

    this for chaining.

  • probabilistic_histo_walk(n: number): Map<string, number>
  • Take n probabilistic steps and return a histograph of how many times each state was visited.

    Parameters

    • n: number

      Number of steps to walk.

    Returns Map<string, number>

    A Map from state name to visit count.

  • probabilistic_transition(): boolean
  • Take a single random transition from the current state, weighted by edge probabilities.

    Returns boolean

    true if a transition was taken, false otherwise.

  • probabilistic_walk(n: number): string[]
  • Take n consecutive probabilistic transitions and return the sequence of states visited (before each transition).

    Parameters

    • n: number

      Number of steps to walk.

    Returns string[]

    An array of state names visited during the walk.

  • probable_action_exits(whichState?: string): any[]
  • List all action exits from a state with their probabilities.

    throws

    {JssmError} If the state does not exist.

    Parameters

    • whichState: string = ...

      The state to inspect. Defaults to the current state.

    Returns any[]

    An array of { action, probability } objects.

  • Get the transitions available from a state, filtered to those with probability data. Used by the probabilistic walk system.

    throws

    {JssmError} If the state does not exist.

    Parameters

    • whichState: string

      The state to inspect.

    Returns JssmTransition<string, mDT>[]

    An array of JssmTransition edges exiting the state.

  • prop(name: string): any
  • Get the current value of a given property name. Checks the current state's properties first, then falls back to the global default. Returns undefined if neither exists. For a throwing variant, see strict_prop.

    const m = sm`property color default "grey"; a -> b;
    state b: { property color "blue"; };`;

    m.prop('color'); // 'grey' (default, because state is 'a')
    m.go('b');
    m.prop('color'); // 'blue' (state 'b' overrides the default)
    m.prop('size'); // undefined (no such property)

    Parameters

    • name: string

      The relevant property name to look up.

    Returns any

    The value behind the prop name, or undefined if not defined.

  • props(): object
  • 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.

    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; }

    Returns object

    An object mapping every known property name to its current value (or undefined if the property has no default and the current state doesn't define it).

  • Serialize the current machine, including all defining state but not the machine string, to a structure. This means you will need the machine string to recreate (to not waste repeated space;) if you want the machine string embedded, call {@link serialize_with_string} instead.

    Parameters

    • Optional comment: string

      An optional comment string to embed in the serialized output for identification or debugging.

    Returns JssmSerialization<mDT>

    A JssmSerialization object containing the machine's current state, data, and timestamp.

  • Low-level hook registration. Installs a handler described by a HookDescription into the appropriate internal map. Prefer the convenience wrappers (hook, hook_entry, etc.) over calling this directly.

    Parameters

    • HookDesc: HookDescription<mDT>

      A hook descriptor specifying kind, states, and handler.

    Returns void

  • set_state_timeout(next_state: string, after_time: number): void
  • Schedule an automatic transition to next_state after after_time milliseconds. Only one timeout may be active at a time.

    throws

    {JssmError} If a timeout is already pending.

    Parameters

    • next_state: string

      The state to transition to when the timer fires.

    • after_time: number

      Delay in milliseconds.

    Returns void

  • Convenience method to create a new machine from a tagged template literal. Equivalent to calling the top-level sm function.

    Parameters

    • template_strings: TemplateStringsArray

      The template string array.

    • Rest ...remainder: any[]

      Interpolated values.

    Returns Machine<mDT>

    A new Machine instance.

  • state(): string
  • Get the current state of a machine.

    import * as jssm from 'jssm';

    const lswitch = jssm.from('on <=> off;');
    console.log( lswitch.state() ); // 'on'

    lswitch.transition('off');
    console.log( lswitch.state() ); // 'off'

    Returns string

    The current state name.

  • state_is_complete(whichState: string): boolean
  • Check whether a specific state is complete (every exit has an action).

    throws

    {JssmError} If the state does not exist.

    Parameters

    • whichState: string

      The state to check.

    Returns boolean

    true if the state is complete.

  • state_is_final(whichState: string): boolean
  • Check whether a given state is final (either has no exits or is marked complete.)

    import { sm, state_is_final } from 'jssm';

    const final_test = sm`first -> second;`;

    console.log( final_test.state_is_final('first') ); // false
    console.log( final_test.state_is_final('second') ); // true

    Parameters

    • whichState: string

      The name of the state to check for finality

    Returns boolean

  • state_is_terminal(whichState: string): boolean
  • Check whether a specific state is terminal (has no exits).

    throws

    {JssmError} If the state does not exist.

    Parameters

    • whichState: string

      The state to check.

    Returns boolean

    true if the state has zero exits.

  • state_timeout_for(which_state: string): [string, number]
  • Get the configured after timeout for a given state, if any.

    Parameters

    • which_state: string

      The state to look up.

    Returns [string, number]

    A [targetState, delayMs] tuple, or undefined if no timeout is configured for that state.

  • states(): string[]
  • List all the states known by the machine. Please note that the order of these states is not guaranteed.

    import * as jssm from 'jssm';

    const lswitch = jssm.from('on <=> off;');
    console.log( lswitch.states() ); // ['on', 'off']

    Returns string[]

    An array of all state names in the machine.

  • strict_prop(name: string): any
  • Get the current value of a given property name. If missing on the state and without a global default, throws a JssmError, unlike prop, which would return undefined instead.

    const m = sm`property color default "grey"; a -> b;`;

    m.strict_prop('color'); // 'grey'
    m.strict_prop('size'); // throws JssmError
    throws

    {JssmError} If the property is not defined on the current state and has no default.

    Parameters

    • name: string

      The relevant property name to look up.

    Returns any

    The value behind the prop name.

  • Gets the composite style for a specific node by individually imposing the style layers on a given object, after determining which layers are appropriate.

    The order of composition is base, then theme, then user content. Each item in the stack will be composited independently. First, the base state style, then the theme state style, then the user state style.

    After the three state styles, we'll composite the hooked styles; then the terminal styles; then the start styles; then the end styles; finally, the active styles. Remember, last wins.

    The base state style must exist. All other styles are optional.

    Parameters

    • state: string

      The state to compute the composite style for.

    Returns Partial<JssmStateDeclaration>

    The fully composited JssmStateConfig for the given state.

  • transition(newState: string, newData?: mDT): boolean
  • Instruct the machine to complete a transition. Synonym for go.

    const light = sm`
    off 'start' -> red;
    red 'next' -> green 'next' -> yellow 'next' -> red;
    [red yellow green] 'shutdown' ~> off;
    `;

    light.state(); // 'off'
    light.go('red'); // true
    light.state(); // 'red'
    light.go('green'); // true
    light.state(); // 'green'
    light.go('blue'); // !! false - no such state
    light.state(); // 'green'
    light.go('red'); // !! false - green may not go directly to red, only to yellow
    light.state(); // 'green'

    Parameters

    • newState: string

      The state to switch to

    • Optional newData: mDT

      The data change to insert during the transition

    Returns boolean

    true if the transition was legal and occurred, false otherwise.

  • transition_impl(newStateOrAction: string, newData: mDT, wasForced: boolean, wasAction: boolean): boolean
  • Shared transition core used by transition, force_transition, and action. Runs validation, fires the full hook pipeline (pre- everything, any-action, after, any-transition, exit, named, basic, edge-type, entry, everything), commits the new state if nothing rejected, and returns whether the transition succeeded.

    Not meant for external use. Call one of the public wrappers instead:

    • transition for an ordinary legal transition
    • force_transition to bypass the legality check
    • action to dispatch by action name rather than target state
    remarks

    Known sharp edges, carried over from the original // TODO comments:

    • The forced-ness behavior needs to be cleaned up a lot here.
    • The callbacks are not fully correct across the forced / action / plain cases and should be revisited.
    • When multiple edges exist between two states with different kind values, only the first edge's kind is used to pick the edge-type hook.
    internal

    Parameters

    • newStateOrAction: string

      The target state name (for a plain or forced transition) or the action name (when wasAction is true).

    • newData: mDT

      Optional replacement machine data to install alongside the transition. Hooks may further override this via complex results.

    • wasForced: boolean

      true if the caller invoked force_transition, in which case legality is checked against valid_force_transition rather than valid_transition.

    • wasAction: boolean

      true if the caller invoked action, in which case newStateOrAction is an action name and the target state is looked up via the current action edge.

    Returns boolean

    true if the transition was valid and every hook passed; false if the transition was invalid or any hook rejected.

  • valid_action(action: string, _newData?: mDT): boolean
  • Check whether an action is available from the current state.

    Parameters

    • action: string

      The action name to check.

    • Optional _newData: mDT

      Reserved for future data validation.

    Returns boolean

    true if the action can be taken.

  • valid_force_transition(newState: string, _newData?: mDT): boolean
  • Check whether a forced transition to a given state exists from the current state.

    Parameters

    • newState: string

      The target state.

    • Optional _newData: mDT

      Reserved for future data validation.

    Returns boolean

    true if a forced (or any) transition exists.

  • valid_transition(newState: string, _newData?: mDT): boolean
  • Check whether a transition to a given state is legal (non-forced) from the current state.

    Parameters

    • newState: string

      The target state.

    • Optional _newData: mDT

      Reserved for future data validation.

    Returns boolean

    true if the transition is legal.

Generated using TypeDoc