# JavaScript Module

* [Definition](#definicao)
  * [Usage possibilities](#usage-possibilities)
  * [Usage restrictions](#usage-restrictions)
* [Module configuration](#configuracao-do-modulo-transformacao-de-dados)
  * [Variable configuration](#variable-configuration)
  * [Result](#result)
* [Use examples](#use-examples)
  * [Synchronous Code with Two Parameters](#example-1-synchronous-code-with-two-parameters)
  * [Asynchronous Code with Promises](#example-2-asynchronous-code-with-promises)
  * [Creating a token using the signJwtToken function](#example-3-creating-a-token-using-the-signjwttoken-function)
  * [Decoding a token using the decodeJwtToken function](#example-4-decoding-a-token-using-the-decodejwttoken-function)
  * [Best Practices](#good-practices)

### **Definition** <a href="#definicao" id="definicao"></a>

The **"JavaScript"** tool module, a standard feature in **Skyone Studio** and available for use in any flow, enables the secure execution of JavaScript code within a controlled environment.

This module is ideal for transforming data, performing custom calculations, and executing other JavaScript-specific operations.

Below, you'll find the available features, usage restrictions, and practical examples of how to use this functionality.

#### ✅ Usage possibilities

* **Standard JavaScript code execution:** You can use all the standard JavaScript functionalities, including variable declarations, loops, conditionals, object manipulation and arrays.&#x20;
* **Asynchronous functions and Promises:** Support for async/await and Promises, allowing asynchronous operations such as simulated data requests or operations that rely on timers.&#x20;
* **Timers:**&#x20;
  * **setTimeout:** Available to schedule asynchronous operations after a specified delay.&#x20;
  * **clearTimeout:** Available to cancel timers created with setTimeout.&#x20;
* **String and number manipulation:** Use of global functions such as parseInt, parseFloat, Number, String, and others to manipulate numbers and strings.
* **Native JavaScript functions:** All native JavaScript functions, such as Math, Date, JSON, Array, Object, and RegExp, are available.
* **Memory**: You can use up to 60MB of memory to execute the code.

#### 🚫 Usage restrictions

* **Module Import:** It is not possible to import modules using require or import. This includes both native Node.js modules and third-party libraries, ensuring a secure and isolated environment.&#x20;
* **System Access:** There is no access to the file system, network, or other system-level operations that could compromise the security of **Skyone Studio**.
* **Process Handling:** Functions for manipulating processes, such as process.exit() and process.kill(), are not available.&#x20;
* **Restricted Keywords:** Certain keywords and operations, such as eval and Function, are restricted to prevent the execution of code that could escape the secure environment.&#x20;
* **Access to Global Variables:** The code executed is isolated from the global context, with no access to global variables external to the sandbox.

### Configuration of the JavaScript module <a href="#configuracao-do-modulo-transformacao-de-dados" id="configuracao-do-modulo-transformacao-de-dados"></a>

The "**JavaScript**" module appears in the **Tools** option when editing a flow. As soon as you click to add it, the modal opens for configuration:

<figure><img src="/files/bGwXVEWnjOrXhbzqrcxC" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
[Find out about the Module Header here](/english/skyone-studio/integrations/flows/module-header.md).
{% endhint %}

#### Variable Configuration

Fill in the following fields:

* **Key:** variable identifier
* **Value**: type or drag a variable
* **Type:** choose the most appropriate data type. Options are: text, number, boolean, object, and array.

<figure><img src="/files/q7bedTeXgzr5QcXDDo1I" alt=""><figcaption><p>Configuration example</p></figcaption></figure>

After completing the configurations, click "**Next**".

#### Result

On this screen, you can execute and view the data transformation information and manipulate it with JavaScript.

<figure><img src="/files/cVhubEzrIe0hBvug8eEe" alt=""><figcaption><p>"Result" screen</p></figcaption></figure>

#### Parameters&#x20;

All parameters are passed within the "data" field. In practice, this means that all parameters are within a "data" object, which can be accessed by the JavaScript code.

#### Structure and Content of data

* **Data Type:** "data" is a JSON object. This means it can contain key-value pairs, where the keys are strings and the values can be data types such as strings, numbers, arrays, objects, booleans, or null.&#x20;
* **Custom Fields:** The content of data is completely customizable and can contain any information the user’s code needs to function. There are no specific restrictions on the structure of the data, other than being JSON serializable.&#x20;

#### Examples of Fields:

* **Numbers and Strings:** Numeric or text values that can be used for calculations or manipulations.
* **Arrays and Objects:** More complex data structures that can contain lists of items or other nested objects.&#x20;
* **Configuration Data:** Specific configuration information that determines how the code should behave.

To finalize the module configuration, click "**Save**".[<br>](https://docs.integrasky.cloud/skyone/data/integrations/flows/tool-modules/csv-module)

### Use examples

#### **Example 1:** Synchronous Code with Two Parameters:

Imagine a scenario where we have two parameters. In this example, we will call them "number1" and "number2". We input the data and use the following code in JavaScript:

```javascript
function addNumbers(data) {
  return data.number1 + data.number2;
}
return addNumbers(data);
```

Next, we click "Run." The result will be the sum of the parameters, as shown in the image below:

<figure><img src="/files/l8Hjp6WjrOUUZGEso1xv" alt=""><figcaption></figcaption></figure>

#### **Example 2:** Asynchronous Code with **Promises:**

In this example, we will work with an asynchronous scenario using Promises in JavaScript.&#x20;

Imagine we want to process the data after a certain time. We will use two parameters, which are inside "data," and the function will return a Promise.&#x20;

The code below simulates an asynchronous operation using setTimeout to wait for one second before resolving the Promise with a message and the provided data, after clicking "Run":

```javascript
function fetchData(data) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ message: 'Data processed successfully', data });
}, 1000);
});
}

return fetchData(data);

```

The result can be seen in the image below:

<figure><img src="/files/5ET1nV39mcyUtI1zdZfB" alt=""><figcaption></figcaption></figure>

#### **Example 3:**  Creating a token using the signJwtToken function

In this example, we’ll demonstrate how to create a JWT token using the JavaScript module.\
To do this, we’ll use the `signJwtToken` function, provided directly within the module, which allows for practical and secure token generation.

The `signJwtToken` function requires the following parameters:

* **payload** (required | object): defines the body of the token, containing the data to be encoded.
* **secret** (required | string): the secret key used to sign and validate the token.
* **options** (optional | object): allows for additional token configuration. For more details on this parameter, refer to the documentation of the JavaScript library being used: [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken#readme).&#x20;

The `signJwtToken` function takes a *payload* (data we want to include in the token) and a secret key to sign the token.

\
**Usage** **example**

In the input data, you can configure a parameter or variable if needed. For instance:

<figure><img src="/files/G3ZvLYZ1zrsCwAjehYug" alt=""><figcaption></figcaption></figure>

Example of input data:

```json
{
  "data": {
    "payload": {
      "id": 1,
      "first_name": "Kristos",
      "last_name": "Amiranda",
      "email": "kamiranda0@hugedomains.com",
      "gender": "Male",
      "ip_address": "183.129.112.78"
    },
    "secret": "687398ee-8c99-48fe-93b5-5ade50d6e22f"
  }
}

```

We insert the code below into the JavaScript Code area:&#x20;

```javascript
const {payload, secret} = data;

return signJwtToken(payload, secret, {expiresIn: '1d'})
```

Considering that the parameters *payload* and *secret* are required, additional options can be included. In this example, we used *expiresIn*. To view other available options, [refer to the documentation](https://github.com/auth0/node-jsonwebtoken#readme).

After execution, the result can be seen in the image below:

<figure><img src="/files/DOMMXg1mm2nMfNK2mtjH" alt=""><figcaption></figcaption></figure>

In case of an error, the response will be different, as shown below:

<pre class="language-json"><code class="lang-json">{
	"error": "simulate error",
<strong>	"success": "false"
</strong>}
</code></pre>

#### Example 4: Decoding a token using the decodeJwtToken function

In this example, we will decode a JWT token to verify and access the data stored within it.&#x20;

We will use a function provided by the module called ***decodeJwtToken.*** This function requires two parameters:

* **token**: This field is required and must be a string. It represents the token to be decoded and verified.
* **secret**: This field is required and must be a string. It represents the secret key used to sign the token.

**Usage example**

For the input, we used the following data:

```json
{
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiZmlyc3RfbmFtZSI6IktyaXN0b3MiLCJsYXN0X25hbWUiOiJBbWlyYW5kYSIsImVtYWlsIjoia2FtaXJhbmRhMEBodWdlZG9tYWlucy5jb20iLCJnZW5kZXIiOiJNYWxlIiwiaXBfYWRkcmVzcyI6IjE4My4xMjkuMTEyLjc4IiwiaWF0IjoxNzM3NjQwNzk1LCJleHAiOjE3Mzc3MjcxOTV9.Isi8OlBpc-yUa5EsJa9IOA8wgmAFivgrn_pRClssVGE",
    "secret": "687398ee-8c99-48fe-93b5-5ade50d6e22f"
  }
}
```

We inserted the code below into the JavaScript Code area:

```javascript
const {token, secret} = data;

return decodeJwtToken(token, secret)
```

After execution, the result can be seen in the image below:

<figure><img src="/files/0stgMQyQsA5jwFUuymmn" alt=""><figcaption></figcaption></figure>

In case of an error, the response will be different, as shown below:

```json
{
    "error": "simulate error",
    "success": "false"
}
```

#### Best Practices

* **Input Validation:** Always validate input data to ensure correct code execution and avoid unexpected errors.&#x20;
* **Performance**: Avoid infinite loops or deep recursions that can cause excessive memory usage.&#x20;


---

# 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://docs.skyone.cloud/english/skyone-studio/integrations/flows/tool-modules/javascript-module.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.
