// src/runtime/util.ts
async function deleteBoxSafe(box) {
  if (!box || typeof box.delete !== "function") return true;
  try {
    await box.delete();
    return true;
  } catch {
    return false;
  }
}
function randomSuffix(len = 8) {
  return Math.random().toString(36).slice(2, 2 + len);
}
function randomUuid() {
  return crypto.randomUUID();
}
function abortError() {
  const err = new Error("aborted");
  err.name = "AbortError";
  return err;
}
function throwAbort() {
  throw abortError();
}
function throwIfAborted(signal) {
  if (signal?.aborted) throw abortError();
}
function isAbortError(err) {
  return err instanceof Error && err.name === "AbortError";
}
function sleep(ms, signal) {
  return new Promise((resolve) => {
    if (signal?.aborted) {
      resolve();
      return;
    }
    let onAbort;
    const timer = setTimeout(() => {
      if (onAbort && signal) signal.removeEventListener("abort", onAbort);
      resolve();
    }, ms);
    if (signal) {
      onAbort = () => {
        clearTimeout(timer);
        resolve();
      };
      signal.addEventListener("abort", onAbort, { once: true });
    }
  });
}
function withTimeout(promise, ms) {
  return new Promise((resolve) => {
    const timer = setTimeout(() => resolve(void 0), ms);
    promise.then(
      (value) => {
        clearTimeout(timer);
        resolve(value);
      },
      () => {
        clearTimeout(timer);
        resolve(void 0);
      }
    );
  });
}
function stringifySafe(value, opts = {}) {
  let s;
  try {
    if (typeof value === "string") {
      s = value;
    } else {
      const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
      s = json ?? String(value);
    }
  } catch {
    s = String(value);
  }
  if (opts.max !== void 0 && s.length > opts.max) return `${s.slice(0, opts.max)}\u2026`;
  return s;
}
function zeroTokenUsage() {
  return { input: 0, output: 0 };
}
function addTokenUsage(acc, delta) {
  acc.input += delta.input ?? 0;
  acc.output += delta.output ?? 0;
}
async function mapWithConcurrency(items, limit, fn) {
  const bound = Math.max(1, Math.floor(limit));
  const results = new Array(items.length);
  let next = 0;
  let failed = false;
  const worker = async () => {
    while (!failed) {
      const i = next;
      next += 1;
      if (i >= items.length) return;
      try {
        results[i] = await fn(items[i], i);
      } catch (err) {
        failed = true;
        throw err;
      }
    }
  };
  const workerCount = Math.min(bound, items.length);
  await Promise.all(Array.from({ length: workerCount }, () => worker()));
  return results;
}

export {
  deleteBoxSafe,
  randomSuffix,
  randomUuid,
  throwAbort,
  throwIfAborted,
  isAbortError,
  sleep,
  withTimeout,
  stringifySafe,
  zeroTokenUsage,
  addTokenUsage,
  mapWithConcurrency
};
//# sourceMappingURL=chunk-3MDZX7YU.js.map