@@ -6,37 +6,33 @@ import { Buffer as BrowserBuffer } from "buffer";
66
77import type { Data } from "isomorphic-ws" ;
88
9- const { Buffer : PossibleBuiltInBuffer } = globalThis as Partial < {
10- Buffer : typeof Buffer ;
11- } > ;
12-
13- const BufferClassToUse = PossibleBuiltInBuffer ?? BrowserBuffer ;
14-
15- export class IsomorphicBuffer extends BufferClassToUse {
16- /**
17- * given a relatively unknown websocket frame data object,
18- * returns a valid Buffer instance that is safe to use
19- * isomorphically in any JS runtime environment
20- */
21- static async fromWebsocketData ( data : Data ) {
22- if ( typeof data === "string" ) {
23- return BufferClassToUse . from ( new TextEncoder ( ) . encode ( data ) . buffer ) ;
24- }
25- if ( data instanceof Blob ) {
26- // let the uncaught promise exception bubble up if there's an issue
27- return BufferClassToUse . from ( await data . arrayBuffer ( ) ) ;
28- }
29- if ( data instanceof ArrayBuffer ) return BufferClassToUse . from ( data ) ;
30- if ( Buffer . isBuffer ( data ) ) {
31- const arrBuffer = new ArrayBuffer ( data . length ) ;
32- const v = new Uint8Array ( arrBuffer ) ;
33- for ( const [ i , item ] of data . entries ( ) ) {
34- v [ i ] = item ;
35- }
36- return BufferClassToUse . from ( arrBuffer ) ;
37- }
38- throw new TypeError (
39- "unexpected event data type found when IsomorphicBuffer.fromWebsocketData() called" ,
40- ) ;
9+ const BufferClassToUse =
10+ "Buffer" in globalThis ? globalThis . Buffer : BrowserBuffer ;
11+
12+ /**
13+ * given a relatively unknown websocket frame data object,
14+ * returns a valid Buffer instance that is safe to use
15+ * isomorphically in any JS runtime environment
16+ */
17+ export async function bufferFromWebsocketData ( data : Data ) : Promise < Buffer > {
18+ if ( typeof data === "string" ) {
19+ return BufferClassToUse . from ( new TextEncoder ( ) . encode ( data ) . buffer ) ;
20+ }
21+
22+ if ( data instanceof BufferClassToUse ) return data ;
23+
24+ if ( data instanceof Blob ) {
25+ // let the uncaught promise exception bubble up if there's an issue
26+ return BufferClassToUse . from ( await data . arrayBuffer ( ) ) ;
4127 }
28+
29+ if ( data instanceof ArrayBuffer ) return BufferClassToUse . from ( data ) ;
30+
31+ if ( Array . isArray ( data ) ) {
32+ // an array of buffers is highly unlikely, but it is a possibility
33+ // indicated by the WebSocket Data interface
34+ return BufferClassToUse . concat ( data ) ;
35+ }
36+
37+ return data ;
4238}
0 commit comments