openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 6.73 kB
JavaScript
import{c as normalizeOptionalLowercaseString}from"./string-coerce-CpTFcSwY.mjs";import{R as resolveTimerTimeoutMs}from"./number-coercion-B3CfI447.mjs";import{p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{n as estimateBase64DecodedBytes,t as canonicalizeBase64}from"./base64-BbBj85Rq.mjs";import{d as normalizeMimeType,n as detectMime}from"./mime-ZmYZsEjx.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import"./http-body-CsPV_uT5.mjs";import{i as readResponseWithLimit,t as cancelUnreadResponseBody}from"./http-response-body-BJ35MG8h.mjs";import{i as fetchWithSsrFGuard}from"./fetch-guard-B_7-F5Lc.mjs";import{n as classifyAttachmentBytes}from"./attachment-classify-BWbx74Ae.mjs";import{t as parseMediaContentLength}from"./content-length-CJ-NwIug.mjs";import{r as convertHeicToJpeg}from"./image-ops-BYBI_WlA.mjs";import"./media-services-DAOLsxWe.mjs";import{t as extractPdfContent}from"./pdf-extract-B6xEOxRs.mjs";import{MIMEType}from"node:util";
//!src/media/input-files.ts
const NORMALIZED_INPUT_IMAGE_MIME=`image/jpeg`;const HEIC_INPUT_IMAGE_MIMES=/* @__PURE__ */ new Set([`image/heic`,`image/heif`]);function parseContentType(e){if(!e)return{};const t=normalizeMimeType(e);try{return{mimeType:t,charset:new MIMEType(e).params.get(`charset`)??void 0}}catch{return{mimeType:t}}}async function readInputSource(e,t,n,r){if(e.type===`base64`){const r=estimateBase64DecodedBytes(e.data);if(r>t.maxBytes)throw new Error(`${n===`input_image`?`Image`:`File`} too large: ${r} bytes (limit: ${t.maxBytes} bytes)`);const i=canonicalizeBase64(e.data);if(!i)throw new Error(`${n} base64 source has invalid 'data' field`);return{buffer:Buffer.from(i,`base64`),contentType:e.mediaType,canonicalData:i}}if(n===`input_image`&&e.type!==`url`)throw new Error(`Unsupported input_image source type: ${e.type}`);if(!t.allowUrl)throw new Error(`${n} URL sources are disabled by config`);const{response:i,release:a}=await fetchWithSsrFGuard({url:e.url,maxRedirects:t.maxRedirects,timeoutMs:t.timeoutMs,signal:r,policy:{allowPrivateNetwork:false,hostnameAllowlist:t.urlAllowlist},auditContext:`openresponses.${n}`,init:{headers:{"User-Agent":`OpenClaw-Gateway/1.0`}}});let o;try{if(!i.ok){await cancelUnreadResponseBody(i);throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`)}let e;try{e=parseMediaContentLength(i.headers.get(`content-length`))}catch(e){await cancelUnreadResponseBody(i);throw e}if(e!==null&&e>t.maxBytes){await cancelUnreadResponseBody(i);throw new Error(`Content too large: ${e} bytes (limit: ${t.maxBytes} bytes)`)}o={buffer:await readResponseWithLimit(i,t.maxBytes),contentType:i.headers.get(`content-type`)??void 0}}finally{await a()}r?.throwIfAborted();return o}function decodeTextContent(e,t,n){const r=normalizeOptionalLowercaseString(t)||`utf-8`;const i=Math.max(0,Math.floor(n));const decode=t=>{const n=new TextDecoder(t);let r=``;for(let t=0;t<e.length&&r.length<=i;t+=16384){const i=Math.min(t+16384,e.length);r+=n.decode(e.subarray(t,i),{stream:i<e.length})}const a=truncateUtf16Safe(r,i);return{text:a,...a.length<r.length?{metadata:{textTruncated:true,imagesTruncated:false}}:{}}};try{return decode(r)}catch{return decode(`utf-8`)}}async function normalizeInputImageBuffer(e){if(e.buffer.byteLength>e.limits.maxBytes)throw new Error(`Image too large: ${e.buffer.byteLength} bytes (limit: ${e.limits.maxBytes} bytes)`);const t=normalizeMimeType(e.mimeType)??`application/octet-stream`;const n=normalizeMimeType(await detectMime({buffer:e.buffer,headerMime:e.mimeType}));if(t.startsWith(`image/`)&&n&&!n.startsWith(`image/`))throw new Error(`Unsupported image MIME type: ${n}`);const r=(n?.startsWith(`image/`)?n:t).replace(/^(image\/hei[cf])-sequence$/,`$1`);if(!e.limits.allowedMimes.has(r))throw new Error(`Unsupported image MIME type: ${r}`);if(!HEIC_INPUT_IMAGE_MIMES.has(r))return{buffer:e.buffer,mimeType:r};const i=await convertHeicToJpeg(e.buffer);if(i.byteLength>e.limits.maxBytes)throw new Error(`Image too large after HEIC conversion: ${i.byteLength} bytes (limit: ${e.limits.maxBytes} bytes)`);return{buffer:i,mimeType:NORMALIZED_INPUT_IMAGE_MIME}}async function extractImageContentFromSource(e,t,n){n?.throwIfAborted();const{buffer:r,contentType:i,canonicalData:a}=await readInputSource(e,t,`input_image`,n);const o=await normalizeInputImageBuffer({buffer:r,mimeType:e.type===`base64`?normalizeMimeType(i)??`image/png`:parseContentType(i).mimeType,limits:t});n?.throwIfAborted();return{type:`image`,data:o.buffer===r&&a?a:o.buffer.toString(`base64`),mimeType:o.mimeType}}async function extractFileContentFromSource(e){const{source:t,limits:n,signal:r}=e;r?.throwIfAborted();const i=t.filename||`file`;const{buffer:a,contentType:o}=await readInputSource(t,n,`input_file`,r);const s=await extractFileContentFromBuffer({buffer:a,filename:i,mimeType:o,limits:n,...r?{signal:r}:{}});r?.throwIfAborted();return s}async function extractFileContentFromBuffer(e){const{buffer:t,limits:n}=e;e.signal?.throwIfAborted();const r=e.filename||`file`;if(t.byteLength>n.maxBytes)throw new Error(`File too large: ${t.byteLength} bytes (limit: ${n.maxBytes} bytes)`);const i=e.classification??await classifyAttachmentBytes({buffer:t,declaredMime:e.mimeType});e.signal?.throwIfAborted();const a=i.mime;const o=i.charset??e.charset??parseContentType(e.mimeType).charset;if(!a)throw new Error(`input_file missing media type`);if(!n.allowedMimes.has(a))throw new Error(`Unsupported file MIME type: ${a}`);if(a===`application/pdf`){const i=resolveTimerTimeoutMs(n.timeoutMs,1);const a=new AbortController;const o=e.signal?AbortSignal.any([e.signal,a.signal]):a.signal;o.throwIfAborted();const s=setTimeout(()=>a.abort(/* @__PURE__ */ new Error(`PDF extraction timed out after ${i}ms`)),i);let c;try{c=await racePromiseWithAbortSignal(()=>extractPdfContent({buffer:t,signal:o,maxPages:n.pdf.maxPages,maxPixels:n.pdf.maxPixels,minTextChars:n.pdf.minTextChars,...e.config?{config:e.config}:{},onImageExtractionError:e=>{logWarn(`media: PDF image extraction skipped, ${String(e)}`)}}),o,e=>toErrorObject(e.reason,`Input file extraction aborted`))}finally{clearTimeout(s)}const l=truncateUtf16Safe(c.text,n.maxChars);const u={...c.metadata,textTruncated:c.metadata?.textTruncated===true||l.length<c.text.length,imagesTruncated:c.metadata?.imagesTruncated===true};return{filename:r,text:l,images:c.images.length>0?c.images:void 0,metadata:u}}return{filename:r,...decodeTextContent(t,o,n.maxChars)}}export{normalizeInputImageBuffer as i,extractFileContentFromSource as n,extractImageContentFromSource as r,extractFileContentFromBuffer as t};