/**
 * Copyright (c) 2021 Expo, Inc.
 * Copyright (c) 2018 Drifty Co.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */ import plist from '@expo/plist' ; import Debug from 'debug' ; import type * as net from 'net' ; import type { ProtocolWriter } from './protocol' ; import { PlistProtocolReader , ProtocolClient , ProtocolReaderFactory } from './protocol' ; const debug = Debug ( 'expo:xdl:ios:lib:protocol:usbmux' ) ; export const USBMUXD_HEADER_SIZE = 16 ; export interface UsbmuxMessage { messageType : string ; extraFields ? : { [ key ] : any ; } ; } export class UsbmuxProtocolClient extends ProtocolClient < UsbmuxMessage > { constructor ( socket ) { super ( socket , new ProtocolReaderFactory ( UsbmuxProtocolReader ) , new UsbmuxProtocolWriter ( ) ) ; } } export class UsbmuxProtocolReader extends PlistProtocolReader { constructor ( callback ) { super ( USBMUXD_HEADER_SIZE , callback ) ; } parseHeader ( data ) { return data . readUInt32LE ( 0 ) - USBMUXD_HEADER_SIZE ; } parseBody ( data ) { const resp = super . parseBody ( data ) ; debug ( `Response: ${ JSON . stringify ( resp ) }` ) ; return resp ; } } export class UsbmuxProtocolWriter implements ProtocolWriter { private useTag = 0 ; write ( socket , msg ) { debug ( `socket write: ${ JSON . stringify ( msg ) }` ) ; const { messageType , extraFields } = msg ; const plistMessage = plist . build ( { BundleID : 'dev.expo.native-run' , ClientVersionString : 'usbmux.js' , MessageType : messageType , ProgName : 'native-run' , kLibUSBMuxVersion : 3 , ... extraFields } ) ; const dataSize = plistMessage ? plistMessage . length : 0 ; const protocolVersion = 1 ; const messageCode = 8 ; const header = Buffer . alloc ( USBMUXD_HEADER_SIZE ) ; header . writeUInt32LE ( USBMUXD_HEADER_SIZE + dataSize , 0 ) ; header . writeUInt32LE ( protocolVersion , 4 ) ; header . writeUInt32LE ( messageCode , 8 ) ; header . writeUInt32LE ( this . useTag ++ , 12 ) ; socket . write ( header ) ; socket . write ( plistMessage ) ; } }