agsamantha/node_modules/formdata-node/lib/esm/blobHelpers.js
2024-10-02 15:15:21 -05:00

75 lines
2.5 KiB
JavaScript

/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
import { isFunction } from "./isFunction.js";
const CHUNK_SIZE = 65536;
async function* clonePart(part) {
const end = part.byteOffset + part.byteLength;
let position = part.byteOffset;
while (position !== end) {
const size = Math.min(end - position, CHUNK_SIZE);
const chunk = part.buffer.slice(position, position + size);
position += chunk.byteLength;
yield new Uint8Array(chunk);
}
}
async function* consumeNodeBlob(blob) {
let position = 0;
while (position !== blob.size) {
const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
yield new Uint8Array(buffer);
}
}
export async function* consumeBlobParts(parts, clone = false) {
for (const part of parts) {
if (ArrayBuffer.isView(part)) {
if (clone) {
yield* clonePart(part);
}
else {
yield part;
}
}
else if (isFunction(part.stream)) {
yield* part.stream();
}
else {
yield* consumeNodeBlob(part);
}
}
}
export function* sliceBlob(blobParts, blobSize, start = 0, end) {
end !== null && end !== void 0 ? end : (end = blobSize);
let relativeStart = start < 0
? Math.max(blobSize + start, 0)
: Math.min(start, blobSize);
let relativeEnd = end < 0
? Math.max(blobSize + end, 0)
: Math.min(end, blobSize);
const span = Math.max(relativeEnd - relativeStart, 0);
let added = 0;
for (const part of blobParts) {
if (added >= span) {
break;
}
const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;
if (relativeStart && partSize <= relativeStart) {
relativeStart -= partSize;
relativeEnd -= partSize;
}
else {
let chunk;
if (ArrayBuffer.isView(part)) {
chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.byteLength;
}
else {
chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.size;
}
relativeEnd -= partSize;
relativeStart = 0;
yield chunk;
}
}
}