# Responses and SSE

How HakoRun turns function output into JSON responses, and the event format of stream mode.

## Type Tagging

Non-stream mode returns `{"data": ..., "type": ...}`. The result is the first valid JSON line found scanning stdout from the bottom; without one, it is the full output after filtering Node.js warnings (`Warning:`, `ExperimentalWarning`, and similar).

| `type` | Condition | Example `data` |
|--------|-----------|----------------|
| `string` | JSON string | `"done"` |
| `number` | JSON number | `8` |
| `json` | JSON object, array, boolean, or `null` | `{"sum": 30}` |
| `text` | Not valid JSON | `hello world` |

## SSE Events

With `stream: true` the response uses `text/event-stream`, and each event is one `data: <JSON>` line:

```
data: {"event":"log","data":0,"type":"number"}

data: {"event":"result","data":"done","type":"string"}
```

| `event` | Sent When |
|---------|-----------|
| `log` | Each stdout line, once the next line arrives |
| `result` | The process exits normally; content is the last stdout line |
| `error` | Stderr output, timeout, client disconnect, or non-zero exit |

Each event's `type` follows the table above; newlines inside `result` / `error` are replaced with spaces.

## Completion and Abort

- After sending `result` or `error`, the server hijacks and closes the connection.
- The first stderr line triggers termination, with `error` reading `stopped to run script: <that line>`.
- On client disconnect, `error` is `stopped to run script: client disconnected` (the client never receives it).

## Related Pages

- [API Reference](/api-reference)
- [Script Runtime](/script-runtime)
