# If Condition

> Evalúa una condición booleana sobre el payload de entrada para bifurcar el flujo de ejecución.

Source: https://docs.sommatic.ai/es/nodes/flow.if/

- Slug: `flow.if`
- Familia: Control de flujo
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Evalúa una condición booleana sobre el payload de entrada para bifurcar el flujo de ejecución.

Este operador actúa como una compuerta que dirige la ejecución hacia el puerto 'true' o el puerto 'false' según el resultado de la expresión configurada. Admite dos modos de evaluación: el Sommatic AI Expression Engine (sintaxis {{ }}, JavaScript completo mediante vm.Script) como motor principal, y JSONata directo como alternativa más sencilla para las expresiones que se escriben sin {{ }}.

**Comportamiento:**
- Si la expresión da un valor verdadero (truthy), la ejecución continúa por el puerto 'true'.
- Si la expresión da un valor falso (falsy), la ejecución continúa por el puerto 'false'.
- Si 'treat_missing_as' está en true y la expresión devuelve undefined/null, el resultado se trata como falso.

## Configuración

- `expr` (string, obligatorio, acepta expresiones): Expresión que debe evaluarse como booleano. Enciérrala en {{ }} para usar el Sommatic AI Expression Engine (JavaScript) con variables como $json, $input o $("Node Name"), p. ej. {{ $json.age >= 18 }} o {{ $json.status === "active" }}. Sin {{ }}, el texto se evalúa como JSONata sobre el payload, donde los campos se referencian directamente: age >= 18 o status = "active". $json no existe en JSONata, así que $json.age >= 18 sin {{ }} siempre da false.
- `treat_missing_as` (boolean, opcional): Si está activado, cuando la expresión devuelve undefined o null la ejecución se dirige automáticamente al puerto False en lugar de lanzar un error. Por defecto: `false`.

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

- `true` (por defecto): Se activa cuando la expresión es verdadera.
- `false`: Se activa cuando la expresión es falsa.
- `error`: Se activa cuando falla la evaluación de la expresión.

## Contrato de entrada

- `payload` (object, opcional)

## Contrato de salida

- `payload` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("If Condition").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `If Condition`). **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 `true`, según la salida que muestra Puertos.

- `$("If Condition").item.json.payload` (object) **El worker no la devuelve: se lee como undefined.**
- `$("If Condition").item.json.order_id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("If Condition").item.json.amount` (number) = `1250` (El editor no la sugiere)
- `$("If Condition").item.json.status` (string) = `"active"` (El editor no la sugiere)


## Cómo funciona

Evalúa una condición y envía el payload sin cambios por `true` o `false`.

1. Resuelve `expr`: el Expression Engine evalúa un `{{ }}` (JavaScript en un contexto aislado, límite de 100 ms) con `$json`, `$("Node")`, `$now` y las demás variables del motor.
2. Si el valor resuelto es `undefined`, `null` o `""`, devuelve un sobre de error sin puerto (ver errores).
3. Un booleano se usa tal cual.
4. Una cadena se evalúa como JSONata sobre el payload, donde los campos se usan directamente: `amount > 1000`, `status = "active"`. Esto también aplica a un `{{ }}` que devolvió una cadena y a un `{{ }}` que falló en el motor (su texto se interpreta entonces como JSONata y falla).
5. Cualquier otro tipo (número, objeto, arreglo) no se puede compilar como JSONata y va a `error`.
6. Convierte el resultado con `!!result` y envía el payload por `true` o `false`, con `meta.evaluation` `{ expr, result, raw_result }` (`expr` es el texto original).

## En un workflow

### Nodo

```json
{
  "node_id": "node-high-value",
  "label": "High value?",
  "operator_slug": "flow.if",
  "operator_version": "1.0.0",
  "config": {
    "expr": "{{ $json.amount > 1000 }}",
    "treat_missing_as": false
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "amount": 1250,
    "status": "active"
  },
  "port": "true",
  "meta": {
    "evaluation": {
      "expr": "{{ $json.amount > 1000 }}",
      "result": true,
      "raw_result": true
    }
  }
}
```

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

### `true`

La condición es verdadera.

```json
{
  "order_id": "ord_123",
  "amount": 1250,
  "status": "active"
}
```

### `false`

La condición es falsa, incluidos los resultados `undefined` y `null` de JSONata.

```json
{
  "order_id": "ord_124",
  "amount": 80,
  "status": "active"
}
```

### `error`

La compilación o evaluación de JSONata falló.

```json
{
  "ok": false,
  "errors": [
    "Expression evaluation failed: path.charAt is not a function"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `expr`: Sin `{{ }}`, `$json` no está disponible en JSONata: `$json.amount > 1000` siempre es falso. Un `{{ }}` que devuelve una cadena, como `{{ $json.name }}`, se evalúa otra vez como ruta JSONata y casi siempre da falso.
- `treat_missing_as`: No tiene efecto visible: los resultados `undefined` y `null` siempre van a `false`, y en ningún caso se lanza un error.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing configuration: expr is required.` | `out` | `expr` está vacío o su `{{ }}` devolvió `undefined`, `null` o `""` (por ejemplo `{{ $json.flag }}` con un campo ausente). El sobre no tiene puerto, así que el motor lo envía a `out`, que este nodo no tiene: la rama se detiene sin aviso. Compara de forma explícita, por ejemplo `{{ $json.flag === true }}`. |
| `Expression evaluation failed: path.charAt is not a function` | `error` | El `{{ }}` devolvió un número, objeto o arreglo. Devuelve un booleano, por ejemplo `{{ $json.items.length > 0 }}`. |
| `Expression evaluation failed: <JSONata message>` | `error` | JSONata no válido, o un `{{ }}` con un error de JavaScript cuyo texto se interpretó luego como JSONata (por ejemplo `Expected ":", got "}"`). |

## Notas y límites

- `meta` solo queda en los pasos de la ejecución: los nodos siguientes reciben `data` como payload y no pueden leer `meta` con `$json` ni con `$("Node")`.
- 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": "flow.if",
  "name": "If Condition",
  "category": "flow",
  "description": "Evaluates a boolean condition against the input payload to bifurcate the execution flow.\n\n  This operator functions as a gateway that routes execution to either the 'true' or 'false' port based on the result of the configured expression. It supports two evaluation modes: the Sommatic AI Expression Engine ({{ }} syntax, full JavaScript via vm.Script) as the primary engine, and raw JSONata as a simpler fallback for expressions entered without {{ }}.\n\n  **Behavior:**\n  - If the expression evaluates to a truthy value, execution proceeds through the 'true' port.\n  - If the expression evaluates to a falsy value, execution proceeds through the 'false' port.\n  - If 'treat_missing_as' is set to true and the expression yields undefined/null, it is treated as false.",
  "capabilities": [
    "branching",
    "logic",
    "expression-engine",
    "jsonata"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "expr"
    ],
    "properties": {
      "expr": {
        "type": "string",
        "title": "Condition Expression",
        "description": "An expression that must evaluate to a boolean. Wrap it in {{ }} to use the Sommatic AI Expression Engine (JavaScript) with variables like $json, $input or $(\"Node Name\"), e.g. {{ $json.age >= 18 }} or {{ $json.status === \"active\" }}. Without {{ }} the text is evaluated as JSONata against the payload, where fields are referenced directly: age >= 18 or status = \"active\". $json is not bound in JSONata, so $json.age >= 18 without {{ }} always evaluates to false.",
        "format": "expression"
      },
      "treat_missing_as": {
        "type": "boolean",
        "title": "Treat Missing as False",
        "description": "If enabled, undefined or null results from the expression will automatically route to the False port instead of throwing an error.",
        "default": false
      },
      "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": "The JSON payload to be evaluated by the expression.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The original payload is passed through to the selected output port.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "true",
      "label": "True",
      "is_default": true,
      "supports_condition": true,
      "description": "Active when expression is true."
    },
    {
      "port_id": "false",
      "label": "False",
      "supports_condition": true,
      "description": "Active when expression is false."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Active when expression evaluation fails."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "logic",
    "condition",
    "branch",
    "control-flow"
  ],
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "expr"
  ],
  "properties": {
    "expr": {
      "type": "string",
      "title": "Condition Expression",
      "description": "An expression that must evaluate to a boolean. Wrap it in {{ }} to use the Sommatic AI Expression Engine (JavaScript) with variables like $json, $input or $(\"Node Name\"), e.g. {{ $json.age >= 18 }} or {{ $json.status === \"active\" }}. Without {{ }} the text is evaluated as JSONata against the payload, where fields are referenced directly: age >= 18 or status = \"active\". $json is not bound in JSONata, so $json.age >= 18 without {{ }} always evaluates to false.",
      "format": "expression"
    },
    "treat_missing_as": {
      "type": "boolean",
      "title": "Treat Missing as False",
      "description": "If enabled, undefined or null results from the expression will automatically route to the False port instead of throwing an error.",
      "default": false
    },
    "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": "The JSON payload to be evaluated by the expression.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The original payload is passed through to the selected output port.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "true",
    "label": "True",
    "is_default": true,
    "supports_condition": true,
    "description": "Active when expression is true."
  },
  {
    "port_id": "false",
    "label": "False",
    "supports_condition": true,
    "description": "Active when expression is false."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Active when expression evaluation fails."
  }
]
```
