@ethersphere/bee-js
Version:
Javascript client for Bee
86 lines (85 loc) • 3.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamFiles = exports.streamDirectory = exports.hashDirectory = void 0;
const cafe_utility_1 = require("cafe-utility");
const __1 = require("..");
const manifest_1 = require("../manifest/manifest");
const chunk_size_1 = require("./chunk-size");
const collection_1 = require("./collection");
const mime_1 = require("./mime");
const typed_bytes_1 = require("./typed-bytes");
async function hashDirectory(_dir) {
throw new Error('Hashing directories is not supported in browsers!');
}
exports.hashDirectory = hashDirectory;
async function streamDirectory(_bee, _dir, _postageBatchId, _onUploadProgress, _options, _requestOptions) {
throw new Error('Streaming directories is not supported in browsers!');
}
exports.streamDirectory = streamDirectory;
async function streamFiles(bee, files, postageBatchId, onUploadProgress, options, requestOptions) {
const queue = new cafe_utility_1.AsyncQueue(64, 64);
let total = 0;
let processed = 0;
for (const file of files) {
total += (0, chunk_size_1.totalChunks)(file.size);
}
postageBatchId = new typed_bytes_1.BatchId(postageBatchId);
async function onChunk(chunk) {
await queue.enqueue(async () => {
await bee.uploadChunk(postageBatchId, chunk.build(), options, requestOptions);
onUploadProgress?.({ total, processed: ++processed });
});
}
const mantaray = new manifest_1.MantarayNode();
for (const file of files) {
const rootChunk = await new Promise((resolve, reject) => {
const tree = new cafe_utility_1.MerkleTree(onChunk);
let offset = 0;
const reader = new FileReader();
reader.onerror = () => {
reject(reader.error);
};
const readNextChunk = async () => {
if (offset >= file.size) {
const rootChunk = await tree.finalize();
resolve(rootChunk);
return;
}
const slice = file.slice(offset, offset + 4096);
reader.readAsArrayBuffer(slice);
};
reader.onload = async (event) => {
if (!event.target) {
reject('No event target');
return;
}
const data = event.target.result;
if (data) {
await tree.append(new Uint8Array(data));
offset += 4096;
}
readNextChunk();
};
readNextChunk();
});
await queue.drain();
const { filename, extension } = cafe_utility_1.Strings.parseFilename(file.name);
mantaray.addFork((0, collection_1.makeFilePath)(file), rootChunk.hash(), {
'Content-Type': maybeEnrichMime(mime_1.mimes[extension.toLowerCase()] || 'application/octet-stream'),
Filename: filename,
});
if (file.name === 'index.html') {
mantaray.addFork('/', __1.NULL_ADDRESS, {
'website-index-document': 'index.html',
});
}
}
return mantaray.saveRecursively(bee, postageBatchId, options, requestOptions);
}
exports.streamFiles = streamFiles;
function maybeEnrichMime(mime) {
if (['text/html', 'text/css'].includes(mime)) {
return `${mime}; charset=utf-8`;
}
return mime;
}