import { isObject } from "./functions.js";
const readLogStream = async (serverAddress, fetchArgs, onError, onEvent) => {
  var _a;
  try {
    const options = isObject(fetchArgs.options) ? fetchArgs.options : {};
    if (process.env.IS_DEV)
      options.credentials = "include";
    const response = await fetch(serverAddress(fetchArgs.url), options);
    if (!response.ok) {
      const body = await response.json();
      const e = new Error((_a = body == null ? void 0 : body.error) == null ? void 0 : _a.message);
      onError(e);
      return;
    }
    if (!response.body)
      return onError(`Unable to fetch stream from ${fetchArgs.url}.`);
    const decoder = new TextDecoder();
    const reader = response.body.getReader();
    let buffer = "";
    let isCancelled = false;
    if (options == null ? void 0 : options.signal) {
      const signal = options.signal;
      const abortHandler = () => {
        signal.removeEventListener("abort", abortHandler);
        isCancelled = true;
      };
      signal.addEventListener("abort", abortHandler);
    }
    const handleStreamError = (e) => onError(e);
    const handleStreamLine = (line) => {
      if (isCancelled)
        return;
      try {
        const ndjson = JSON.parse(line);
        if (ndjson.error) {
          onError(ndjson.error);
        } else {
          onEvent == null ? void 0 : onEvent(ndjson.result);
        }
      } catch {
      }
    };
    const handleStreamRead = (result) => {
      if (isCancelled)
        return;
      if (result.done) {
        buffer = buffer.trim();
        if (buffer.length !== 0)
          handleStreamLine(buffer);
        return;
      }
      buffer += decoder.decode(result.value, { stream: true });
      const lines = buffer.split("\n");
      for (let i = 0; i < lines.length - 1; ++i) {
        const line = lines[i].trim();
        if (line.length === 0)
          continue;
        handleStreamLine(line);
      }
      buffer = lines[lines.length - 1];
      return reader.read().then(handleStreamRead).catch(handleStreamError);
    };
    return reader.read().then(handleStreamRead).catch(handleStreamError);
  } catch (e) {
    onError(e);
  }
};
export {
  readLogStream
};
