59 lines
2.7 KiB
JavaScript
59 lines
2.7 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());
|
||
|
});
|
||
|
};
|
||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||
|
};
|
||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||
|
exports.prepareWebsocketData = exports.prepareData = void 0;
|
||
|
const fetch_blob_1 = __importDefault(require("fetch-blob"));
|
||
|
const stream_1 = require("./stream");
|
||
|
/**
|
||
|
* Prepare data for valid input for node-fetch.
|
||
|
*
|
||
|
* node-fetch is not using WHATWG ReadableStream but NodeJS Readable so we need to convert in case of ReadableStream,
|
||
|
* but the typings are set to use ReadableStream so hence why type conversion here.
|
||
|
*
|
||
|
* @param data any string, ArrayBuffer, Uint8Array or Readable
|
||
|
*/
|
||
|
function prepareData(data) {
|
||
|
return __awaiter(this, void 0, void 0, function* () {
|
||
|
if (typeof data === 'string')
|
||
|
return new fetch_blob_1.default([data], { type: 'text/plain' });
|
||
|
if (data instanceof Uint8Array || data instanceof ArrayBuffer) {
|
||
|
return new fetch_blob_1.default([data], { type: 'application/octet-stream' });
|
||
|
}
|
||
|
if (data instanceof fetch_blob_1.default || (0, stream_1.isNodeReadable)(data))
|
||
|
return data;
|
||
|
if ((0, stream_1.isReadableStream)(data)) {
|
||
|
return (0, stream_1.readableWebToNode)(data);
|
||
|
}
|
||
|
throw new TypeError('unknown data type');
|
||
|
});
|
||
|
}
|
||
|
exports.prepareData = prepareData;
|
||
|
function isBufferArray(buffer) {
|
||
|
return Array.isArray(buffer) && buffer.length > 0 && buffer.every(data => data instanceof Buffer);
|
||
|
}
|
||
|
function prepareWebsocketData(data) {
|
||
|
return __awaiter(this, void 0, void 0, function* () {
|
||
|
if (typeof data === 'string')
|
||
|
return new TextEncoder().encode(data);
|
||
|
if (data instanceof Buffer)
|
||
|
return new Uint8Array(data);
|
||
|
if (data instanceof ArrayBuffer)
|
||
|
return new Uint8Array(data);
|
||
|
if (isBufferArray(data))
|
||
|
return new Uint8Array(Buffer.concat(data));
|
||
|
throw new TypeError('unknown websocket data type');
|
||
|
});
|
||
|
}
|
||
|
exports.prepareWebsocketData = prepareWebsocketData;
|