openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
153 lines (152 loc) • 4.43 kB
JavaScript
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./error-runtime-BM740gJj.mjs";
//#region extensions/document-extract/document-extractor.runtime.ts
const MAX_EXTRACTED_TEXT_CHARS = 2e5;
const MAX_RENDER_DIMENSION = 1e4;
let pdfEnginePromise = null;
async function loadPdfEngine() {
if (!pdfEnginePromise) pdfEnginePromise = import("clawpdf").then(({ createEngine: e }) => e()).catch((e) => {
pdfEnginePromise = null;
throw new Error("Dependency clawpdf is required for PDF extraction", { cause: e });
});
return pdfEnginePromise;
}
function toDocumentImage(e) {
return {
type: "image",
data: Buffer.from(e.buffer, e.byteOffset, e.byteLength).toString("base64"),
mimeType: "image/png"
};
}
function pageRenderOptions(e, t, n) {
if (!Number.isFinite(e) || !Number.isFinite(t) || e <= 0 || t <= 0) return null;
const r = Math.ceil(e * (96 / 72));
const i = Math.ceil(t * (96 / 72));
if (r <= MAX_RENDER_DIMENSION && i <= MAX_RENDER_DIMENSION && r * i <= n) return {
options: {
dpi: 96,
forms: true
},
reduced: false
};
const a = e >= t;
const o = a ? e : t;
const s = a ? t : e;
let c = 1;
let l = Math.min(MAX_RENDER_DIMENSION, Math.ceil(o * (96 / 72)));
let u = 1;
while (c <= l) {
const e = Math.floor((c + l) / 2);
if (e * Math.max(1, Math.ceil(s * (e / o))) <= n) {
u = e;
c = e + 1;
} else l = e - 1;
}
return {
options: a ? {
width: u,
forms: true
} : {
height: u,
forms: true
},
reduced: true
};
}
async function extractPdfContent(e, t) {
const n = await loadPdfEngine();
t.throwIfCancelled();
let r;
try {
r = e.password ? await n.open(e.buffer, { password: e.password }) : await n.open(e.buffer);
} catch (e) {
if (extractErrorCode(e) === "password") throw new Error("PDF requires a password or password is incorrect.", { cause: e });
throw e;
}
try {
t.throwIfCancelled();
const n = e.pageNumbers ? e.pageNumbers.filter((e) => Number.isInteger(e) && e >= 1 && e <= r.pageCount).slice(0, e.maxPages) : void 0;
if (e.pageNumbers?.length && n?.length === 0) throw new Error(`No requested PDF pages exist in this ${r.pageCount}-page document.`);
const i = n ?? Array.from({ length: Math.min(r.pageCount, e.maxPages) }, (e, t) => t + 1);
const a = {
pages: {
processed: i,
total: r.pageCount,
selection: e.pageNumbers ? "explicit" : "automatic",
truncated: e.pageNumbers ? e.pageNumbers.length > i.length : r.pageCount > e.maxPages
},
textTruncated: false,
imagesTruncated: false
};
const o = [];
let s = "";
for (const n of i) {
t.throwIfCancelled();
const i = r.page(n).text();
if (i.trim().length < e.minTextChars) o.push(n);
const c = s ? "\n\n" : "";
const l = MAX_EXTRACTED_TEXT_CHARS - s.length - c.length;
const u = truncateUtf16Safe(i, Math.max(0, l));
a.textTruncated ||= u.length < i.length;
if (u) s += c + u;
}
t.throwIfCancelled();
if (o.length === 0) return {
text: s,
images: [],
metadata: a
};
try {
const { encodePng: n, PdfError: i } = await import("clawpdf");
if (!Number.isFinite(e.maxPixels)) throw new i("budget", "maxPixels must be a finite positive number");
const c = [];
let l = e.maxPixels;
for (const [e, i] of o.entries()) {
t.throwIfCancelled();
if (l <= 0) {
a.imagesTruncated = true;
break;
}
const s = o.length - e;
const u = Math.max(1, Math.ceil(l / s));
const d = r.page(i);
const f = pageRenderOptions(d.width, d.height, u);
if (!f) {
a.imagesTruncated = true;
continue;
}
a.imagesTruncated ||= f.reduced;
const p = d.render(f.options);
t.throwIfCancelled();
const m = await t.runNativeSection(() => n(p.rgba, {
width: p.width,
height: p.height
}));
t.throwIfCancelled();
c.push(toDocumentImage(m));
l -= p.width * p.height;
}
return {
text: s,
images: c,
metadata: a
};
} catch (n) {
t.throwIfCancelled();
a.imagesTruncated = true;
e.onImageExtractionError?.(n);
if (!s.trim()) throw new Error("PDF image extraction failed with no extractable text.", { cause: n });
return {
text: s,
images: [],
metadata: a
};
}
} finally {
r.destroy();
}
}
//#endregion
export { extractPdfContent as t };