Class StateBackedClient

A client for the StateBacked.dev API.

State Backed allows you to launch instances of XState state machines in the cloud with a simple API.

This client is suitable for use client-side or server-side.

See the full State Backed documentation at https://docs.statebacked.dev.

To use this client, first, download the smply CLI with npm install --global smply. Get your organization ID with smply orgs list. Use anonymous authentication with just your org ID or configure token exchange to authenticate users using your existing identity provider.

Then, create a State Backed client with new StateBackedClient(config);

Hierarchy

  • StateBackedClient

Constructors

Properties

billing: {
    get: ((signal?) => Promise<{
        url: string;
    }>);
} = ...

Type declaration

  • get: ((signal?) => Promise<{
        url: string;
    }>)
      • (signal?): Promise<{
            url: string;
        }>
      • Parameters

        • Optional signal: AbortSignal

        Returns Promise<{
            url: string;
        }>

identityProviders: {
    delete: ((req, signal?) => Promise<void>);
    list: ((opts?, signal?) => Promise<{
        cursor?: string;
        idps: {
            algs: ("HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES384" | "ES512" | "EdDSA")[];
            aud?: string;
            iss?: string;
            jwksUrl?: string;
            mapping: {
                [key: string]: unknown;
            };
        }[];
    }>);
    upsert: ((req, signal?) => Promise<void>);
} = ...

Administrative APIs to manage identity providers.

An identity provider is a configuration for validating and extracting claims from JWTs created by a third-party identity provider (e.g. Auth0, Supabase, etc.).

Those claims can then be used by token providers to generate State Backed tokens.

This token exchange allows fully-secure, end-to-end authorized requests directly from client code without needing any server and without having to change identity providers.

Type declaration

  • delete: ((req, signal?) => Promise<void>)
      • (req, signal?): Promise<void>
      • Delete an identity provider configuration

        Parameters

        • req: {
              aud?: string;
              iss?: string;
          }

          identity provider configuration. At least one of aud and iss must be provided.

          • Optional aud?: string

            Description

            Audience for the identity provider (at least one of aud or iss must be provided).

          • Optional iss?: string

            Description

            Issuer for the identity provider (at least one of aud or iss must be provided).

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<void>

  • list: ((opts?, signal?) => Promise<{
        cursor?: string;
        idps: {
            algs: ("HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES384" | "ES512" | "EdDSA")[];
            aud?: string;
            iss?: string;
            jwksUrl?: string;
            mapping: {
                [key: string]: unknown;
            };
        }[];
    }>)
      • (opts?, signal?): Promise<{
            cursor?: string;
            idps: {
                algs: ("HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES384" | "ES512" | "EdDSA")[];
                aud?: string;
                iss?: string;
                jwksUrl?: string;
                mapping: {
                    [key: string]: unknown;
                };
            }[];
        }>
      • Retrieve a page of identity providers.

        Parameters

        • Optional opts: ListOptions

          options for the list operation

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            idps: {
                algs: ("HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES384" | "ES512" | "EdDSA")[];
                aud?: string;
                iss?: string;
                jwksUrl?: string;
                mapping: {
                    [key: string]: unknown;
                };
            }[];
        }>

        • a page of identity providers
  • upsert: ((req, signal?) => Promise<void>)
      • (req, signal?): Promise<void>
      • Create or update an identity provider configuration.

        Token exchange involves exchanging an identity provider-signed token for a State Backed-signed token. By adding an identity provider configuration to State Backed, you are instructing State Backed to trust any valid token from that identity provider when evaluating whether to allow a token exchange. You are also extracting the claims from that token that you want to make available to your token providers to include in the State Backed token.

        For example, if you are using Auth0 as your identity provider, you can configure State Backed to trust your Auth0 tokens by calling:

        client.identityProviders.upsert({
        aud: "https://<your-auth0-domain>.us.auth0.com/api/v2/",
        iss: "https://<your-auth0-domain>.us.auth0.com/",
        jwksUrl: "https://<your-auth0-domain>.us.auth0.com/.well-known/jwks.json",
        algs: ["RS256"],
        mapping: {
        "sub.$": "$.sub",
        "email.$": "$.email",
        "provider": "auth0",
        },
        })

        State Backed uses the audience (aud) and issuer (iss) claims in any tokens provided for exchange to identify the identity provider to use for verification.

        In this example, token providers would be have access to sub, email, and provider claims that they could include in the resultant State Backed token.

        Upserts may change algorithms, mappings, keys or jwksUrls.

        This endpoint requires admin access.

        Parameters

        • req: {
              algs: ("HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES384" | "ES512" | "EdDSA")[];
              aud?: string;
              iss?: string;
              jwksUrl?: string;
              key?: string;
              mapping: {
                  [key: string]: unknown;
              };
          }

          identity provider configuration. At least one of aud and iss must be provided and at least one of keys and jwksUrl must be provided.

          • algs: ("HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES384" | "ES512" | "EdDSA")[]

            Description

            Allowed signing algorithms

          • Optional aud?: string

            Description

            The audience claim that identifies tokens from this identity provider (one of aud or iss must be provided)

          • Optional iss?: string

            Description

            The issuer claim that identifies tokens from this identity provider (one of aud or iss must be provided)

          • Optional jwksUrl?: string

            Description

            Absolute URL at which to find a JWKS key set to verify token signatures (one of key or jwksUrl must be provided)

          • Optional key?: string

            Description

            base64url-encoded key to use to verify token signatures (one of key or jwksUrl must be provided)

          • mapping: {
                [key: string]: unknown;
            }

            Description

            A mapping object that extracts claims from the identity provider tokens that token providers can reference when creating the claims for State Backed tokens.

            The values of properties that end in ".$" are treated as JSONPath references into the claim set of the provided token.

            So a mapping of { "sub.$": "$.sub" } with identity provider claims of { "sub": "user-123" } will result in { "sub": "user-123" } as the input claims into any token provider.

            • [key: string]: unknown
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<void>

inProgressTokenPromise: Promise<string>
keys: {
    create: ((req, signal?) => Promise<{
        id: string;
        key: string;
    }>);
    delete: ((keyId, signal?) => Promise<void>);
    list: ((opts?, signal?) => Promise<{
        cursor?: string;
        keys: {
            createdAt: string;
            id: string;
            name: string;
            scopes: ("events.write" | "events.read" | "state.read" | "instances.read" | "instances.write" | "instances.admin" | "machines.read" | "machines.write" | "machines.admin" | "machine-versions.read" | "machine-versions.write" | "analytics.read" | "org.read" | "org.write" | "org.keys.write" | "org-members.write" | "logs.read" | "tokens.admin")[];
        }[];
    }>);
} = ...

Type declaration

  • create: ((req, signal?) => Promise<{
        id: string;
        key: string;
    }>)
      • (req, signal?): Promise<{
            id: string;
            key: string;
        }>
      • Parameters

        • req: {
              name: string;
              scopes?: ("events.write" | "events.read" | "state.read" | "instances.read" | "instances.write" | "instances.admin" | "machines.read" | "machines.write" | "machines.admin" | "machine-versions.read" | "machine-versions.write" | "analytics.read" | "org.read" | "org.write" | "org.keys.write" | "org-members.write" | "logs.read" | "tokens.admin")[];
              use?: "production" | "ci";
          }
          • name: string
          • Optional scopes?: ("events.write" | "events.read" | "state.read" | "instances.read" | "instances.write" | "instances.admin" | "machines.read" | "machines.write" | "machines.admin" | "machine-versions.read" | "machine-versions.write" | "analytics.read" | "org.read" | "org.write" | "org.keys.write" | "org-members.write" | "logs.read" | "tokens.admin")[]

            Description

            The scopes that any request with a token signed by this key will have access to. You must either pass scopes or use.

          • Optional use?: "production" | "ci"

            Description

            The intended use for this key. This is a shorthand way to set a reasonable set of scopes. You must either pass scopes or use.

        • Optional signal: AbortSignal

        Returns Promise<{
            id: string;
            key: string;
        }>

  • delete: ((keyId, signal?) => Promise<void>)
      • (keyId, signal?): Promise<void>
      • Parameters

        • keyId: string
        • Optional signal: AbortSignal

        Returns Promise<void>

  • list: ((opts?, signal?) => Promise<{
        cursor?: string;
        keys: {
            createdAt: string;
            id: string;
            name: string;
            scopes: ("events.write" | "events.read" | "state.read" | "instances.read" | "instances.write" | "instances.admin" | "machines.read" | "machines.write" | "machines.admin" | "machine-versions.read" | "machine-versions.write" | "analytics.read" | "org.read" | "org.write" | "org.keys.write" | "org-members.write" | "logs.read" | "tokens.admin")[];
        }[];
    }>)
      • (opts?, signal?): Promise<{
            cursor?: string;
            keys: {
                createdAt: string;
                id: string;
                name: string;
                scopes: ("events.write" | "events.read" | "state.read" | "instances.read" | "instances.write" | "instances.admin" | "machines.read" | "machines.write" | "machines.admin" | "machine-versions.read" | "machine-versions.write" | "analytics.read" | "org.read" | "org.write" | "org.keys.write" | "org-members.write" | "logs.read" | "tokens.admin")[];
            }[];
        }>
      • Parameters

        • Optional opts: ListOptions
        • Optional signal: AbortSignal

        Returns Promise<{
            cursor?: string;
            keys: {
                createdAt: string;
                id: string;
                name: string;
                scopes: ("events.write" | "events.read" | "state.read" | "instances.read" | "instances.write" | "instances.admin" | "machines.read" | "machines.write" | "machines.admin" | "machine-versions.read" | "machine-versions.write" | "analytics.read" | "org.read" | "org.write" | "org.keys.write" | "org-members.write" | "logs.read" | "tokens.admin")[];
            }[];
        }>

latestToken: string
logs: {
    retrieve: ((from, filter?, signal?) => Promise<{
        logs: {
            instanceName: string;
            log: string;
            machineName: string;
            machineVersionId: string;
            orgId: string;
            outputType: "stdout" | "stderr";
            timestamp: string;
        }[];
        maxTimestamp: string;
    }>);
    watch: ((from, filter?, signal?) => AsyncIterable<{
        instanceName: string;
        log: string;
        machineName: string;
        machineVersionId: string;
        orgId: string;
        outputType: "stdout" | "stderr";
        timestamp: string;
    }>);
} = ...

Logs API.

State Backed collects logs from transitions, actions, services, authorizers, and migrations. Logs are currently available approximately 1 minute after they are generated and log retention depends on your plan.

Type declaration

  • retrieve: ((from, filter?, signal?) => Promise<{
        logs: {
            instanceName: string;
            log: string;
            machineName: string;
            machineVersionId: string;
            orgId: string;
            outputType: "stdout" | "stderr";
            timestamp: string;
        }[];
        maxTimestamp: string;
    }>)
      • (from, filter?, signal?): Promise<{
            logs: {
                instanceName: string;
                log: string;
                machineName: string;
                machineVersionId: string;
                orgId: string;
                outputType: "stdout" | "stderr";
                timestamp: string;
            }[];
            maxTimestamp: string;
        }>
      • Retrieve a batch of up to 100 log entries. Each log entry may have multiple log lines in its log field.

        You may receive fewer than 100 log entries (or 0 entries) due to partitioning.

        Along with the log entries, you will receive a maxTimestamp field indicating the timestamp to use as your from parameter in your next call if you want to retrieve the next batch of logs.

        If the returned maxTimestamp matches your from parameter, you have retrieved all of the logs that are currently available.

        You should then wait 30s and try again if you want to retrieve more logs.

        Parameters

        • from: Date

          the timestamp to start retrieving logs from

        • Optional filter: {
              instanceName?: string;
              machineName?: string;
              machineVersionId?: string;
              to?: Date;
          }

          optional filter parameters to filter the logs returned

          • Optional instanceName?: string
          • Optional machineName?: string
          • Optional machineVersionId?: string
          • Optional to?: Date
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            logs: {
                instanceName: string;
                log: string;
                machineName: string;
                machineVersionId: string;
                orgId: string;
                outputType: "stdout" | "stderr";
                timestamp: string;
            }[];
            maxTimestamp: string;
        }>

        logs and maxTimestamp

  • watch: ((from, filter?, signal?) => AsyncIterable<{
        instanceName: string;
        log: string;
        machineName: string;
        machineVersionId: string;
        orgId: string;
        outputType: "stdout" | "stderr";
        timestamp: string;
    }>)
      • (from, filter?, signal?): AsyncIterable<{
            instanceName: string;
            log: string;
            machineName: string;
            machineVersionId: string;
            orgId: string;
            outputType: "stdout" | "stderr";
            timestamp: string;
        }>
      • Returns an async iterator that yields log entries as they are generated, polling in a sensible way for new entries.

        Parameters

        • from: Date

          the timestamp to start retrieving logs from

        • Optional filter: {
              instanceName?: string;
              machineName?: string;
              machineVersionId?: string;
              to?: Date;
          }

          optional filter parameters to filter the logs returned

          • Optional instanceName?: string
          • Optional machineName?: string
          • Optional machineVersionId?: string
          • Optional to?: Date
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the iteration. If aborted, the iterator will end and no error will be thrown.

        Returns AsyncIterable<{
            instanceName: string;
            log: string;
            machineName: string;
            machineVersionId: string;
            orgId: string;
            outputType: "stdout" | "stderr";
            timestamp: string;
        }>

        An AsyncIterator that yields log entries as they are generated.

        See

        retrieve for more information on the parameters.

        If no filter.to is provided, the iterator will never end because it will continue to look for new logs.

        Example:

        const logs = client.logs.watch(new Date());
        for await (const log of logs) {
        // do something with log
        }
machineInstances: {
    admin: {
        get: ((machineName, machineInstanceName, signal?) => Promise<{
            context: {
                [key: string]: unknown;
            };
            createdAt: string;
            desiredMachineVersion?: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            done: boolean;
            machineVersion: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            state: string | {
                [key: string]: components["schemas"]["StateValue"] | undefined;
            };
            status: "paused" | "running";
            tags: string[];
        }>);
        updateDesiredVersion: ((machineName, instanceName, req, signal?) => Promise<void>);
    };
    create: ((machineName, req, signal?) => Promise<EnhancedState>);
    dangerously: {
        delete: ((machineName, machineInstanceName, req, signal?) => Promise<void>);
        setStatus: ((machineName, machineInstanceName, req, signal?) => Promise<void>);
    };
    get: ((machineName, machineInstanceName, signal?) => Promise<EnhancedState>);
    getActor: (<TEvent, TState, TContext>(machineName, machineInstanceName, signal?) => Promise<Actor<TEvent, TState, TContext>>);
    getOrCreate: ((machineName, instanceName, creationParams, signal?) => Promise<EnhancedState>);
    getOrCreateActor: (<TEvent, TState, TContext>(machineName, machineInstanceName, creationParams, signal?) => Promise<Actor<TEvent, TState, TContext>>);
    list: ((machineName, opts?, signal?) => Promise<{
        cursor?: string;
        instances: {
            createdAt: string;
            machineVersion: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            slug: string;
            status: "paused" | "running";
        }[];
    }>);
    listTransitions: ((machineName, machineInstanceName, opts?, signal?) => Promise<{
        cursor?: string;
        transitions: {
            createdAt: string;
            event: string | {
                type: string;
                [key: string]: unknown;
            };
            state: string | {
                [key: string]: components["schemas"]["StateValue"] | undefined;
            };
        }[];
    }>);
    query: ((machineName, indexName, req?, signal?) => Promise<{
        cursor?: string;
        instances: {
            indexValue: string;
            slug: string;
        }[];
    }>);
    sendEvent: ((machineName, instanceName, req, signal?) => Promise<EnhancedState>);
    subscribe: ((machineName, machineInstanceName, onStateUpdate, onError?, signal?) => Unsubscribe);
} = ...

Machine instances API.

Think of a machine definition like a class and machine instances as, well, instances of that class.

An instance of a machine has persistent state that preserves the state of the XState machine, including any context, history, etc.

You can create as many instances of each machine as you'd like. Each instance is independent. It has its own name, its own state, makes its own authorization decisions, receives its own events, and handles its own delayed events.

Type declaration

  • admin: {
        get: ((machineName, machineInstanceName, signal?) => Promise<{
            context: {
                [key: string]: unknown;
            };
            createdAt: string;
            desiredMachineVersion?: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            done: boolean;
            machineVersion: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            state: string | {
                [key: string]: components["schemas"]["StateValue"] | undefined;
            };
            status: "paused" | "running";
            tags: string[];
        }>);
        updateDesiredVersion: ((machineName, instanceName, req, signal?) => Promise<void>);
    }
    • get: ((machineName, machineInstanceName, signal?) => Promise<{
          context: {
              [key: string]: unknown;
          };
          createdAt: string;
          desiredMachineVersion?: {
              clientInfo: string;
              createdAt: string;
              id: string;
          };
          done: boolean;
          machineVersion: {
              clientInfo: string;
              createdAt: string;
              id: string;
          };
          state: string | {
              [key: string]: components["schemas"]["StateValue"] | undefined;
          };
          status: "paused" | "running";
          tags: string[];
      }>)
        • (machineName, machineInstanceName, signal?): Promise<{
              context: {
                  [key: string]: unknown;
              };
              createdAt: string;
              desiredMachineVersion?: {
                  clientInfo: string;
                  createdAt: string;
                  id: string;
              };
              done: boolean;
              machineVersion: {
                  clientInfo: string;
                  createdAt: string;
                  id: string;
              };
              state: string | {
                  [key: string]: components["schemas"]["StateValue"] | undefined;
              };
              status: "paused" | "running";
              tags: string[];
          }>
        • Retrieve the administrative state of a machine instance.

          Parameters

          • machineName: string

            the name of the machine we are retrieving an instance of

          • machineInstanceName: string

            the name of the machine instance we are retrieving

          • Optional signal: AbortSignal

            an optional AbortSignal to abort the request

          Returns Promise<{
              context: {
                  [key: string]: unknown;
              };
              createdAt: string;
              desiredMachineVersion?: {
                  clientInfo: string;
                  createdAt: string;
                  id: string;
              };
              done: boolean;
              machineVersion: {
                  clientInfo: string;
                  createdAt: string;
                  id: string;
              };
              state: string | {
                  [key: string]: components["schemas"]["StateValue"] | undefined;
              };
              status: "paused" | "running";
              tags: string[];
          }>

          the administrative state of the machine

    • updateDesiredVersion: ((machineName, instanceName, req, signal?) => Promise<void>)
        • (machineName, instanceName, req, signal?): Promise<void>
        • Update the desired machine version for an existing instance.

          The instance will not be upgraded immediately but will be upgraded the next time an event is sent to it from a settled state.

          Parameters

          • machineName: string

            the name of the machine we are updating the desired version for

          • instanceName: string

            the name of the machine instance we are updating the desired version for

          • req: {
                targetMachineVersionId: string;
            }

            desired version information

            • targetMachineVersionId: string
          • Optional signal: AbortSignal

            an optional AbortSignal to abort the request

          Returns Promise<void>

          Throws

          errors.NoMigrationPathError if there is no path through the set of existing migrations from the current instance version to the desired instance version.

  • create: ((machineName, req, signal?) => Promise<EnhancedState>)
      • (machineName, req, signal?): Promise<EnhancedState>
      • Create a machine instance.

        Parameters

        • machineName: string

          the name of the machine we are creating an instance of

        • req: {
              context?: {
                  [key: string]: unknown;
              };
              machineVersionId?: string;
              slug: string;
          }

          instance information

          • Optional context?: {
                [key: string]: unknown;
            }

            Description

            The initial context for the machine instance. Defaults to {}.

            • [key: string]: unknown
          • Optional machineVersionId?: string
          • slug: string
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<EnhancedState>

        the initial state and public context of the machine after initialization

  • dangerously: {
        delete: ((machineName, machineInstanceName, req, signal?) => Promise<void>);
        setStatus: ((machineName, machineInstanceName, req, signal?) => Promise<void>);
    }

    The methods within machineInstances.dangerous are... DANGEROUS.

    They are intended to be used in development or in very exceptional circumstances in production.

    These methods can cause data loss and are the only mechanisms through which you can cause a machine instance to enter an invalid state.

    • delete: ((machineName, machineInstanceName, req, signal?) => Promise<void>)
        • (machineName, machineInstanceName, req, signal?): Promise<void>
        • Deletes a machine instance.

          THIS WILL OBVIOUSLY CAUSE DATA LOSS

          Deleted machine instances are not recoverable.

          All historical transitions, scheduled events, pending upgrades, and current state will be irrevocably deleted.

          Parameters

          • machineName: string

            the name of the machine we are deleting an instance of

          • machineInstanceName: string

            the name of the machine instance we are deleting

          • req: {
                dangerDataWillBeDeletedForever: true;
            }

            confirmation that you are permanently deleting data

            • dangerDataWillBeDeletedForever: true
          • Optional signal: AbortSignal

            an optional AbortSignal to abort the request

          Returns Promise<void>

    • setStatus: ((machineName, machineInstanceName, req, signal?) => Promise<void>)
        • (machineName, machineInstanceName, req, signal?): Promise<void>
        • Pauses or resumes a machine instance.

          PAUSE WITH CARE

          Pausing a machine instance will cause it to reject all events until it is resumed, including rejecting scheduled/delayed events. Scheduled events are only retried 5 times (~30 seconds apart) before they are permanently dropped so it is possible to invalidate the typical guarantees that your machine provides by pausing an instance.

          Parameters

          • machineName: string

            the name of the machine we are pausing/resuming an instance of

          • machineInstanceName: string

            the name of the machine instance we are pausing/resuming

          • req: {
                status: "paused" | "running";
            }

            status information

            • status: "paused" | "running"
          • Optional signal: AbortSignal

            an optional AbortSignal to abort the request

          Returns Promise<void>

  • get: ((machineName, machineInstanceName, signal?) => Promise<EnhancedState>)
      • (machineName, machineInstanceName, signal?): Promise<EnhancedState>
      • Retrieve the machine instance's state and public context

        Parameters

        • machineName: string

          the name of the machine we are retrieving an instance of

        • machineInstanceName: string

          the name of the machine instance we are retrieving

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<EnhancedState>

        the current state and public context of the machine

  • getActor: (<TEvent, TState, TContext>(machineName, machineInstanceName, signal?) => Promise<Actor<TEvent, TState, TContext>>)
      • <TEvent, TState, TContext>(machineName, machineInstanceName, signal?): Promise<Actor<TEvent, TState, TContext>>
      • Returns an XState-compatible actor that represents the machine instance.

        The actor allows for subscriptions to state and sending events.

        Type Parameters

        • TEvent extends {
              type: string;
              [key: string]: unknown;
          }

        • TState extends string | {
              [key: string]: components["schemas"]["StateValue"] | undefined;
          } = any

        • TContext extends Record<string, unknown> = any

        Parameters

        • machineName: string

          the name of the machine we are creting an actor for

        • machineInstanceName: string

          the name of the machine instance we are creating an actor for

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<Actor<TEvent, TState, TContext>>

        • an XState-compatible actor
  • getOrCreate: ((machineName, instanceName, creationParams, signal?) => Promise<EnhancedState>)
      • (machineName, instanceName, creationParams, signal?): Promise<EnhancedState>
      • Convenience method to ensure that a machine instance exists.

        If the machine exists, it will read its state. Otherwise, it will create the machine and return its state.

        Parameters

        • machineName: string

          the name of the machine we are ensuring exists

        • instanceName: string

          the name of the machine instance we are ensuring exists

        • creationParams: Omit<{
              context?: {
                  [key: string]: unknown;
              };
              machineVersionId?: string;
              slug: string;
          }, "slug"> | (() => Omit<{
              context?: {
                  [key: string]: unknown;
              };
              machineVersionId?: string;
              slug: string;
          }, "slug">)

          parameters to use when creating the machine instance if it doesn't exist OR function returning those parameters if they are expensive to calculate

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<EnhancedState>

        the current (or initial) state and public context of the machine

  • getOrCreateActor: (<TEvent, TState, TContext>(machineName, machineInstanceName, creationParams, signal?) => Promise<Actor<TEvent, TState, TContext>>)
      • <TEvent, TState, TContext>(machineName, machineInstanceName, creationParams, signal?): Promise<Actor<TEvent, TState, TContext>>
      • Returns an XState-compatible actor that represents the machine instance, creating the instance if it does not exist.

        The actor allows for subscriptions to state and sending events.

        Type Parameters

        • TEvent extends {
              type: string;
              [key: string]: unknown;
          }

        • TState extends string | {
              [key: string]: components["schemas"]["StateValue"] | undefined;
          } = any

        • TContext extends Record<string, unknown> = any

        Parameters

        • machineName: string

          the name of the machine we are creting an actor for

        • machineInstanceName: string

          the name of the machine instance we are creating an actor for

        • creationParams: Omit<{
              context?: {
                  [key: string]: unknown;
              };
              machineVersionId?: string;
              slug: string;
          }, "slug"> | (() => Omit<{
              context?: {
                  [key: string]: unknown;
              };
              machineVersionId?: string;
              slug: string;
          }, "slug">)

          parameters to use when creating the machine instance if it doesn't exist OR function returning those parameters if they are expensive to calculate

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<Actor<TEvent, TState, TContext>>

        • an XState-compatible actor
  • list: ((machineName, opts?, signal?) => Promise<{
        cursor?: string;
        instances: {
            createdAt: string;
            machineVersion: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            slug: string;
            status: "paused" | "running";
        }[];
    }>)
      • (machineName, opts?, signal?): Promise<{
            cursor?: string;
            instances: {
                createdAt: string;
                machineVersion: {
                    clientInfo: string;
                    createdAt: string;
                    id: string;
                };
                slug: string;
                status: "paused" | "running";
            }[];
        }>
      • Retrieve a page of machine instances for a machine.

        Parameters

        • machineName: string

          the name of the machine we are retrieving instances for

        • Optional opts: ListOptions

          options for the list operation

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            instances: {
                createdAt: string;
                machineVersion: {
                    clientInfo: string;
                    createdAt: string;
                    id: string;
                };
                slug: string;
                status: "paused" | "running";
            }[];
        }>

        • a page of machine instances
  • listTransitions: ((machineName, machineInstanceName, opts?, signal?) => Promise<{
        cursor?: string;
        transitions: {
            createdAt: string;
            event: string | {
                type: string;
                [key: string]: unknown;
            };
            state: string | {
                [key: string]: components["schemas"]["StateValue"] | undefined;
            };
        }[];
    }>)
      • (machineName, machineInstanceName, opts?, signal?): Promise<{
            cursor?: string;
            transitions: {
                createdAt: string;
                event: string | {
                    type: string;
                    [key: string]: unknown;
                };
                state: string | {
                    [key: string]: components["schemas"]["StateValue"] | undefined;
                };
            }[];
        }>
      • Retrieve a page of transitions for a machine instance.

        Parameters

        • machineName: string

          the name of the machine we are retrieving transitions for

        • machineInstanceName: string

          the name of the machine instance we are retrieving transitions for

        • Optional opts: ListOptions

          options for the list operation

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            transitions: {
                createdAt: string;
                event: string | {
                    type: string;
                    [key: string]: unknown;
                };
                state: string | {
                    [key: string]: components["schemas"]["StateValue"] | undefined;
                };
            }[];
        }>

        • a page of machine instance transitions
  • query: ((machineName, indexName, req?, signal?) => Promise<{
        cursor?: string;
        instances: {
            indexValue: string;
            slug: string;
        }[];
    }>)
      • (machineName, indexName, req?, signal?): Promise<{
            cursor?: string;
            instances: {
                indexValue: string;
                slug: string;
            }[];
        }>
      • Query for instances of this machine whose indexed context value matches the given query.

        Results are returned in pages and the next page may be retrieved by passing the cursor returned by the prior call and supplying the same parameters.

        Note: The same instance may appear on multiple pages of the result set if its indexed context value changes between calls.

        Parameters

        • machineName: string

          the name of the machine we are querying instances of

        • indexName: string

          the name of the index we are querying

        • Optional req: {
              cursor?: string;
              dir?: "desc" | "asc";
              limit?: number;
              op?: "eq" | "ne" | "gt" | "gte" | "lt" | "lte";
              value?: string;
          }

          the query parameters, will list all machine instances in ascending order if not provided

          • Optional cursor?: string

            Description

            The cursor returned from a previous call to query.

          • Optional dir?: "desc" | "asc"

            Description

            The sort direction for the index.

          • Optional limit?: number

            Description

            The maximum number of items to return.

          • Optional op?: "eq" | "ne" | "gt" | "gte" | "lt" | "lte"

            Description

            The operation for the filter.

          • Optional value?: string

            Description

            The value for the filter.

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            instances: {
                indexValue: string;
                slug: string;
            }[];
        }>

        • a page of machine instances
  • sendEvent: ((machineName, instanceName, req, signal?) => Promise<EnhancedState>)
      • (machineName, instanceName, req, signal?): Promise<EnhancedState>
      • Send an event to a machine instance.

        Parameters

        • machineName: string

          the name of the machine we are sending an event to

        • instanceName: string

          the name of the machine instance we are sending an event to

        • req: {
              event: string | {
                  type: string;
                  [key: string]: unknown;
              };
          }

          event information

          • event: string | {
                type: string;
                [key: string]: unknown;
            }
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<EnhancedState>

        the state and public context of the machine after processing the event

  • subscribe: ((machineName, machineInstanceName, onStateUpdate, onError?, signal?) => Unsubscribe)
      • (machineName, machineInstanceName, onStateUpdate, onError?, signal?): Unsubscribe
      • Subscribe to state change notifications for an instance.

        onStateUpdate will be invoked right after the subscription is confirmed and on (almost) every state update thereafter until unsubscribe is called.

        It is possible that clients may miss some state updates (e.g. due to transitions happening during reconnects) so the only assumption client code should make is that onStateUpdate is called with the latest known state.

        A web socket will be established and kept open whenever at least one subscriber is active.

        In non-web environments, you may need to set the WebSocket implementation the client uses by passing a WebSocket option in the constructor.

        Parameters

        • machineName: string

          the name of the machine we are subscribing to an instance of

        • machineInstanceName: string

          the name of the instance we are subscribing to

        • onStateUpdate: ((stateUpdate) => void)

          function to invoke with each state update

            • (stateUpdate): void
            • Parameters

              • stateUpdate: {
                    done: boolean;
                    publicContext?: {
                        [key: string]: unknown;
                    };
                    state: string | {
                        [key: string]: components["schemas"]["StateValue"] | undefined;
                    };
                    tags: string[];
                    ts: number;
                }
                • done: boolean

                  Description

                  Is the state machine complete

                • Optional publicContext?: {
                      [key: string]: unknown;
                  }

                  Description

                  The public context of the machine instance.

                  This includes all context under the public key.

                  • [key: string]: unknown
                • state: string | {
                      [key: string]: components["schemas"]["StateValue"] | undefined;
                  }
                • tags: string[]

                  Description

                  Array of tags for the current states

                • ts: number

                  Description

                  Timestamp for when the state was created

              Returns void

        • Optional onError: ((err) => void)

          function to invoke if there is an error subscribing

            • (err): void
            • Parameters

              Returns void

        • Optional signal: AbortSignal

          optional AbortSignal. If aborted, we will unsubscribe.

        Returns Unsubscribe

        an unsubscribe function to be called when the subscription should be canceled

machineVersionMigrations: {
    create: ((machineName, req, signal?) => Promise<{
        machineVersionId?: string;
    }>);
    finalize: ((machineName, signedMachineVersionMigrationId, signal?) => Promise<{
        machineVersionId?: string;
    }>);
    provisionallyCreate: ((machineName, req, gzip?, signal?) => Promise<{
        codeUploadFields: {
            [key: string]: string | undefined;
        };
        codeUploadUrl: string;
        machineVersionMigrationId: string;
    }>);
} = ...

Machine version migrations API.

Migrations allow you to migrate running instances from one machine version to another.

A machine version migration maps states and context from one machine version to another.

Similarly to machine versions, machine version migrations are created in a 3-step process: provisional creation to reserve an ID, code upload, and finalization.

However, you can use the create convenience wrapper to do all 3 steps in one call.

Type declaration

  • create: ((machineName, req, signal?) => Promise<{
        machineVersionId?: string;
    }>)
      • (machineName, req, signal?): Promise<{
            machineVersionId?: string;
        }>
      • Convenience method to create a machine version migration in one call.

        Once a machine version migration is finalized, it may participate in upgrade operations on existing instances.

        Parameters

        • machineName: string

          the name of the machine we are adding a version to

        • req: Object

          migration information

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            machineVersionId?: string;
        }>

        machine version migration ID

  • finalize: ((machineName, signedMachineVersionMigrationId, signal?) => Promise<{
        machineVersionId?: string;
    }>)
      • (machineName, signedMachineVersionMigrationId, signal?): Promise<{
            machineVersionId?: string;
        }>
      • Finalize the creation of a machine version migration.

        Once a machine version migration is finalized, it may participate in upgrade operations on existing instances.

        Parameters

        • machineName: string

          the name of the machine we are finalizing a version for

        • signedMachineVersionMigrationId: string

          the signed machine version migration ID returned from the provisional creation step

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            machineVersionId?: string;
        }>

        machine version migration ID

  • provisionallyCreate: ((machineName, req, gzip?, signal?) => Promise<{
        codeUploadFields: {
            [key: string]: string | undefined;
        };
        codeUploadUrl: string;
        machineVersionMigrationId: string;
    }>)
      • (machineName, req, gzip?, signal?): Promise<{
            codeUploadFields: {
                [key: string]: string | undefined;
            };
            codeUploadUrl: string;
            machineVersionMigrationId: string;
        }>
      • Provisionally create a machine version migration.

        After this call, you must upload your code and finalize the machine version migration like this:

        const { codeUploadFields, codeUploadUrl } = await provisionalVersionMigrationCreationResponse.json();
        const uploadForm = new FormData();
        for (const [key, value] of Object.entries(codeUploadFields)) {
        uploadForm.append(key, value as string);
        }
        uploadForm.set("content-type", "application/javascript");
        uploadForm.append(
        "file",
        new Blob(["javascript-code-here"], {
        type: "application/javascript",
        }),
        "your-file-name.js",
        );
        const uploadRes = await fetch(
        codeUploadUrl,
        {
        method: "POST",
        body: uploadForm,
        },
        );

        Parameters

        • machineName: string

          the name of the machine we are adding a version migration to

        • req: {
              fromMachineVersionId: string;
              toMachineVersionId: string;
          }

          migration information

          • fromMachineVersionId: string
          • toMachineVersionId: string
        • gzip: boolean = false
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            codeUploadFields: {
                [key: string]: string | undefined;
            };
            codeUploadUrl: string;
            machineVersionMigrationId: string;
        }>

        code upload fields and url to upload the machine version migration's code to and a signed machine version migration ID to use in the finalization step

machineVersions: {
    create: ((machineName, req, signal?) => Promise<{
        machineVersionId: string;
    }>);
    finalize: ((machineName, signedMachineVersionId, req, signal?) => Promise<{
        machineVersionId: string;
    }>);
    list: ((machineName, opts?, signal?) => Promise<{
        cursor?: string;
        versions: {
            clientInfo: string;
            createdAt: string;
            id: string;
        }[];
    }>);
    provisionallyCreate: ((machineName, gzip?, signal?) => Promise<{
        codeUploadFields: {
            [key: string]: string | undefined;
        };
        codeUploadUrl: string;
        machineVersionId: string;
    }>);
} = ...

Machine versions API.

Each machine definition may have many machine versions associated with it.

The most important aspect of a machine version is your actual code for your authorizer and state machines.

Machine versions can also provide a version specifier to help you link a version to your own systems. We recommend a semantic version, timestamp, or git commit sha for a version specifier.

Machine versions are created in a 3-step process: provisional creation to reserve an ID, code upload, and finalization. You can use the convenience wrapper, create, to do all 3 steps in one call.

If you want to migrate running instances from one version to another,

Type declaration

  • create: ((machineName, req, signal?) => Promise<{
        machineVersionId: string;
    }>)
      • (machineName, req, signal?): Promise<{
            machineVersionId: string;
        }>
      • Convenience method to create a machine version in one call.

        Once a machine version is created, you may create instances from it. If you want to migrate running instances from one version to another,

        Parameters

        • machineName: string

          the name of the machine we are adding a version to

        • req: Object

          version information

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            machineVersionId: string;
        }>

        machine version ID

        See

        machineVersionMigrations. If you want all future instances to use this version by default, pass { makeCurrent: true }.

  • finalize: ((machineName, signedMachineVersionId, req, signal?) => Promise<{
        machineVersionId: string;
    }>)
      • (machineName, signedMachineVersionId, req, signal?): Promise<{
            machineVersionId: string;
        }>
      • Finalize the creation of a machine version.

        Once a machine version is finalized, you may create instances from it. If you want to migrate running instances from one version to another,

        Parameters

        • machineName: string

          the name of the machine we are finalizing a version for

        • signedMachineVersionId: string

          the signed machine version ID returned from the provisional creation step

        • req: {
              clientInfo?: string;
              indexSelectors?: {
                  [key: string]: string | undefined;
              };
              makeCurrent?: boolean;
          }

          version information

          • Optional clientInfo?: string

            Description

            Informational only. Any string that describes this version. Good uses would be a semantic version number or git commit.

          • Optional indexSelectors?: {
                [key: string]: string | undefined;
            }

            Description

            Mapping from index names (must match index names from the corresponding machine) to JSON path selectors into machine context. On every state update, the pointed-to value in machine context will be extracted and used to index the machine.

            • [key: string]: string | undefined
          • Optional makeCurrent?: boolean

            Description

            Whether to make this version the current version for the machine definition. If true, the current version will be set to this version. If false, the current version will not be changed.

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            machineVersionId: string;
        }>

        machine version ID

        See

        machineVersionMigrations. If you want all future instances to use this version by default, pass { makeCurrent: true }.

  • list: ((machineName, opts?, signal?) => Promise<{
        cursor?: string;
        versions: {
            clientInfo: string;
            createdAt: string;
            id: string;
        }[];
    }>)
      • (machineName, opts?, signal?): Promise<{
            cursor?: string;
            versions: {
                clientInfo: string;
                createdAt: string;
                id: string;
            }[];
        }>
      • Retrieve a page of machine versions for a machine.

        Parameters

        • machineName: string

          the name of the machine we are retrieving versions for

        • Optional opts: ListOptions

          options for the list operation

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            versions: {
                clientInfo: string;
                createdAt: string;
                id: string;
            }[];
        }>

        • a page of machine versions
  • provisionallyCreate: ((machineName, gzip?, signal?) => Promise<{
        codeUploadFields: {
            [key: string]: string | undefined;
        };
        codeUploadUrl: string;
        machineVersionId: string;
    }>)
      • (machineName, gzip?, signal?): Promise<{
            codeUploadFields: {
                [key: string]: string | undefined;
            };
            codeUploadUrl: string;
            machineVersionId: string;
        }>
      • Provisionally create a machine version.

        After this call, you must upload your code and finalize the machine version like this:

        const { codeUploadFields, codeUploadUrl } = await provisionalVersionCreationResponse.json();
        const uploadForm = new FormData();
        for (const [key, value] of Object.entries(codeUploadFields)) {
        uploadForm.append(key, value as string);
        }
        uploadForm.set("content-type", "application/javascript");
        uploadForm.append(
        "file",
        new Blob(["javascript-code-here"], {
        type: "application/javascript",
        }),
        "your-file-name.js",
        );
        const uploadRes = await fetch(
        codeUploadUrl,
        {
        method: "POST",
        body: uploadForm,
        },
        );

        Parameters

        • machineName: string

          the name of the machine we are adding a version to

        • gzip: boolean = false
        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            codeUploadFields: {
                [key: string]: string | undefined;
            };
            codeUploadUrl: string;
            machineVersionId: string;
        }>

        code upload fields and url to upload the machine version's code to and a signed machine version ID to use in the finalization step

See

machineVersionMigrations.

machines: {
    create: ((machineName, req?, signal?) => Promise<void>);
    dangerously: {
        delete: ((machineName, req, signal?) => Promise<void>);
    };
    get: ((machineName, signal?) => Promise<{
        machine: {
            createdAt: string;
            currentVersion?: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            indexes: string[];
        };
    }>);
    list: ((opts?, signal?) => Promise<{
        cursor?: string;
        machines: {
            createdAt: string;
            currentVersion?: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            slug: string;
        }[];
    }>);
} = ...

Machines API.

Machine definitions name a logical machine.

For example, you might have a machine definition that represents a flow for a user in your app (like the onboarding machine) or a machine definition that represents the state of a user or entity (like a user machine or a machine for a document that might be shared across many users).

We call this a logical machine because your actual business logic lives in machine versions.

Once a machine exists and it has at least one version, you can launch instances of it.

Type declaration

  • create: ((machineName, req?, signal?) => Promise<void>)
      • (machineName, req?, signal?): Promise<void>
      • Create a machine.

        Parameters

        • machineName: string

          the name of the machine

        • Optional req: Omit<{
              indexes?: string[];
              slug: string;
          }, "slug">

          additional options for the machine creation request

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<void>

  • dangerously: {
        delete: ((machineName, req, signal?) => Promise<void>);
    }

    The methods within machines.dangerous are... DANGEROUS.

    They are intended to be used in development or in very exceptional circumstances in production.

    These methods can cause data loss.

    • delete: ((machineName, req, signal?) => Promise<void>)
        • (machineName, req, signal?): Promise<void>
        • Deletes a machine.

          THIS WILL OBVIOUSLY CAUSE DATA LOSS

          Deleted machines are not recoverable and deleting a machine deletes its associated versions and the migrations between them.

          Machines cannot be deleted if there are still instances of them running. You may delete instances of machines using

          Parameters

          • machineName: string

            the name of the machine we are deleting an instance of

          • req: {
                dangerDataWillBeDeletedForever: true;
            }

            confirmation that you are permanently deleting data

            • dangerDataWillBeDeletedForever: true
          • Optional signal: AbortSignal

            an optional AbortSignal to abort the request

          Returns Promise<void>

          See

          machineInstances.dangerously.delete.

  • get: ((machineName, signal?) => Promise<{
        machine: {
            createdAt: string;
            currentVersion?: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            indexes: string[];
        };
    }>)
      • (machineName, signal?): Promise<{
            machine: {
                createdAt: string;
                currentVersion?: {
                    clientInfo: string;
                    createdAt: string;
                    id: string;
                };
                indexes: string[];
            };
        }>
      • Retrieve a machine definition.

        Parameters

        • machineName: string

          the name of the machine we are retrieving

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            machine: {
                createdAt: string;
                currentVersion?: {
                    clientInfo: string;
                    createdAt: string;
                    id: string;
                };
                indexes: string[];
            };
        }>

        the machine definition

  • list: ((opts?, signal?) => Promise<{
        cursor?: string;
        machines: {
            createdAt: string;
            currentVersion?: {
                clientInfo: string;
                createdAt: string;
                id: string;
            };
            slug: string;
        }[];
    }>)
      • (opts?, signal?): Promise<{
            cursor?: string;
            machines: {
                createdAt: string;
                currentVersion?: {
                    clientInfo: string;
                    createdAt: string;
                    id: string;
                };
                slug: string;
            }[];
        }>
      • Retrieve a page of machine definitions.

        Parameters

        • Optional opts: ListOptions

          options for the list operation

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            machines: {
                createdAt: string;
                currentVersion?: {
                    clientInfo: string;
                    createdAt: string;
                    id: string;
                };
                slug: string;
            }[];
        }>

        a page of machine definitions

opts: Omit<ClientOpts, "actAs"> & Required<Pick<Omit<ClientOpts, "actAs">, "fetch" | "base64url" | "hmacSha256" | "apiHost" | "wsPingIntervalMs" | "FormData" | "Blob">> & {
    actAs?: string;
}

Type declaration

  • Optional actAs?: string
orgs: {
    create: ((req, signal?) => Promise<{
        id: string;
    }>);
    list: ((opts?, signal?) => Promise<{
        cursor?: string;
        orgs: {
            createdAt: string;
            id: string;
            limits: {
                monthlyEventsLimit: number;
                monthlyReadsLimit: number;
            };
            name: string;
            role: "write" | "admin" | "read";
        }[];
    }>);
} = ...

Type declaration

  • create: ((req, signal?) => Promise<{
        id: string;
    }>)
      • (req, signal?): Promise<{
            id: string;
        }>
      • Parameters

        • req: {
              allowAnonymousAccess?: boolean;
              name: string;
          }
          • Optional allowAnonymousAccess?: boolean

            Description

            If true, a key, trusted identity provider, and token provider that support anonymous access will be created for the org. The usual authorization checks still apply at the machine level so individual reads and writes for anonymous access depends on your allowRead and allowWrite implementations. Auth context for anonymous tokens includes Session ID (sid), Device ID (did), and { "auth": "anonymous" }.

            Default

            true
            
          • name: string
        • Optional signal: AbortSignal

        Returns Promise<{
            id: string;
        }>

  • list: ((opts?, signal?) => Promise<{
        cursor?: string;
        orgs: {
            createdAt: string;
            id: string;
            limits: {
                monthlyEventsLimit: number;
                monthlyReadsLimit: number;
            };
            name: string;
            role: "write" | "admin" | "read";
        }[];
    }>)
      • (opts?, signal?): Promise<{
            cursor?: string;
            orgs: {
                createdAt: string;
                id: string;
                limits: {
                    monthlyEventsLimit: number;
                    monthlyReadsLimit: number;
                };
                name: string;
                role: "write" | "admin" | "read";
            }[];
        }>
      • Parameters

        • Optional opts: ListOptions
        • Optional signal: AbortSignal

        Returns Promise<{
            cursor?: string;
            orgs: {
                createdAt: string;
                id: string;
                limits: {
                    monthlyEventsLimit: number;
                    monthlyReadsLimit: number;
                };
                name: string;
                role: "write" | "admin" | "read";
            }[];
        }>

tokenConfig: string | TokenConfig | (() => Promise<string>)

Configuration to retrieve the State Backed token to use for all requests.

Type declaration

    • (): Promise<string>
    • Returns Promise<string>

tokenExpiration: number
tokenProviders: {
    delete: ((service, signal?) => Promise<void>);
    list: ((opts?, signal?) => Promise<{
        cursor?: string;
        tokenProviders: {
            keyId: string;
            mapping: {
                [key: string]: unknown;
            };
            service: string;
        }[];
    }>);
    upsert: ((req, signal?) => Promise<void>);
} = ...

Token exchange involves exchanging an identity provider-signed token for a State Backed-signed token.

Token providers are responsible for creating State Backed tokens from a standardized claim set extracted from identity provider tokens by their mappings.

Token providers are identified by a service name. You might, for instance, want a service name for each application that you host with State Backed.

Token providers also specify the State Backed key to use to sign the tokens they generate and a mapping that creates the claims for the generated token.

For example, if your identity provider mappings extract claims like this:

{
"sub": "your-sub",
"email": "your-email",
"provider": "identity-provider"
}

you could create a token provider like this:

client.tokenProviders.upsert({
"keyId": "sbk_...", // ID for a previously-created State Backed key
"service": "your-app", // any identifier for your token provider
"mapping": {
"sub.$": "$.sub",
"email.$": "$.email",
"provider.$": "$.provider",
}
})

That token provider would allow you to exchange any of your identity provider- signed tokens for a State Backed token that includes the sub, email, and provider claims, all of which would be available for your use in allowRead and allowWrite functions in your machine definitions.

Upserts may change key ids and mappings.

Type declaration

  • delete: ((service, signal?) => Promise<void>)
      • (service, signal?): Promise<void>
      • Delete the token provider configuration identified by its service name.

        Parameters

        • service: string

          the service name of the token provider to delete

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<void>

  • list: ((opts?, signal?) => Promise<{
        cursor?: string;
        tokenProviders: {
            keyId: string;
            mapping: {
                [key: string]: unknown;
            };
            service: string;
        }[];
    }>)
      • (opts?, signal?): Promise<{
            cursor?: string;
            tokenProviders: {
                keyId: string;
                mapping: {
                    [key: string]: unknown;
                };
                service: string;
            }[];
        }>
      • Retrieve a page of token providers.

        Parameters

        • Optional opts: ListOptions

          options for the list operation

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<{
            cursor?: string;
            tokenProviders: {
                keyId: string;
                mapping: {
                    [key: string]: unknown;
                };
                service: string;
            }[];
        }>

        • a page of token providers
  • upsert: ((req, signal?) => Promise<void>)
      • (req, signal?): Promise<void>
      • Create or update a token provider configuration.

        The mapping is an object that defines the shape of the claims that will be included in any State Backed tokens generated by this token provider. The mapping may refer to claims extracted from the identity provider token by suffixing the key with ".$" and using a JSON path to the claim in the identity provider token.

        For example:

        {
        "sub.$": "$.sub",
        "service": "my-service",
        }

        would produce a sub claim with the value of the sub field on the extracted claims and a service claim with the constant value "my-service".

        Parameters

        • req: {
              keyId: string;
              mapping: {
                  [key: string]: unknown;
              };
              service: string;
          }

          token provider configuration

          • keyId: string

            Description

            ID of the State Backed key (created using smply keys create or posting to /keys) to use to sign tokens created by this token provider.

          • mapping: {
                [key: string]: unknown;
            }

            Description

            A mapping object that creates the claim set for the State Backed token and may reference the claims extracted by the identity provider mappings.

            The values of properties that end in ".$" are treated as JSONPath references into the claim set of the provided token.

            So a mapping of { "sub.$": "$.sub" } with identity provider claims of { "sub": "user-123" } will result in { "sub": "user-123" } as the State Backed token claims.

            • [key: string]: unknown
          • service: string

            Description

            The name of this token provider. This name is used to request tokens from the /tokens endpoint

        • Optional signal: AbortSignal

          an optional AbortSignal to abort the request

        Returns Promise<void>

tokens: {
    exchange: ((req, signal?) => Promise<string>);
} = ...

Type declaration

  • exchange: ((req, signal?) => Promise<string>)
      • (req, signal?): Promise<string>
      • Parameters

        Returns Promise<string>

ws: ReconnectingWebSocket<{
    done: boolean;
    machineInstanceName: string;
    machineName: string;
    publicContext: {
        [key: string]: unknown;
    };
    state: string | {
        [key: string]: components["schemas"]["StateValue"] | undefined;
    };
    tags: string[];
    ts: number;
    type: "instance-update";
} | {
    code?: string;
    requestId: string;
    status: number;
    type: "error";
}, {
    machineInstanceName: string;
    machineName: string;
    requestId: string;
    type: "subscribe-to-instance";
} | {
    machineInstanceName: string;
    machineName: string;
    requestId: string;
    type: "unsubscribe-from-instance";
} | {
    type: "ping";
}>

Accessors

  • get headers(): Promise<{
        authorization: string;
        content-type: string;
        x-statebacked-act?: string;
        x-statebacked-org-id?: string;
    }>
  • Returns Promise<{
        authorization: string;
        content-type: string;
        x-statebacked-act?: string;
        x-statebacked-org-id?: string;
    }>

  • get nonAuthJSONHeaders(): {
        content-type: string;
        x-statebacked-act?: string;
        x-statebacked-org-id?: string;
    }
  • Returns {
        content-type: string;
        x-statebacked-act?: string;
        x-statebacked-org-id?: string;
    }

    • content-type: string
    • Optional x-statebacked-act?: string
    • Optional x-statebacked-org-id?: string

Methods

  • Parameters

    • handler: ((msg) => void)
        • (msg): void
        • Parameters

          • msg: {
                done: boolean;
                machineInstanceName: string;
                machineName: string;
                publicContext: {
                    [key: string]: unknown;
                };
                state: string | {
                    [key: string]: components["schemas"]["StateValue"] | undefined;
                };
                tags: string[];
                ts: number;
                type: "instance-update";
            } | {
                code?: string;
                requestId: string;
                status: number;
                type: "error";
            }

          Returns void

    Returns Promise<(() => void)>

Generated using TypeDoc