All files index.ts

100% Statements 81/81
100% Branches 42/42
100% Functions 20/20
100% Lines 78/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 2441x                                 16x       1x               16x 10x         6x                                                 22x                           21x   1x         19x 1x 18x     1x 17x         19x 19x   8x 8x 8x   19x       19x     8x           10x     10x 10x 10x   10x             8x     10x   10x   25x 24x   2x 2x       22x 1x       21x 21x 21x   6x 6x         8x           19x   7x 19x   7x 7x   12x 11x 7x   4x                       6x     6x 6x   6x 6x 6x       8x 3x 5x 5x 5x       5x   5x         5x   4x 4x   4x 3x   4x       1x 1x           5x 5x 2x 5x     6x   6x      
import * as through2 from 'through2'
 
 
export interface HeadResult< StreamType >
{
	head: Uint8Array;
	stream: StreamType;
}
 
export interface Options
{
	bytes: number;
}
 
function isWhatwgStream( stream: NodeJS.ReadableStream | ReadableStream )
: stream is ReadableStream
{
	return typeof ( stream as ReadableStream ).getReader === 'function' &&
		typeof ( stream as ReadableStream ).pipeThrough === 'function';
}
 
export default function<
	StreamType extends NodeJS.ReadableStream | ReadableStream
>(
	readable: StreamType,
	opts: Options
)
: Promise< HeadResult< StreamType > >
{
	if ( isWhatwgStream( readable ) )
		return streamHeadWhatwg(
			readable as ReadableStream,
			opts.bytes
		) as any;
	else
		return streamHeadNode(
			readable as NodeJS.ReadableStream,
			opts.bytes
		) as any;
}
 
type TypedArray =
	| Int8Array
	| Uint8Array
	| Uint8ClampedArray
	| Int16Array
	| Uint16Array
	| Int32Array
	| Uint32Array
	| Float32Array
	| Float64Array;
 
type DataChunk =
	| TypedArray
	| ArrayBuffer
	| SharedArrayBuffer
	| DataView;
 
function isDataChunk( arr: any ): arr is DataChunk
{
	if (
		arr instanceof Int8Array
		|| arr instanceof Uint8Array
		|| arr instanceof Uint8ClampedArray
		|| arr instanceof Int16Array
		|| arr instanceof Uint16Array
		|| arr instanceof Int32Array
		|| arr instanceof Uint32Array
		|| arr instanceof Float32Array
		|| arr instanceof Float64Array
		|| arr instanceof ArrayBuffer
		|| arr instanceof SharedArrayBuffer
		|| arr instanceof DataView
	)
		return true;
 
	return false;
}
 
function ensureTypedArray( chunk: DataChunk ): TypedArray
{
	if ( chunk instanceof DataView )
		return new Uint8Array( chunk.buffer );
	else if (
		chunk instanceof ArrayBuffer || chunk instanceof SharedArrayBuffer
	)
		return new Uint8Array( chunk );
	return chunk;
}
 
function concat( chunks: Array< DataChunk > ): Uint8Array
{
	const arrays = chunks.map( chunk => ensureTypedArray( chunk ) );
	const len = arrays.reduce( ( prev, arr ) => prev + arr.byteLength, 0 );
 
	const ret = new Uint8Array( len );
	let offset = 0;
	for ( let arr of arrays )
	{
		ret.set(
			new Uint8Array( arr.buffer, arr.byteOffset, arr.byteLength ),
			offset
		);
		offset += arr.byteLength;
	}
 
	return ret;
}
 
function streamHeadWhatwg( readable: ReadableStream, bytes: number )
: Promise< HeadResult< ReadableStream > >
{
	return new Promise< HeadResult< ReadableStream > >(
		( resolve, reject ) =>
	{
		let bytesRead = 0;
		let isComplete = false;
		const chunks: Array< DataChunk > = [ ];
 
		const reader = readable.getReader( );
 
		function complete( )
		{
			/* istanbul ignore next */
			if ( isComplete )
				return null;
			isComplete = true;
		}
 
		( async ( ) =>
		{
			while ( true )
			{
				const { done, value: chunk } = await reader.read( );
				if ( done )
				{
					complete( );
					break;
				}
				else
				{
					if ( !isDataChunk( chunk ) )
						throw new TypeError(
							"Expecting chunk to be a typed array"
						);
 
					bytesRead += chunk.byteLength;
					chunks.push( chunk );
					if ( bytesRead >= bytes )
					{
						complete( );
						break;
					}
				}
			}
 
			resolve( {
				head: concat( chunks ),
				stream: new ReadableStream< any >( {
					start( ) { },
					async pull( controller )
					{
						if ( chunks.length > 0 )
						{
							chunks.forEach( chunk =>
									controller.enqueue( chunk )
							);
							chunks.length = 0;
							return;
						}
						const { done, value } = await reader.read( );
						if ( done )
							controller.close( );
						else
							controller.enqueue( value );
					}
				} ),
			} );
		} )( )
		.catch( reject );
	} );
}
 
function streamHeadNode( readable: NodeJS.ReadableStream, bytes: number )
: Promise< HeadResult< NodeJS.ReadableStream > >
{
	return new Promise< HeadResult< NodeJS.ReadableStream > >(
		( resolve, reject ) =>
	{
		const headStream = through2( onChunk, onEnd );
		const outputStream = through2( );
 
		let bytesRead = 0;
		let isComplete = false;
		const chunks: Array< Buffer > = [ ];
 
		function complete( )
		{
			if ( isComplete )
				return null;
			isComplete = true;
			const head = Buffer.concat( chunks );
			resolve( {
				head: new Uint8Array( head ),
				stream: outputStream,
			} );
			chunks.length = 0;
 
			return head;
		}
 
		function onChunk( chunk, encoding, callback )
		{
			if ( !isComplete )
			{
				chunks.push( chunk );
				bytesRead += chunk.length;
 
				if ( bytesRead >= bytes )
					this.push( complete( ) );
 
				return callback( );
			}
			else
			{
				this.push( chunk );
				return callback( );
			}
		}
 
		function onEnd( callback )
		{
			const head = complete( );
			if ( head )
				this.push( head );
			return callback( );
		}
 
		headStream.once( 'error', reject );
 
		readable.pipe( headStream ).pipe( outputStream );
	} );
}