> ## Documentation Index
> Fetch the complete documentation index at: https://docs.jelou.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Secretos

> Gestiona variables de entorno cifradas: tres modos para configurarlas, acceso con ctx.env, restricciones de prefijo y uso en CI.

## ¿Qué son los secrets?

Los secrets son variables de entorno cifradas que accedes en runtime a través de `ctx.env`. Úsalos para API keys, URLs de base de datos, tokens de servicios externos y cualquier valor sensible.

## Configurar secrets

Tienes tres formas de configurar secrets con el CLI:

<Tabs>
  <Tab title="Inline">
    Pasa pares `KEY=VALUE` directamente:

    ```bash theme={null}
    jelou secrets set consultar-cliente CRM_API_KEY=sk_test_EXAMPLE JELOU_API_KEY=jfn_pat_EXAMPLE
    # ✓ Set 2 secrets
    ```
  </Tab>

  <Tab title="Archivo .env">
    Importa desde un archivo `.env`:

    ```bash theme={null}
    jelou secrets set consultar-cliente --from-env .env.production
    ```

    El archivo sigue el formato estándar:

    ```bash .env.production theme={null}
    CRM_API_KEY=sk_test_EXAMPLE
    JELOU_API_KEY=jfn_pat_EXAMPLE
    DATABASE_URL=postgres://user:pass@host:5432/db
    ```

    Se ignoran líneas vacías y comentarios (`#`).
  </Tab>

  <Tab title="Interactivo">
    Sin argumentos, el CLI te guía paso a paso:

    ```bash theme={null}
    jelou secrets set consultar-cliente
    # ? Secret key: CRM_API_KEY
    # ? Secret value: ****
    # ? Add another secret? (y/N) y
    # ? Secret key: JELOU_API_KEY
    # ? Secret value: ****
    # ? Add another secret? (y/N) n
    # ✓ Set 2 secrets
    ```

    Los valores se enmascaran durante la entrada.
  </Tab>
</Tabs>

Las claves deben ser `UPPER_SNAKE_CASE` (patrón: `^[A-Z][A-Z0-9_]*$`).

## Acceder a secrets en tu función

Usa `ctx.env` dentro del handler:

```typescript index.ts theme={null}
import { define, z } from "@jelou/functions";

export default define({
  name: "enviar-whatsapp",
  description: "Envía un mensaje de WhatsApp usando la API de Jelou",
  input: z.object({
    telefono: z.string().min(10),
    mensaje: z.string().min(1),
  }),
  handler: async (input, ctx) => {
    const apiKey = ctx.env.get("JELOU_API_KEY");
    const botId = ctx.env.get("BOT_ID");

    if (!apiKey) {
      ctx.log("Error: JELOU_API_KEY no configurada");
      return { enviado: false, error: "API key faltante" };
    }

    const res = await fetch("https://api.jelou.ai/v1/messages/send", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        botId,
        phone: input.telefono,
        message: input.mensaje,
      }),
    });

    return { enviado: res.ok, status: res.status };
  },
});
```

### Métodos de `ctx.env`

| Método               | Retorna                  | Descripción                           |
| -------------------- | ------------------------ | ------------------------------------- |
| `ctx.env.get("KEY")` | `string \| undefined`    | Obtiene el valor de un secret         |
| `ctx.env.has("KEY")` | `boolean`                | Verifica si un secret existe          |
| `ctx.env.toObject()` | `Record<string, string>` | Obtiene todos los secrets como objeto |

## Variables bloqueadas

Las variables internas de la plataforma con prefijo `__FN_` están bloqueadas. Llamar a `ctx.env.get("__FN_COMPANY_ID")` retorna `undefined`.

## Desarrollo local

En desarrollo local, el servidor de `jelou functions dev` carga secrets desde tu archivo `.env`:

```bash .env theme={null}
CRM_API_KEY=sk-test-local123
JELOU_API_KEY=jfn_pat_test_local
DATABASE_URL=postgres://localhost:5432/mydb
```

Puedes especificar un archivo diferente:

```bash theme={null}
jelou functions dev --env .env.local
```

<Warning>
  Nunca subas tu archivo `.env` al repositorio. `jelou functions init` lo agrega automáticamente al `.gitignore`.
</Warning>

## Listar y eliminar secrets

```bash theme={null}
jelou secrets list consultar-cliente
# ▸ Key              Updated
# ▸ CRM_API_KEY      2 hours ago
# ▸ JELOU_API_KEY    3 days ago

jelou secrets delete consultar-cliente CRM_API_KEY
# ✓ Deleted CRM_API_KEY
```

## Secrets en CI/CD

En pipelines de CI, usa variables de entorno del sistema para inyectar secrets:

```yaml deploy.yml theme={null}
- name: Configure secrets and deploy
  env:
    JELOU_TOKEN: ${{ secrets.JELOU_TOKEN }}
  run: |
    jelou secrets set consultar-cliente \
      CRM_API_KEY=${{ secrets.CRM_API_KEY }} \
      JELOU_API_KEY=${{ secrets.JELOU_API_KEY }}
    jelou functions deploy --no-confirm
```
