openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
102 lines (101 loc) • 3.07 kB
JavaScript
import "./path-guards-quCEQx1i.mjs";
import "./redact-BRF0hr6G.mjs";
import "./errors-hqLS1E8Y.mjs";
import { n as withResponseBodyTimeout, t as withResponseBodyIdleTimeout } from "./http-response-body-timeout-D-i9t_LZ.mjs";
import { channel } from "node:diagnostics_channel";
import { clearTimeout, setTimeout } from "node:timers";
//#region packages/normalization-core/src/response-bytes.ts
async function consumeResponseBytes(e) {
let t = 0;
while (true) {
const { done: n, value: r } = await e.read();
if (n) return {
size: t,
truncated: false
};
if (e.skipEmptyChunks !== false && !r?.length) continue;
const i = e.maxBytes - t;
t += r.length;
if (t > e.maxBytes || e.stopAtLimit && t === e.maxBytes) {
if (i > 0) e.onChunk(r.subarray(0, i));
await e.onLimit(t);
return {
size: t,
truncated: true
};
}
e.onChunk(r);
}
}
//#endregion
//#region src/infra/http-request-lifecycle.ts
const responseFinishDiagnostics = channel("http.server.response.finish");
//#endregion
//#region src/infra/http-response-body.ts
/** Requests cancellation only when no consumer has started reading the body. */
async function cancelUnreadResponseBody(e) {
if (e && !e.bodyUsed) e.body?.cancel().catch(() => void 0);
}
async function readResponsePrefix(e, t, n, r) {
if (!Number.isFinite(t) || t < 0) throw new RangeError(`maxBytes must be a non-negative finite number: ${t}`);
let i;
try {
i = typeof r?.timeoutMs === "function" ? r.timeoutMs() : r?.timeoutMs;
} catch (t) {
e.body?.cancel(t).catch(() => void 0);
throw t;
}
const a = e.body;
const o = a && typeof a.getReader === "function" ? a.getReader() : void 0;
try {
return await withResponseBodyTimeout({
timeoutMs: i,
onTimeout: r?.onTimeout,
signal: r?.signal,
cancel: async (e) => await (o ?? a)?.cancel(e),
read: async () => {
if (!o) {
const n = Buffer.from(await e.arrayBuffer());
const r = n.length > t;
return {
materializeBuffer: () => r ? n.subarray(0, t) : n,
size: n.length,
truncated: r
};
}
const i = [];
const a = await withResponseBodyIdleTimeout(o, r?.chunkTimeoutMs || void 0, r?.onIdleTimeout, (e) => consumeResponseBytes({
maxBytes: t,
stopAtLimit: n,
read: () => {
e?.();
return o.read();
},
onChunk: (e) => i.push(e),
onLimit: () => {
o.cancel().catch(() => void 0);
}
}));
return {
materializeBuffer: () => Buffer.concat(i, Math.floor(Math.min(a.size, t))),
...a
};
}
});
} finally {
o?.releaseLock();
}
}
/** Reads a response body under byte, idle, and overall timeout bounds. */
async function readResponseWithLimit(e, t, n) {
const r = n?.onOverflow;
const i = await readResponsePrefix(e, t, false, n);
if (i.truncated) throw r ? r({
size: i.size,
maxBytes: t,
res: e
}) : /* @__PURE__ */ new Error(`Content too large: ${i.size} bytes (limit: ${t} bytes)`);
return i.materializeBuffer();
}
//#endregion
export { readResponseWithLimit as n, cancelUnreadResponseBody as t };