All files / src/PerfectWSAdvanced/transform TransformBinaryData.ts

82% Statements 123/150
84% Branches 42/50
100% Functions 8/8
82% Lines 123/150

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 1862x               2x 42x   42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x   42x   42x 2952x 2952x 2952x 2952x 1729x 1729x 1729x 2952x 2952x 2952x   42x 3037x 3037x 3037x 15657x 15657x   1729x 1729x     15657x 15657x 15657x 15657x 15657x 15657x 3037x 3037x   42x 1729x 1275x 1275x   1729x 454x 454x 454x       454x   1729x                                             1729x   42x 1729x 1547x 1547x   1359x 11x 11x   1359x 13x 13x   158x 1359x       1359x 1729x   1729x 139x 139x 139x 139x 139x 139x   19x 19x 1729x   42x 15657x 155850x 154121x 154121x   1729x   155850x 1547x 1547x 182x 42x 42x 140x 11x 11x 129x 129x 129x         1729x 1729x   13928x 15657x 42x    
import { transformSendDeserializeType, transformSendRecursive } from './utils/changeType.js';
 
/**
 * Transforms binary data types to maintain their interface through BSON serialization.
 * Works in both Node.js (with Buffer) and browser environments (TypedArrays only).
 * Supports: Buffer (Node.js), TypedArrays, ArrayBuffer, DataView
 */
 
export class TransformBinaryData {
    private static readonly HAS_BUFFER = typeof Buffer !== 'undefined';
 
    private static readonly TYPES: Record<string, any> = {
        ...(TransformBinaryData.HAS_BUFFER ? { Buffer } : {}),
        Uint8Array,
        Uint16Array,
        Uint32Array,
        Int8Array,
        Int16Array,
        Int32Array,
        Float32Array,
        Float64Array,
        ArrayBuffer,
        DataView
    };
 
    private static readonly BYTES_PER_ELEMENT: Record<string, number> = {
        Buffer: 1,
        Uint8Array: 1,
        Int8Array: 1,
        Uint16Array: 2,
        Int16Array: 2,
        Uint32Array: 4,
        Int32Array: 4,
        Float32Array: 4,
        Float64Array: 8,
        ArrayBuffer: 1,
        DataView: 1
    };
 
    private static readonly ALIGNMENTS: Record<string, number> = {
        Uint16Array: 2,
        Int16Array: 2,
        Uint32Array: 4,
        Int32Array: 4,
        Float32Array: 4,
        Float64Array: 8
    };
 
    constructor(private _maxDepth = 100) { }
 
    deserialize(data: any) {
        return transformSendDeserializeType(
            data,
            'binaryData',
            ({ type, data: binaryData }) => {
                const bytes = this._extractBytes(binaryData);
                return this._restoreType(type, bytes);
            },
            this._maxDepth
        );
    }
 
    serialize(obj: any) {
        return transformSendRecursive(obj, {
            maxDepth: this._maxDepth,
            transformData: data => {
                const detected = this._detectBinaryType(data);
                if (!detected) return null;
 
                const binaryData = TransformBinaryData.HAS_BUFFER
                    ? Buffer.from(detected.bytes)
                    : detected.bytes;
 
                return {
                    ___type: 'binaryData',
                    type: detected.type,
                    data: binaryData
                };
            }
        });
    }
 
    private _extractBytes(data: any): Uint8Array {
        if (TransformBinaryData.HAS_BUFFER && Buffer.isBuffer(data)) {
            return new Uint8Array(data.buffer, data.byteOffset, data.length);
        }
 
        if (data?.buffer) {
            if (TransformBinaryData.HAS_BUFFER && Buffer.isBuffer(data.buffer)) {
                return new Uint8Array(data.buffer.buffer, data.buffer.byteOffset, data.buffer.length);
            }
            if (data.buffer instanceof ArrayBuffer) {
                return new Uint8Array(data.buffer);
            }
        }
 
        if (data?.constructor?.name === 'Binary') {
            const buf = data.buffer || data;
            if (buf instanceof ArrayBuffer) {
                return new Uint8Array(buf);
            }
            if (TransformBinaryData.HAS_BUFFER) {
                return new Uint8Array(Buffer.from(buf));
            }
        }
 
        if (data instanceof Uint8Array) {
            return data;
        }
 
        if (data instanceof ArrayBuffer) {
            return new Uint8Array(data);
        }
 
        if (TransformBinaryData.HAS_BUFFER) {
            return new Uint8Array(Buffer.from(data));
        }
 
        return new Uint8Array(data);
    }
 
    private _restoreType(type: string, bytes: Uint8Array): any {
        if (type === 'Buffer' && TransformBinaryData.HAS_BUFFER) {
            return Buffer.from(bytes);
        }
 
        if (type === 'ArrayBuffer') {
            return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length);
        }
 
        if (type === 'DataView') {
            return new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
        }
 
        const Constructor = TransformBinaryData.TYPES[type];
        if (!Constructor) {
            return bytes;
        }
 
        const alignment = TransformBinaryData.ALIGNMENTS[type] || 1;
        const bytesPerElement = TransformBinaryData.BYTES_PER_ELEMENT[type] || 1;
 
        if (bytes.byteOffset % alignment === 0) {
            return new Constructor(
                bytes.buffer,
                bytes.byteOffset,
                bytes.length / bytesPerElement
            );
        }
 
        const alignedBytes = new Uint8Array(bytes);
        return new Constructor(alignedBytes.buffer);
    }
 
    private _detectBinaryType(data: any): { type: string; bytes: Uint8Array; } | null {
        for (const [typeName, Constructor] of Object.entries(TransformBinaryData.TYPES)) {
            if (!(data instanceof Constructor)) {
                continue;
            }
 
            let bytes: Uint8Array;
 
            if (typeName === 'Buffer' && TransformBinaryData.HAS_BUFFER) {
                bytes = new Uint8Array(data.buffer, data.byteOffset, data.length);
            }
            else if (data instanceof Uint8Array && !(TransformBinaryData.HAS_BUFFER && data instanceof Buffer)) {
                bytes = data;
            }
            else if (data instanceof ArrayBuffer) {
                bytes = new Uint8Array(data);
            }
            else if (data.buffer && data.byteOffset !== undefined && data.byteLength !== undefined) {
                bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
            }
            else {
                continue;
            }
 
            return { type: typeName, bytes };
        }
 
        return null;
    }
}