RTSDK
    Preparing search index...

    Class Visitor

    Create an instance of Visitor class with a given id and optional attributes and session credentials.

    import { Visitor } from "utils/topiaInit.ts";

    const visitor = await Visitor.get(visitorId, urlSlug, { attributes: { moveTo: { x: 0, y: 0 } }, credentials: { interactivePublicKey: "examplePublicKey", interactiveNonce: "exampleNonce", assetId: "exampleDroppedAssetId", profileId: "exampleProfileId", visitorId: 1, urlSlug: "exampleUrlSlug" } });

    Hierarchy (View Summary)

    Implements

    Index

    Assets

    • Returns all assets owned by User when an email address is provided.

      Returns Promise<void | ResponseType>

      get, fetch, retrieve, list, user assets, objects

      await user.fetchAssets();
      const userAssets = user.assets;
    • Returns all platform assets.

      Returns Promise<object | ResponseType>

      Returns the platform assets or an error response.

      get, fetch, retrieve, list, platform assets, objects

      const assets = await user.fetchPlatformAssets();
      

    Avatars

    • Add a new avatar

      Parameters

      • formData: FormData

      Returns Promise<void | ResponseType>

      add, create, upload, avatar, character

      const animationMeta = {
      "emote": { "loop": false, "x": 0, "y": 0, "hideLoop": true }
      }

      const spriteSheetJSON = {
      "animations": {
      "emote": [
      "emote/1.png"
      ]
      },
      "frames": {
      "emote/1.png": {
      "frame": {
      "x": 1911,
      "y": 778,
      "w": 58,
      "h": 91
      },
      "rotated": true,
      "trimmed": true,
      "spriteSourceSize": {
      "x": 50,
      "y": 33,
      "w": 58,
      "h": 91
      },
      "sourceSize": {
      "w": 159,
      "h": 159
      }
      }
      },
      "spriteSheetTypeMeta": {
      "nameplate": {
      "x": 0,
      "y": -70
      }
      },
      "meta": {
      "image": "spriteSheets%2FTvHNjgoMkiErDNSrVqHU%2FspriteSheet.png?alt=media",
      "format": "RGBA8888",
      "size": {
      "w": 2006,
      "h": 1099
      },
      "scale": "1"
      }
      }

      const formData = new FormData();
      formData.append('animationMeta', animationMeta);
      formData.append('name', "ExampleAvatarName");
      formData.append('spriteSheetJSON', spriteSheetJSON);
      formData.append('expression_dance', expression_dance);
      formData.append('expression_emote', expression_emote);
      formData.append('expression_sit', expression_sit);
      formData.append('expression_stand', expression_stand);
      formData.append('expression_transport', expression_transport);
      formData.append('preview', preview);
      formData.append('spriteSheet', spriteSheet);
      formData.append('unityPackage', unityPackage);
      await user.uploadAvatarFiles("exampleAvatarId", formData);
    • Update avatar and sprite sheet records and upload files to existing sprite sheet and avatar storage buckets

      Parameters

      • avatarId: string

      Returns Promise<void | ResponseType>

      delete, remove, erase, destroy, eliminate, avatar

      await user.deleteAvatar("exampleAvatarId");
      
    • Returns all avatars owned by User

      Returns Promise<void | ResponseType>

      Returns the avatars or an error.

      get, fetch, retrieve, list, avatars, characters

      const avatars = await user.fetchAvatars();
      
    • Update avatar and sprite sheet records and upload files to existing sprite sheet and avatar storage buckets

      Parameters

      • avatarId: string
      • formData: FormData

      Returns Promise<void | ResponseType>

      update, modify, change, edit, avatar, character

      const animationMeta = {
      "emote": { "loop": false, "x": 0, "y": 0, "hideLoop": true }
      }

      const spriteSheetJSON = {
      "animations": {
      "emote": [
      "emote/1.png"
      ]
      },
      "frames": {
      "emote/1.png": {
      "frame": {
      "x": 1911,
      "y": 778,
      "w": 58,
      "h": 91
      },
      "rotated": true,
      "trimmed": true,
      "spriteSourceSize": {
      "x": 50,
      "y": 33,
      "w": 58,
      "h": 91
      },
      "sourceSize": {
      "w": 159,
      "h": 159
      }
      }
      },
      "spriteSheetTypeMeta": {
      "nameplate": {
      "x": 0,
      "y": -70
      }
      },
      "meta": {
      "image": "spriteSheets%2FTvHNjgoMkiErDNSrVqHU%2FspriteSheet.png?alt=media",
      "format": "RGBA8888",
      "size": {
      "w": 2006,
      "h": 1099
      },
      "scale": "1"
      }
      }

      const formData = new FormData();
      formData.append('animationMeta', animationMeta);
      formData.append('name', "ExampleAvatarName");
      formData.append('spriteSheetJSON', spriteSheetJSON);
      formData.append('expression_dance', expression_dance);
      formData.append('expression_emote', expression_emote);
      formData.append('expression_sit', expression_sit);
      formData.append('expression_stand', expression_stand);
      formData.append('expression_transport', expression_transport);
      formData.append('preview', preview);
      formData.append('spriteSheet', spriteSheet);
      formData.append('unityPackage', unityPackage);
      await user.uploadAvatarFiles("exampleAvatarId", formData);

    Data Objects

    • Retrieves the data object for a visitor.

      Parameters

      • OptionalappPublicKey: string
      • OptionalappJWT: string
      • OptionalsharedAppPublicKey: string
      • OptionalsharedAppJWT: string

      Returns Promise<void | ResponseType>

      Returns the data object or an error response.

      get, fetch, retrieve, load, data, object, state

      const dataObject = await visitor.fetchDataObject();
      
    • Increments a specific value in the data object for a visitor by the amount specified. Must have valid interactive credentials from a visitor in the world.

      Parameters

      • path: string
      • amount: number
      • options: {
            analytics?: AnalyticType[];
            appJWT?: string;
            appPublicKey?: string;
            lock?: { lockId: string; releaseLock?: boolean };
            sharedAppJWT?: string;
            sharedAppPublicKey?: string;
        } = {}

      Returns Promise<void | ResponseType>

      Optionally, a lock can be provided with this request to ensure only one update happens at a time between all updates that share the same lock id

      increment, increase, add, count, data, object, state

      await visitor.incrementDataObjectValue("key", 1);
      
    • Sets the data object for a visitor.

      Parameters

      • dataObject: undefined | null | object
      • options: {
            analytics?: AnalyticType[];
            appJWT?: string;
            appPublicKey?: string;
            lock?: { lockId: string; releaseLock?: boolean };
            sharedAppJWT?: string;
            sharedAppPublicKey?: string;
        } = {}

      Returns Promise<void | ResponseType>

      set, assign, store, save, data, object, state

      Optionally, a lock can be provided with this request to ensure only one update happens at a time between all updates that share the same lock id

      await visitor.setDataObject(
      { itemsCollected: 0 },
      {
      analytics: [{ analyticName: "resets"} ],
      lock: { lockId: `${assetId}-${itemsCollected}-${new Date(Math.round(new Date().getTime() / 10000) * 10000)}` },
      },
      );

      const { itemsCollected } = visitor.dataObject;
    • Updates the data object for a visitor.

      Parameters

      • dataObject: object
      • options: {
            analytics?: AnalyticType[];
            appJWT?: string;
            appPublicKey?: string;
            lock?: { lockId: string; releaseLock?: boolean };
            sharedAppJWT?: string;
            sharedAppPublicKey?: string;
        } = {}

      Returns Promise<void | ResponseType>

      Optionally, a lock can be provided with this request to ensure only one update happens at a time between all updates that share the same lock id

      update, modify, change, edit, alter, data, object, state

      const theme = "exampleTheme";

      await visitor.updateDataObject({
      [`${theme}.itemsCollectedByUser`]: { [dateKey]: { count: 1 }, total: 1 },
      });

      const { exampleTheme } = visitor.dataObject;

    Dropped Assets

    • Retrieves ids of all dropped assets in all worlds with a matching interactivePublicKey.

      Parameters

      • interactivePublicKey: string

      Returns Promise<object | ResponseType>

      Returns the urlSlugs of worlds where the Public Key is found or an error response.

      get, fetch, retrieve, list, interactive worlds, public key

      await user.fetchInteractiveWorldsByKey("interactivePublicKeyExample");
      const interactiveWorlds = user.interactiveWorlds;

    Expressions

    • Get expressions

      Parameters

      • __namedParameters: { getUnlockablesOnly?: boolean; name?: string }

      Returns Promise<ResponseType>

      Returns an array of expressions or an error response.

      get, fetch, retrieve, list, expressions, emotes

      await visitor.getExpressions({ getUnlockablesOnly: true, });
      
    • Grant expression to a visitor by id or name.

      Parameters

      • __namedParameters: { id?: string; name?: string }

      Returns Promise<ResponseType>

      Returns { success: true } if the expression was granted successfully or an error response.

      grant, give, add, expression, emote

      await visitor.grantExpression({ id: "exampleExpressionId" });
      await visitor.grantExpression({ name: "exampleExpressionName" });

    Inventory

    • Grants an inventory item to this visitor.

      Parameters

      • item: InventoryItemInterface

        The InventoryItem to grant to the visitor

      • quantity: number = 1

        The quantity to grant (default: 1)

      Returns Promise<UserInventoryItem>

      Returns the granted UserInventoryItem with quantity and metadata.

      This method requires that the inventory item is already defined in your application's inventory system. Each visitor can only be granted an item once. Use modifyInventoryItemQuantity() to adjust quantities for items the visitor already owns. The grant_source will be set to track where the item came from.

      Important: This method will throw an error if the visitor already owns this inventory item. Check visitorInventoryItems first or use modifyInventoryItemQuantity() to update existing items.

      grant, give, add, inventory, item, visitor, award, reward

      // First create or fetch the inventory item
      const item = await InventoryItem.get("item-id-123");

      // Grant it to the visitor
      const userItem = await visitor.grantInventoryItem(item, 2);
      console.log(`Granted ${userItem.quantity} items to visitor`);

    NPCs

    • Creates an NPC (Non-Player Character) that follows this visitor using an inventory item the visitor owns.

      Parameters

      • userInventoryItemId: string

        The ID of the user's inventory item (must be an NPC type item owned by this visitor)

      • Optionaloptions: { showNameplate?: boolean }

        Optional configuration for the NPC

        • OptionalshowNameplate?: boolean

          Whether to display a nameplate above the NPC (default: true)

      Returns Promise<Visitor>

      Returns a Visitor object representing the created NPC. The NPC will automatically follow the visitor.

      One NPC is allowed per visitor, per application public key. NPCs are AI-controlled characters that automatically follow the visitor around the world. They appear as additional avatars and can be useful for companions, guides, or assistant characters.

      Requirements:

      • The visitor must own a user inventory item of type "npc"
      • The item must have been granted to the visitor before calling this method
      • Only one NPC can exist per visitor per app at a time

      create, spawn, add, npc, bot, follower, character, assistant, companion

      // First, grant the NPC item to the visitor
      const userItem = await visitor.grantInventoryItem(npcInventoryItem, 1);

      // Then create the NPC using the granted item
      const npc = await visitor.createNpc(userItem.id);

      // Or create without a nameplate
      const npc = await visitor.createNpc(userItem.id, { showNameplate: false });
    • Deletes the NPC (Non-Player Character) this app has assigned to this visitor.

      Returns Promise<void>

      Returns nothing if successful.

      This method removes the NPC associated with this visitor for the current application. The NPC will immediately disappear from the world. The underlying inventory item is not consumed and can be used to create a new NPC later.

      delete, remove, destroy, dismiss, despawn, npc, bot, follower, character

      // Check if NPC exists before deleting
      const npc = await visitor.getNpc();
      if (npc) {
      await visitor.deleteNpc();
      console.log('NPC removed successfully');
      }
    • Retrieves the NPC (Non-Player Character) associated with this visitor, if one exists.

      Returns Promise<null | Visitor>

      Returns a Visitor object representing the NPC, or null if none exists.

      Each visitor can have one NPC per application public key. NPCs are AI-controlled characters that follow the visitor around the world. They are created using inventory items of type "npc" and appear as additional avatars that track the visitor's position. If no NPC exists for this visitor and app, returns null.

      get, fetch, retrieve, npc, bot, follower, character, assistant, companion

      const npc = await visitor.getNpc();
      if (npc) {
      console.log(`NPC position: ${npc.position}`);
      console.log(`NPC ID: ${npc.id}`);
      } else {
      console.log('No NPC found for this visitor');
      }

    Other

    credentials: undefined | InteractiveCredentials
    dataObject?: null | object
    id: number
    jwt?: string
    profile?: Record<string, any>
    profileId?: null | string
    requestOptions: object
    topia: Topia
    urlSlug: string
    user?: User
    • get adminWorlds(): { [key: string]: World }

      Returns { [key: string]: World }

    • get assets(): { [key: string]: Asset }

      Returns { [key: string]: Asset }

    • get scenes(): { [key: string]: Scene }

      Returns { [key: string]: Scene }

    • get worlds(): { [key: string]: World }

      Returns { [key: string]: World }

    • Standardized error handler for all SDK operations.

      Parameters

      • __namedParameters: { error?: unknown; message?: string; params?: object; sdkMethod?: string }

      Returns {
          data: {};
          message: string;
          method: string;
          params: object;
          sdkMethod: undefined | string;
          stack: string;
          stackTrace: Error;
          status: number;
          success: boolean;
          url: string;
      }

      Standardized error object with properties: data, message, method, params, sdkMethod, stack, status, success, url

      This method processes errors from API calls and formats them consistently across the SDK. It extracts relevant error information including:

      • HTTP status codes and response data
      • Error messages from API responses
      • Stack traces for debugging
      • Request details (URL, method, parameters)

      All errors thrown by SDK methods flow through this handler to ensure consistent error format.

      error, exception, handler, debugging, api error, http error

    • Retrieves all inventory items owned by this visitor and app's key.

      Returns Promise<void>

      Returns an array of InventoryItem objects.

      get, fetch, retrieve, list, inventory, items, visitor

      const items = await visitor.fetchInventoryItems();
      
    • Get a single visitor from a world

      Returns Promise<void | ResponseType>

      Returns details for a visitor in a world by id and urlSlug

      get, fetch, retrieve, load, visitor, details

      await visitor.fetchVisitor();
      
    • Display a message via a toast to a visitor currently in a world.

      Parameters

      Returns Promise<void | ResponseType>

      Returns { success: true } or an error.

      toast, message, notification, alert, display, show, popup

      await visitor.fireToast({
      groupId: "custom-message",
      title: "Hello World",
      text: "Thank you for participating!",
      });
    • Teleport or walk a visitor currently in a world to a single set of coordinates.

      Parameters

      Returns Promise<void | ResponseType>

      Returns { success: true } if the visitor was moved successfully.

      move, teleport, walk, position, coordinate, location, place

      await visitor.moveVisitor({
      shouldTeleportVisitor: true,
      x: 100,
      y: 100,
      });
    • Send an email

      Parameters

      • __namedParameters: { html: string; subject: string; to: string }

      Returns Promise<object | ResponseType>

      Returns { success: true } if the email is sent successfully or an error response.

      send, email, message, notify

      const html = `<p><b>Hello World!</b></p><p>This email is being sent from via SDK.</p>`
      await user.sendEmail({ html, subject: "Example", to: "example@email.io" });
    • Setup signal to visitor

      Parameters

      • signal: any

      Returns Promise<void | ResponseType & { answerSignal: any }>

      signal, webrtc, answer, connect, p2p

      await visitor.sendSignalToVisitor(iceServers);
      
    • Returns the configured Axios instance for making API calls to Topia's Public API.

      Returns AxiosInstance

      The configured Axios client instance with authentication headers.

      All HTTP requests to the Topia API should use this method to ensure proper authentication headers and base URL configuration are applied.

      api, axios, http, request, client, public api

    • Mute and turn video off for a visitor currently in a world.

      Returns Promise<void | ResponseType>

      Returns { success: true } or an error.

      mute, video, av, turn off, disable

      await visitor.turnAVOff();
      
    • Update analytics for a given public key. Must have valid interactive credentials from a visitor in the world.

      Parameters

      Returns Promise<void | ResponseType>

      update, modify, change, edit, analytics, analytic, stats, statistics, data

      await visitor.updatePublicKeyAnalytics([{ analyticName: "joins", profileId, uniqueKey: profileId, urlSlug }]);
      

    Particle Effects

    • Get all particles available

      Returns Promise<ResponseType>

      Returns an array of particles or an error response.

      get, fetch, retrieve, list, particles, effects

      await visitor.getAllParticles();
      
    • Trigger a particle effect on a visitor

      Parameters

      • __namedParameters: { duration?: number; id?: string; name?: string }

      Returns Promise<string | ResponseType>

      Returns { success: true } or a message if no particleId is found.

      trigger, particle, effect, spawn, start, play

      await visitor.triggerParticle({ name: "Flame" });
      

    Scenes

    • Returns all scenes owned by User.

      Returns Promise<void | ResponseType>

      get, fetch, retrieve, list, user scenes

      await user.fetchScenes();
      const userScenes = user.scenes;

    Worlds

    • Retrieves all worlds a user with matching API Key is an admin in, creates a new World object for each, and creates new map of Worlds accessible via user.adminWorlds.

      Returns Promise<void | ResponseType>

      get, fetch, retrieve, list, admin worlds, user worlds

      await user.fetchAdminWorldsByKey();
      const adminWorlds = user.adminWorlds;
    • Retrieves all worlds owned by user with matching API Key, creates a new World object for each, and creates new map of Worlds accessible via user.worlds.

      Returns Promise<void | ResponseType>

      { urlSlug: new World({ apiKey, worldArgs, urlSlug }) }
      

      get, fetch, retrieve, list, user worlds

      await user.fetchWorldsByKey();
      const userWorlds = user.worlds;

    iframes

    • Close an iframe for a visitor currently in a world.

      Parameters

      • droppedAssetId: string

      Returns Promise<void | ResponseType>

      Returns { success: true } or an error.

      close, iframe, drawer, modal

      await visitor.closeIframe("droppedAssetId");
      
    • Open an iframe in a drawer or modal for a visitor currently in a world.

      Parameters

      Returns Promise<void | ResponseType>

      Returns { success: true } or an error.

      open, iframe, drawer, modal, link, url, website, web page

      await visitor.openIframe({
      droppedAssetId: "droppedAssetId",
      link: "https://topia.io",
      shouldOpenInDrawer: true,
      title: "Hello World",
      });
    • Reload an iframe for a visitor currently in a world.

      Parameters

      • droppedAssetId: string

      Returns Promise<void | ResponseType>

      Returns { success: true } or an error.

      reload, iframe, drawer, modal, link, url, website, web page

      await visitor.reloadIframe("droppedAssetId");