function isServerSentEvent(data) {
  return data.data !== void 0;
}
let clients = [];
const useServerEvents = () => {
  const send = (data) => {
    const id = Date.now();
    for (const client of clients) {
      sendData(id, client, data);
    }
  };
  const sendSingle = (clientId, data) => {
    const client = clients.find((c) => c.id === clientId);
    if (client) {
      const id = Date.now();
      sendData(id, client, data);
    }
  };
  const sendData = (id, client, data) => {
    client.response.write(`id: ${id}
`);
    if (typeof data === "string") client.response.write(`data: ${JSON.stringify(data)}

`);
    else if (isServerSentEvent(data)) {
      client.response.write(`data: ${JSON.stringify(data.data)}
`);
      if (data.event) client.response.write(`event: ${data.event}
`);
      if (data.retry) {
        client.response.write(`retry: ${data.retry}
`);
      }
      client.response.write("\n");
    }
    client.response.flushHeaders();
  };
  const addClient = (client) => {
    if (!clients.includes(client)) {
      clients.push(client);
    }
  };
  const close = (res) => {
    clients = clients.filter((client) => client.response !== res);
    res.end();
  };
  return { send, sendSingle, addClient, close };
};

export { useServerEvents as u };
//# sourceMappingURL=useServerEvents.mjs.map
