# Getting Started

{% hint style="info" %}
If you want to start coding right away, you can checkout the [tutorial section](https://dev-stagecast.gitbook.io/moments-sdk/tutorials/my-first-moment) and come back here later.
{% endhint %}

## Introduction

The **Moments SDK** (also called **MDK**) is a client Javascript library that simplifies the development of Stagecast Moments (go to <https://www.stagecast.io/product-overview> for general overview)  by offering a set of APIs and tools.

The basic functionalities are:

1. **Wrap the http calls** made towards the Stagecast public API service;
2. **Wrap websocket messages** to be sent via Stagecast Messaging Service;
3. **Offer utilities** to inject ads/logos and translate page content into different languages;
4. Provide some **basic analytics library** to track the user activity;
5. **Support for multiple environments** to improve the testing flow both locally and on production. In particular, there are 3 main environments a moment can run:&#x20;
   * **`preview`** mode;&#x20;
   * **`staging`** mode;&#x20;
   * **`production`** mode;

## How To Use the MDK In Your Project

### 1. Import via CDN Link

Right now, the only supported way to import the Moment SDK, is via direct CDN link.&#x20;

```markup
<!-- Fetch the library code from the Stagecast CDN -->
<script src="https://stagecast.se/media/lib/mdk/stagecast.min.js"></script>
```

### 2. Create an instance of the SDK

```javascript
const SDK = new Stagecast(configObj);
```

The constructor accepts an optional configuration object. However, most of the times, a major part of the configuration will be only accessible at runtime. In the latter case, the library can be instantiated without parameters.

### 3. Register a callback for the `onConfigReceived` event

A Moment is usually run inside a wrapper **`Webview`** or an **`iframe`**.&#x20;

When the Moment gets loaded, the wrapper (ie. the Mobile App or an outer browser window) sends the runtime configuration to the Moment window.&#x20;

Once the MDK has done instantiating, the **`onConfigReceived`**&#x65;vent is fired. This event is always called after the **`window.onload`** and can be considered as the entry point for your web app.&#x20;

Of course, you can execute all the logic you want before the configuration is received. Usually the entry point is necessary to execute the runtime configurations that are only available only at last.

### 4. Example

A simple **`hello world`** Moment may look like the following:

{% tabs %}
{% tab title="index.html" %}

```markup
<html>

  <head>
    <title>Test the SDK</title>
  </head>
  <body>
    <h1>My Awesome Moment</h1>
  </body>
  <!-- Js Scripts Import -->
  <script src="https://stagecast.se/media/lib/mdk/stagecast.min.js"></script>
  <script src="./main.js"></script>
</html>
```

{% endtab %}

{% tab title="main.js" %}

```javascript
const SDK = new Stagecast();
SDK.onConfigReceived(yourCallback.bind(this)); 

async function yourCallback() {
  try {
    const {name, version} = await SDK.connection.getMomentClass();
    console.log(`My ${name} Moment with version ${version} has ben loaded!`); 
  } catch (err) {
    console.error('An error occurred: ', err.message);
  }
}

// My Awesome Moment with version 0.0.1 has been laoded!
```

{% endtab %}
{% endtabs %}

You can have a view at some demos here: <https://github.com/stagecast/moment-demos>.&#x20;

## The Configuration Object

The configuration object schema looks like the following:

```javascript
export interface SdkConfig {
  environment: string;
  token: string;
  userId: string;
  momentClassData: any;
  momentClassId: string;
  momentId: string;
  eventId: string;
  coordinates: string[];
  isGuest: boolean;
  isActive: boolean;
  isMomentActive: boolean;
  disableLogs: boolean;
}
```

**Fields**:&#x20;

* **`environment`**: the platform environment the Moment is running on (**production** or **staging**).
* **`token`**: the user token to authenticate against the backend API service.
* **`userId`**: the user email. It is generally used as a key to read and write to the Moment state. Each user has associated a bucket where the moment can save data.
* **`momentClassData`**: the moment custom data provided at runtime and set by event organizer.&#x20;
* **`momentClassId`**: the moment class id. Each moment belongs to a moment class which defines its basic characteristics (name, category, version etc...). A moment can be seen as an instance of a MomentClass.
* **`momentId`**: the moment id
* **`eventId`**: the id of the event in which the moment are launched.
* **`coordinates`**: the user latitude and longitude as provided by the device (if enabled by the user)
* **`isGuest`**: flag that specifies whether the user is registered to stagecast or it is guest user. You can implement different custom logics based on this flag. However, most users will be guests, as we have dropped user registrations.
* **`isActive`**: flag that specify whether the moment is currently live or has been stopped.&#x20;
* **`isMomentActive`**: same as above, kept for backward compatibility. Soon to be deprecated.
* **`disableLogs`**: a flag used to disable all the **`window.console`** methods.&#x20;

{% tabs %}
{% tab title="Example Configuration Message" %}

```javascript
document.getElementById("frame").contentWindow.postMessage({
"messageSource":"STAGECAST_SDK",
"config":{
  "environment": "staging",
  "userId": "user@stagecast.io",
  "token": "<temporary_user_token>",
  "momentClassData":{
    ...,
    // the property/values inside "custom" are totally 
    // up to the Moment developer
    "custom":{
      "contentList":[
         "7A955D3C-6E7C-42C5-BBD0-2B3196F91CFC"
       ],
      "gallerySize":100,
      "baseColorListHSL":[
        {"h":25,"s":0.7,"l":0.36},
        {"h":46,"s":0.7,"l":0.36},
        {"h":12,"s":0.7,"l":0.36}],
      "time": 10,
      "bigPicturePlacement": [0.5,0.5],
      "bigPictureSize": 0.6,
      "ads": ["A58885CD-F82A-443F-83E8-8CE81FB128F1"],
      "numAds": 2
    }
  },
  "momentClassId": "84B90A99-CF80-45A3-90A0-42E26ECEF633",
  "momentId": "34AB02BF-893A-4191-B4AB-DEE2E4931ECB",
  "created": 1573642962311,
  "eventId": "FC0C225F-CD0A-4B12-821C-0432DEC118CD",
  "disableLogs": false,
  "coordinates": ["0","0"],
  "isGuest": false,
  "isActive": true,
  "isMomentActive": true
}}, '*');
```

{% endtab %}
{% endtabs %}

**IMPORTANT NOTE**

{% hint style="warning" %}
If the **`momentClassData`**&#x66;ield is left empty, the Moment SDK will try to fetch the data saved under th&#x65;**`momentClassId`** key. This data is the one set in the moment configuration modal by the event organizer. If the field is not empty,  **`SDK.getMomentData()`**&#x77;ill return a copy of the object specified in the configuration without calling any external API.

The configuration modal can be accessed via the Stagecast organizer web dashboard.&#x20;
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dev-stagecast.gitbook.io/moments-sdk/undefined.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
