biketrack-app/node_modules/@ethersphere/bee-js/dist/cjs/utils/data.browser.js

75 lines
3.2 KiB
JavaScript

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareWebsocketData = exports.prepareData = void 0;
const stream_1 = require("./stream");
/**
* Validates input and converts to Uint8Array
*
* @param data any string, ArrayBuffer or Uint8Array
*/
function prepareData(data) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof data === 'string')
return new Blob([data], { type: 'text/plain' });
if (data instanceof Uint8Array || data instanceof ArrayBuffer) {
return new Blob([data], { type: 'application/octet-stream' });
}
if (data instanceof Blob) {
return data;
}
// Currently it is not possible to stream requests from browsers
// there are already first experiments on this field (Chromium)
// but till it is fully implemented across browsers-land we have to
// buffer the data before sending the requests.
if ((0, stream_1.isNodeReadable)(data)) {
return new Promise(resolve => {
const buffers = [];
data.on('data', d => {
buffers.push(d);
});
data.on('end', () => {
resolve(new Blob(buffers, { type: 'application/octet-stream' }));
});
});
}
if ((0, stream_1.isReadableStream)(data)) {
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
const reader = data.getReader();
const buffers = [];
let done, value;
do {
;
({ done, value } = yield reader.read());
if (!done) {
buffers.push(value);
}
} while (!done);
resolve(new Blob(buffers, { type: 'application/octet-stream' }));
}));
}
throw new TypeError('unknown data type');
});
}
exports.prepareData = prepareData;
function prepareWebsocketData(data) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof data === 'string')
return new TextEncoder().encode(data);
if (data instanceof ArrayBuffer)
return new Uint8Array(data);
if (data instanceof Blob)
return new Uint8Array(yield new Response(data).arrayBuffer());
throw new TypeError('unknown websocket data type');
});
}
exports.prepareWebsocketData = prepareWebsocketData;