UNPKG

@whisklabs/grpc

Version:

gRPC generator and http library for typescript

79 lines 2.84 kB
// tslint:disable: no-bitwise import { isFunction } from '@whisklabs/typeguards'; import { HEADER_SIZE } from './utils'; function decodeASCII(input) { var str = ''; // eslint-disable-next-line @typescript-eslint/prefer-for-of for (var i = 0; i < input.length; i++) { str += String.fromCharCode(input[i]); } return str; } var parseHttpHeaders = function (str) { var chunks = String(str !== null && str !== void 0 ? str : '') .trim() .split('\r\n'); var headers = {}; for (var _i = 0, chunks_1 = chunks; _i < chunks_1.length; _i++) { var chunk = chunks_1[_i]; var pos = chunk.indexOf(':'); headers[chunk.substring(0, pos).trim()] = chunk.substring(pos + 1).trim(); } return headers; }; var isTrailerHeader = function (headerView) { return (headerView.getUint8(0) & 0x80) === 0x80; }; var readLengthFromHeader = function (headerView) { return headerView.getUint32(1, false); }; var hasEnoughBytes = function (buffer, position, byteCount) { return buffer.byteLength - position >= byteCount; }; function sliceUint8Array(buffer, from, to) { if (isFunction(buffer.slice)) { return buffer.slice(from, to); } var end = buffer.length; if (to !== undefined) { end = to; } var num = end - from; var array = new Uint8Array(num); var arrayIndex = 0; for (var i = from; i < end; i++) { array[arrayIndex++] = buffer[i]; } return array; } export var ChunkType; (function (ChunkType) { ChunkType[ChunkType["MESSAGE"] = 1] = "MESSAGE"; ChunkType[ChunkType["TRAILERS"] = 2] = "TRAILERS"; })(ChunkType || (ChunkType = {})); export function chunkParse(buffer, flush) { if (buffer.length === 0 && flush === true) { return []; } var position = 0; var chunkData = []; while (true) { if (!hasEnoughBytes(buffer, position, HEADER_SIZE)) { return chunkData; } var headerBuffer = sliceUint8Array(buffer, position, position + HEADER_SIZE); var headerView = new DataView(headerBuffer.buffer, headerBuffer.byteOffset, headerBuffer.byteLength); var msgLength = readLengthFromHeader(headerView); if (!hasEnoughBytes(buffer, position, HEADER_SIZE + msgLength)) { return chunkData; } var messageData = sliceUint8Array(buffer, position + HEADER_SIZE, position + HEADER_SIZE + msgLength); position += HEADER_SIZE + msgLength; if (isTrailerHeader(headerView)) { chunkData.push({ chunkType: ChunkType.TRAILERS, trailers: parseHttpHeaders(decodeASCII(messageData)), }); } else { chunkData.push({ chunkType: ChunkType.MESSAGE, data: messageData }); } } } //# sourceMappingURL=parser.js.map