Viv JavaScript Runtime - v0.10.2
    Preparing search index...

    Interface HostApplicationAdapter

    A collection of functions and other parameters that are required by the runtime in order to properly integrate with a host application.

    Note that the Viv runtime does not catch or wrap exceptions thrown by adapter functions. As such, if an adapter function throws, the error will propagate through the runtime and find its way back to the caller, with its original type and stack trace intact.

    As such, you can use instanceof to distinguish between Viv errors (always an instance of VivError) and your own adapter errors (any other error type):

    try {
    const actionID = await selectAction({ initiatorID });
    } catch (error) {
    if (error instanceof VivError) {
    // Something went wrong in the Viv runtime (e.g., a bad expression,
    // a role-casting issue, or a validation failure).
    } else {
    // Something went wrong in your adapter (e.g., a failed database
    // query, a missing entity, or a bug in a custom function).
    }
    }

    Important: Viv assumes that it can freely mutate the furnished data, with any actual updates being persisted via calls to the explicit adapter functions specified in the documentation below, so be sure to clone data as needed.

    interface HostApplicationAdapter {
        getCurrentTimestamp: () => AsyncOrSync<number>;
        getEntityIDs: (
            entityType: EntityType,
            locationID?: string,
        ) => AsyncOrSync<string[]>;
        getEntityLabel: (entityID: string) => AsyncOrSync<string>;
        getEntityView: (entityID: string) => AsyncOrSync<EntityView>;
        getVivInternalState: () => AsyncOrSync<VivInternalState | null>;
        provisionActionID: () => AsyncOrSync<string>;
        saveActionData: (
            actionID: string,
            actionData: ActionView,
        ) => AsyncOrSync<void>;
        saveCharacterMemory: (
            characterID: string,
            actionID: string,
            memory: CharacterMemory,
        ) => AsyncOrSync<void>;
        saveItemInscriptions: (
            itemID: string,
            inscriptions: string[],
        ) => AsyncOrSync<void>;
        saveVivInternalState: (
            vivInternalState: VivInternalState,
        ) => AsyncOrSync<void>;
        config?: HostApplicationAdapterConfig;
        debug?: HostApplicationAdapterDebuggingSettings;
        enums?: Record<string, string | number>;
        fastPaths?: HostApplicationAdapterFastPaths;
        functions?: Record<string, CustomFunction>;
        getCurrentTimeOfDay?: () => AsyncOrSync<TimeOfDay>;
        updateEntityProperty?: (
            entityID: string,
            propertyPath: (string | number)[],
            value: unknown,
        ) => AsyncOrSync<void>;
    }
    Index

    Properties

    getCurrentTimestamp: () => AsyncOrSync<number>

    A function that returns the current timestamp (in story time) in the running simulation instance associated with the host application.

    Here, story time refers to the concept of time within the storyworld being simulated by the host application, as opposed to clock time in the real world as the host application operates. In other words, diegetic time.

    Important: Viv assumes that a DiegeticTimestamp is represented as the number of minutes, in story time, that have passed since some initial reference point in the simulation. The starting point that is used for this determination is up to you, but the time unit must be minutes.

    This allows the Viv runtime to properly handle authored temporal constraints in reaction declarations, which allow for semantics such as "this reaction can only occur between one week and six months from now".

    Type Declaration

    getEntityIDs: (
        entityType: EntityType,
        locationID?: string,
    ) => AsyncOrSync<string[]>

    A function that returns an array containing entity IDs for entities of the given type in the running simulation instance of the host application.

    If a location is specified, the result should be limited to entities currently situated at that location. Otherwise, the result should contain entity IDs for all entities of the given type.

    Important: Viv considers a character or item to be at a location if the entity's location property (in its CharacterView or ItemView) stores the entity ID for that location. Also, Viv assumes that it can freely mutate the furnished array, so be sure to clone as needed.

    Type Declaration

      • (entityType: EntityType, locationID?: string): AsyncOrSync<string[]>
      • Parameters

        • entityType: EntityType

          The type of entity for which entity IDs will be furnished.

        • OptionallocationID: string

          If specified, the entity ID for a location to search for entities, which should only be submitted for characters and items.

        Returns AsyncOrSync<string[]>

        An array of entity IDs.

    If locationID is present but entityType is not EntityType.Character or EntityType.Item.

    getEntityLabel: (entityID: string) => AsyncOrSync<string>

    A function that accepts an ID for an entity and returns a label for the entity, such as its name, that is suitable for insertion into a templated string.

    For example, a Viv author might write a templated string "@giver gives @item to @receiver", which the interpreter will have to render by replacing the references @giver, @item, and @receiver with strings.

    To do this, the runtime will call this function for each reference. Note that, for references to values that are not entity IDs, the value itself will be inserted without any calls to an adapter function, as in @giver.name gives { ~getItemDescription(@item.id) } to @receiver.name.

    Type Declaration

      • (entityID: string): AsyncOrSync<string>
      • Parameters

        • entityID: string

          ID for the entity for whom a label is being requested.

        Returns AsyncOrSync<string>

        The label for the entity.

    getEntityView: (entityID: string) => AsyncOrSync<EntityView>

    A function that accepts an entity ID and returns the full entity view for that entity, if there is such an entity, else throws an error.

    This function is used by the runtime to evaluate expressions such as conditions and effects. Note that the runtime will be careful to only pass an actual entity ID for entityID. How exactly the entity data is persisted is a nuance of the host application that is abstracted from the Viv runtime via the adapter interface. If fetching is expensive -- e.g., because it persists in a DB -- you might consider implementing caching in your application.

    Important: Viv assumes that it can freely mutate the furnished data, with any actual updates being persisted via an adapter function (or CustomFunction), so be sure to clone as needed.

    Type Declaration

    If there is no entity with the given entity ID.

    getVivInternalState: () => AsyncOrSync<VivInternalState | null>

    A function that returns the internal state of the Viv runtime, if it has been initialized, else null.

    While the Viv runtime will manage its own internal state, it relies on the host application to persist it.

    If the internal state has not been initialized -- i.e., the runtime has never called HostApplicationAdapter.saveVivInternalState -- then you should return null here.

    Type Declaration

    provisionActionID: () => AsyncOrSync<string>

    A function that returns a newly provisioned entity ID for an action.

    Note that this function is used to request IDs for queued actions that may never actually be performed. As such, not all IDs provisioned by this function will actually come to be associated with recorded actions.

    This is the only case where a UID will need to be provisioned for Viv, because entities created as a result of Viv actions will be initialized via a custom function specified in the spawn field of a role definition.

    Type Declaration

    saveActionData: (actionID: string, actionData: ActionView) => AsyncOrSync<void>

    A function that accepts a record describing an action and saves the underlying data in the host application.

    This function is called both to create new action records and to update existing action records.

    Important: The action record must be persisted such that any subsequent call to HostApplicationAdapter.getEntityView (with entityID) must produce an ActionView.

    Note: If HostApplicationAdapter.updateEntityProperty is implemented, Viv authors will be free to directly set action data via assignments. How that works behind the scenes depends on the host application.

    Type Declaration

    saveCharacterMemory: (
        characterID: string,
        actionID: string,
        memory: CharacterMemory,
    ) => AsyncOrSync<void>

    A function that accepts a record describing a character memory and saves the underlying data in the host application.

    This function is called both to create new character memories and to update existing ones.

    Important: The memory record must be persisted such that any subsequently retrieved CharacterView for the character in question will include the memory data in its CharacterView.memories field.

    Type Declaration

      • (
            characterID: string,
            actionID: string,
            memory: CharacterMemory,
        ): AsyncOrSync<void>
      • Parameters

        • characterID: string

          Entity ID for the character whose memory is to be saved.

        • actionID: string

          Entity ID for the action to which the memory pertains.

        • memory: CharacterMemory

          A record specifying the memory to save.

        Returns AsyncOrSync<void>

        Nothing.

    saveItemInscriptions: (
        itemID: string,
        inscriptions: string[],
    ) => AsyncOrSync<void>

    A function that accepts an item and updated inscriptions for that item and saves the underlying data in the host application.

    Important: The inscriptions must be persisted such that any subsequently retrieved ItemView for the item in question will include the inscriptions value in its ItemView.inscriptions field.

    Type Declaration

      • (itemID: string, inscriptions: string[]): AsyncOrSync<void>
      • Parameters

        • itemID: string

          Entity ID for the item whose inscriptions are to be saved.

        • inscriptions: string[]

          Array containing entity IDs for all actions about which the given item inscribes knowledge. This will always be deduplicated prior to calling this function.

        Returns AsyncOrSync<void>

        Nothing.

    saveVivInternalState: (vivInternalState: VivInternalState) => AsyncOrSync<void>

    A function that accepts updated internal state for the Viv runtime, and then persists the updated state in the host application.

    Type Declaration

    If supplied, configuration parameters controlling various aspects of Viv system behavior. Default values will be used for parameters that are not supplied.

    If supplied, settings activating debugging facilities of the Viv runtime.

    enums?: Record<string, string | number>

    If supplied, a mapping from enum names to their associated literal values in the host application.

    In Viv, enums are abstract labels like #BIG or #SMALL that may be used in places like effects, in lieu of magic numbers (or strings) that are prone to changing. For instance, an author could specify an effect like @insulted.updateAffinity(@insulter, -#MEDIUM), which specifies that someone who has just been insulted should greatly lower their affinity toward their insulter. For various reasons, this is preferable to something like @insulted.updateAffinity(@insulter, -35).

    Upon adapter registration, the Viv runtime will confirm that all enums referenced in your content bundle are present in this mapping here.

    If supplied, a collection of optional functions implementing frequent read and write operations, so as to be optimized according to implementation details specific to the host application at hand.

    functions?: Record<string, CustomFunction>

    If supplied, a mapping from custom-function names to CustomFunction.

    A host application can expose arbitrary functions in its Viv adapter, which authors can reference using the ~ sigil, as in e.g. ~transport(@person.id, @destination.id). The author defines the arguments using Viv expressions, which will each be evaluated prior to being passed into the actual custom function. The custom function is expected to return an expression value, which is a highly permissive union of various types.

    Important: Viv will dehydrate all arguments prior to passing them into a custom function, meaning any instance of entity data will be converted into its corresponding entity ID. This allows an author to write something like ~move(@person, @destination) without having to worry about whether to pass in the respective id properties.

    getCurrentTimeOfDay?: () => AsyncOrSync<TimeOfDay>

    If implemented, a function that returns the current time of day (in story time) in the running simulation instance associated with the host application.

    Here, story time refers to the concept of time within the storyworld being simulated by the host application, as opposed to clock time in the real world as the host application operates. This function is needed in order to enforce time-of-day constraints that Viv authors may place on actions, specifying concerns such as "this reaction may only be performed between 10pm and 11:59pm".

    If your simulation does not model time of day, you can leave this one out, in which case the adapter validator will ensure that no reactions in your content bundle reference time of day.

    Type Declaration

    updateEntityProperty?: (
        entityID: string,
        propertyPath: (string | number)[],
        value: unknown,
    ) => AsyncOrSync<void>

    If implemented, a function that updates the given entity's data by setting the property at the specified path.

    If this adapter function is not provided, entity data may only be updated via calls to CustomFunction. Further, the validator will ensure that no assignments in your content bundle target entities.

    Important: Viv supports autovivification (no pun intended), where an author may reference potentially undefined substructures along a path that will be created as needed. As such, in your procedure backing this adapter function, all intermediate objects along propertyPath must be created if they do not already exist.

    As an illustrative example, in Viv the assignment @person.foo.bar.baz = 77 is still valid even if @person.foo does not yet have a bar property. As such, your update procedure would have to set @person.foo.bar to an object {baz: 77} in this case. When setting local variables, which do not need to persist in the host application, the Viv runtime uses the default autovivification semantics of the Lodash set() function when it's given an array path: when a missing intermediate value is encountered, make it an array only if the next key is a non-negative integer, otherwise make it a plain object.

    Type Declaration

      • (
            entityID: string,
            propertyPath: (string | number)[],
            value: unknown,
        ): AsyncOrSync<void>
      • Parameters

        • entityID: string

          The entity ID of the entity whose data is to be updated.

        • propertyPath: (string | number)[]

          A path to the particular property of the entity data that is to be updated, structured as an array of property keys and/or array indices -- examples: ["friends", 2, "status"] and ["nearby", "artifacts.treatise", "school of thought"]. Note that property keys are arbitrary strings that may contain dots, whitespace, or any other character. If you plan to convert the path array into a string so that you can use something like Lodash to execute the entity update, you'll need to take care to ensure that your conversion procedure is properly robust. And again, as stated above, you must support autovivification for any undefined substructures along this property path.

        • value: unknown

          The value to set for the property specified by propertyPath.

        Returns AsyncOrSync<void>

        Nothing.