# Transform Data

> Transforma el payload de entrada con potentes expresiones JSONata.

Source: https://docs.sommatic.ai/es/nodes/data.transform/

- Slug: `data.transform`
- Familia: Datos
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Transforma el payload de entrada con potentes expresiones JSONata.

Es la herramienta principal para el mapeo de datos y la transformación estructural dentro del workflow. Permite reorganizar, filtrar y calcular nuevos valores a partir del JSON de entrada.

**Características:**
- Compatibilidad total con la sintaxis de JSONata.
- Acceso a todo el contexto del workflow.
- Capacidad para consultar y agregar datos.

**Casos de uso:**
- Mapear la respuesta de una API a un modelo interno.
- Filtrar elementos de una lista (p. ej., `items[price > 50]`).
- Calcular totales (p. ej., `$sum(items.price)`).

## Configuración

- `expr` (string, obligatorio, acepta expresiones): La expresión JSONata que se evalúa. El resultado se convierte en el payload de salida.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Resultado de la transformación
- `error`: La expresión falló

## Contrato de entrada

- `payload` (object, opcional)

## Contrato de salida

- `result` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Transform Data").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Transform Data`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Transform Data").item.json.result` (object) **El worker no la devuelve: se lee como undefined.**
- `$("Transform Data").item.json.id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("Transform Data").item.json.total` (number) = `42.5` (El editor no la sugiere)
- `$("Transform Data").item.json.lines` (number) = `2` (El editor no la sugiere)


## Cómo funciona

Evalúa una expresión JSONata sobre el payload de entrada; el resultado reemplaza el payload.

1. Resuelve la configuración: el Expression Engine evalúa primero los bloques `{{ }}` dentro de `expr`; el texto JSONata simple no se toca.
2. Falla cuando `expr` está vacío.
3. Si `expr` se resolvió a un objeto o arreglo (un `{{ }}` de valor completo que devuelve datos), ese valor es el resultado y no se usa JSONata.
4. Si no, compila la cadena como JSONata 2 y la evalúa con el payload como raíz: `order.total`, `$sum(items.price)`, `{ "id": order_id, "lines": $count(items) }`.
5. Devuelve el resultado como nuevo payload por `out`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-shape-order",
  "label": "Shape order",
  "operator_slug": "data.transform",
  "operator_version": "1.0.0",
  "config": {
    "expr": "{ \"id\": order_id, \"total\": $sum(items.price), \"lines\": $count(items) }"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "id": "ord_123",
    "total": 42.5,
    "lines": 2
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

La expresión se evaluó.

```json
{
  "id": "ord_123",
  "total": 42.5,
  "lines": 2
}
```

### `error`

`expr` está vacío o JSONata falló.

```json
{
  "ok": false,
  "errors": [
    "Transform Error: Unexpected end of expression"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `expr`: Las variables del Expression Engine no están disponibles dentro de JSONata: `$json.total` da undefined. Usa rutas del payload y funciones de JSONata (`$now()`, `$sum`, `$map`), o inserta valores del motor con `{{ }}` en texto mixto, que pone su forma de texto: `{ "run": "{{ $execution.id }}", "total": $sum(items.price) }`. Un `{{ }}` que falla en texto mixto se convierte en `[ERROR: <message>]` dentro de la expresión.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Transformation expression is required` | `error` | `expr` falta, o su `{{ }}` se resolvió a un valor vacío. |
| `Transform Error: <JSONata message>` | `error` | Error de sintaxis o de ejecución de JSONata, por ejemplo `Unexpected end of expression`. |
| `Transform Error: path.charAt is not a function` | `error` | Un `{{ }}` de valor completo devolvió un número o booleano, que no es texto JSONata ni datos. |

## Notas y límites

- Si el resultado es undefined (una ruta que no coincide con nada) o falsy, el motor guarda el sobre completo `{ ok, port }` como salida en lugar del resultado.
- El payload anterior se reemplaza; consulta datos anteriores con `{{ $("Node").item.json.field }}` en texto mixto.
- Cuando el sobre no trae `data` (o `data` es falsy), el motor guarda el sobre completo como salida del nodo: por `error` el siguiente nodo recibe `{ ok: false, errors: [...], port: "error" }` como payload.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.transform",
  "name": "Transform Data",
  "category": "data",
  "version": "1.0.0",
  "description": "Transforms the input payload using powerful JSONata expressions.\n\n  This is the primary tool for data mapping and structural transformation logic within the workflow. It allows you to reshape, filter, and mathematically compute new values from the input JSON.\n\n  **Features:**\n  - Full JSONata syntax support.\n  - Access to the entire workflow context.\n  - Capability to query and aggregate data.\n\n  **Use Cases:**\n  - Mapping an API response to an internal model.\n  - Filtering items from a list (e.g., `items[price > 50]`).\n  - Calculating totals (e.g., `$sum(items.price)`).",
  "capabilities": [
    "transform",
    "jsonata",
    "mapping",
    "utils"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "expr"
    ],
    "properties": {
      "expr": {
        "type": "string",
        "title": "Transformation Expression",
        "format": "expression",
        "description": "The JSONata expression to evaluate. The result becomes the output payload."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Any JSON payload.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The result of the JSONata evaluation.",
    "properties": {
      "result": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Output",
      "is_default": true,
      "description": "Transformation result"
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Expression failed"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "transform",
    "jsonata",
    "map"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "expr"
  ],
  "properties": {
    "expr": {
      "type": "string",
      "title": "Transformation Expression",
      "format": "expression",
      "description": "The JSONata expression to evaluate. The result becomes the output payload."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Any JSON payload.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The result of the JSONata evaluation.",
  "properties": {
    "result": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Output",
    "is_default": true,
    "description": "Transformation result"
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Expression failed"
  }
]
```
