Norvell's Public Machinations

    engineering

    1.0.1 • Public • Published

    engineering Module Version MIT License Build Status Coverage Status

    Engineer lightweight finite state machines.

    Available in both Node.js and web browsers using Browserify.

    Synopsis

    Installation is easy via npm:

    npm install [--save] engineering
    

    Defining a state machine is very straightforward:

    var engineer = require('engineering');
     
    function Client() {
      // Define state machine for WebSocket state
      this.connection = engineer({
        states: {
          // connected -> disconnecting
          connected: ['disconnecting'],
     
          // connecting -> connected, disconnected
          connecting: ['connected', 'disconnected'],
     
          // disconnecting -> disconnected
          disconnecting: ['disconnected'],
     
          // disconnected -> connecting
          disconnected: ['connecting']
        },
     
        // Default state is disconnected
        default: 'disconnected'
      });
    }

    React to state machine transitions easily:

    function Client() {
      // ...same as above
     
      // When connected, relay WebSocket's "message" notification
      this.connection.on('connected', function (ws) {
        var emit = this.emit.bind(this, 'message');
     
        ws.on('message', function (message) {
          emit(message);
        });
      }, this);
    }

    Effortlessly drive action based on the machine's state:

    Client.prototype.connect = function (url) {
      var self = this;
      var connection = self.connection;
     
      return new Promise(function (resolve, reject) {
        connection
          // Connected, so resolve immediately
          .at('connected', resolve)
          // Connecting, so wait until connected or disconnected
          .at('connecting', function () {
            connection
              .when('connected', resolve)
              .otherwise(reject);
          })
          // Disconnecting, so wait until disconnected and attempt to connect again
          .at('disconnecting', function () {
            connection.once('disconnected', function () {
              self.connect(url).then(resolve, reject);
            });
          })
          // Disconnected, so attempt WebSocket connection
          .otherwise(function () {
            connection.to('connecting');
     
            var onError = function (err) {
              connection.to('disconnected');
              reject(err);
            };
     
            var ws = new WebSocket(url);
            ws.on('error', onError);
            ws.on('open', function () {
              ws.removeListener('error', onError);
              connection.to('connected', ws);
              resolve(ws);
            });
          });
      });
    };

    Know the machine's state using an expressive and easy-to-understand interface:

    Client.prototype.send = function (message) {
      var connection = this.connection;
     
      connection
        .at('connected', function (ws) {
          ws.send(message);
        })
        .otherwise(function () {
          throw new Error('Client not connected');
        });
    };

    View the accompanying examples directory for concrete examples.

    API

    Creating a state machine

    engineer(options) → Machine

    Creates a new Machine machine with given options.

    The following options can be specified:

    • statesObject: A map of state transitions. The keys are states, and the value is an array of transitions. Required.
    • defaultString: The default state. Required.

    Querying present machine state

    machine.is(state[, fn[, context]]) → Boolean

    Indicates whether state machine is currently at state. If at state and fn was passed, the callback will be invoked immediately. state may be an individual state or an array of states.

    Returns true if at state; false otherwise.

    machine.at(state, fn[, context]) → Query

    Begins a chainable query of the machine's current state, queuing fn for invocation if at state.

    query.at(state, fn[, context]) → Query

    Identical to machine.at(). Used to query additional states.

    query.otherwise(fn[, context]) → Any

    Performs check of machine's state. If machine is at a state with a previous query, the appropriate callback is invoked; otherwise, fn is invoked.

    Returns invoked callback's return value.

    Reacting to state transition

    machine.on(state, fn[, context]) → Machine

    If state machine is at state, invokes fn immediately with context. Additionally, every time the state machine transitions to state, fn will be invoked with context.

    machine.once(state, fn) → Machine

    If state machine is at state, invokes fn immediately with context; otherwise, invokes fn with context when machine transitions to state.

    machine.when(state, fn[, context]) → Watch

    Similar to .once(); however, if state machine is not at state and transitions to state next, fn is invoked.

    watch.when(state, fn[, context]) → Watch

    Identical to machine.watch(). Used to watch additional state transitions.

    watch.otherwise(fn[, context]) → Machine

    If state machine transitions to any state that does not have a watch, fn is invoked with context.

    Transitioning machine state

    machine.to(state[, ...args])

    Transitions state machine to state. Any passed args will be applied to any callbacks passed to .is(), .at(), .on(), .once(), and .when().

    License

    MIT

    Install

    npm i engineering

    DownloadsWeekly Downloads

    2

    Version

    1.0.1

    License

    MIT

    Last publish

    Collaborators

    • avatar